blob: 66b9082b2a0289dcf16d504e603973f28c8afc07 [file] [log] [blame]
David L. Jonesf561aba2017-03-08 01:02:16 +00001//===--- LLVM.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Clang.h"
11#include "Arch/AArch64.h"
12#include "Arch/ARM.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
Alex Bradbury71f45452018-01-11 13:36:56 +000015#include "Arch/RISCV.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000016#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Arch/X86.h"
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +000019#include "AMDGPU.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000020#include "CommonArgs.h"
21#include "Hexagon.h"
22#include "InputInfo.h"
23#include "PS4CPU.h"
24#include "clang/Basic/CharInfo.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000028#include "clang/Driver/DriverDiagnostic.h"
29#include "clang/Driver/Options.h"
30#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000031#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000032#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000033#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000034#include "llvm/Option/ArgList.h"
35#include "llvm/Support/CodeGen.h"
36#include "llvm/Support/Compression.h"
37#include "llvm/Support/FileSystem.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Process.h"
Eric Christopher53b2cb72017-06-30 00:03:56 +000040#include "llvm/Support/TargetParser.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000041#include "llvm/Support/YAMLParser.h"
42
43#ifdef LLVM_ON_UNIX
44#include <unistd.h> // For getuid().
45#endif
46
47using namespace clang::driver;
48using namespace clang::driver::tools;
49using namespace clang;
50using namespace llvm::opt;
51
52static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
53 if (Arg *A =
54 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
55 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
56 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
57 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
58 << A->getBaseArg().getAsString(Args)
59 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
60 }
61 }
62}
63
64static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
65 // In gcc, only ARM checks this, but it seems reasonable to check universally.
66 if (Args.hasArg(options::OPT_static))
67 if (const Arg *A =
68 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
69 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
70 << "-static";
71}
72
73// Add backslashes to escape spaces and other backslashes.
74// This is used for the space-separated argument list specified with
75// the -dwarf-debug-flags option.
76static void EscapeSpacesAndBackslashes(const char *Arg,
77 SmallVectorImpl<char> &Res) {
78 for (; *Arg; ++Arg) {
79 switch (*Arg) {
80 default:
81 break;
82 case ' ':
83 case '\\':
84 Res.push_back('\\');
85 break;
86 }
87 Res.push_back(*Arg);
88 }
89}
90
91// Quote target names for inclusion in GNU Make dependency files.
92// Only the characters '$', '#', ' ', '\t' are quoted.
93static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
94 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
95 switch (Target[i]) {
96 case ' ':
97 case '\t':
98 // Escape the preceding backslashes
99 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
100 Res.push_back('\\');
101
102 // Escape the space/tab
103 Res.push_back('\\');
104 break;
105 case '$':
106 Res.push_back('$');
107 break;
108 case '#':
109 Res.push_back('\\');
110 break;
111 default:
112 break;
113 }
114
115 Res.push_back(Target[i]);
116 }
117}
118
119/// Apply \a Work on the current tool chain \a RegularToolChain and any other
120/// offloading tool chain that is associated with the current action \a JA.
121static void
122forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
123 const ToolChain &RegularToolChain,
124 llvm::function_ref<void(const ToolChain &)> Work) {
125 // Apply Work on the current/regular tool chain.
126 Work(RegularToolChain);
127
128 // Apply Work on all the offloading tool chains associated with the current
129 // action.
130 if (JA.isHostOffloading(Action::OFK_Cuda))
131 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
132 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
Yaxun Liu398612b2018-05-08 21:02:12 +0000134 else if (JA.isHostOffloading(Action::OFK_HIP))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
136 else if (JA.isDeviceOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
David L. Jonesf561aba2017-03-08 01:02:16 +0000138
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000139 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
140 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
141 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
142 Work(*II->second);
143 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
144 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
145
David L. Jonesf561aba2017-03-08 01:02:16 +0000146 //
147 // TODO: Add support for other offloading programming models here.
148 //
149}
150
151/// This is a helper function for validating the optional refinement step
152/// parameter in reciprocal argument strings. Return false if there is an error
153/// parsing the refinement step. Otherwise, return true and set the Position
154/// of the refinement step in the input string.
155static bool getRefinementStep(StringRef In, const Driver &D,
156 const Arg &A, size_t &Position) {
157 const char RefinementStepToken = ':';
158 Position = In.find(RefinementStepToken);
159 if (Position != StringRef::npos) {
160 StringRef Option = A.getOption().getName();
161 StringRef RefStep = In.substr(Position + 1);
162 // Allow exactly one numeric character for the additional refinement
163 // step parameter. This is reasonable for all currently-supported
164 // operations and architectures because we would expect that a larger value
165 // of refinement steps would cause the estimate "optimization" to
166 // under-perform the native operation. Also, if the estimate does not
167 // converge quickly, it probably will not ever converge, so further
168 // refinement steps will not produce a better answer.
169 if (RefStep.size() != 1) {
170 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
171 return false;
172 }
173 char RefStepChar = RefStep[0];
174 if (RefStepChar < '0' || RefStepChar > '9') {
175 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
176 return false;
177 }
178 }
179 return true;
180}
181
182/// The -mrecip flag requires processing of many optional parameters.
183static void ParseMRecip(const Driver &D, const ArgList &Args,
184 ArgStringList &OutStrings) {
185 StringRef DisabledPrefixIn = "!";
186 StringRef DisabledPrefixOut = "!";
187 StringRef EnabledPrefixOut = "";
188 StringRef Out = "-mrecip=";
189
190 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
191 if (!A)
192 return;
193
194 unsigned NumOptions = A->getNumValues();
195 if (NumOptions == 0) {
196 // No option is the same as "all".
197 OutStrings.push_back(Args.MakeArgString(Out + "all"));
198 return;
199 }
200
201 // Pass through "all", "none", or "default" with an optional refinement step.
202 if (NumOptions == 1) {
203 StringRef Val = A->getValue(0);
204 size_t RefStepLoc;
205 if (!getRefinementStep(Val, D, *A, RefStepLoc))
206 return;
207 StringRef ValBase = Val.slice(0, RefStepLoc);
208 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
209 OutStrings.push_back(Args.MakeArgString(Out + Val));
210 return;
211 }
212 }
213
214 // Each reciprocal type may be enabled or disabled individually.
215 // Check each input value for validity, concatenate them all back together,
216 // and pass through.
217
218 llvm::StringMap<bool> OptionStrings;
219 OptionStrings.insert(std::make_pair("divd", false));
220 OptionStrings.insert(std::make_pair("divf", false));
221 OptionStrings.insert(std::make_pair("vec-divd", false));
222 OptionStrings.insert(std::make_pair("vec-divf", false));
223 OptionStrings.insert(std::make_pair("sqrtd", false));
224 OptionStrings.insert(std::make_pair("sqrtf", false));
225 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
226 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
227
228 for (unsigned i = 0; i != NumOptions; ++i) {
229 StringRef Val = A->getValue(i);
230
231 bool IsDisabled = Val.startswith(DisabledPrefixIn);
232 // Ignore the disablement token for string matching.
233 if (IsDisabled)
234 Val = Val.substr(1);
235
236 size_t RefStep;
237 if (!getRefinementStep(Val, D, *A, RefStep))
238 return;
239
240 StringRef ValBase = Val.slice(0, RefStep);
241 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
242 if (OptionIter == OptionStrings.end()) {
243 // Try again specifying float suffix.
244 OptionIter = OptionStrings.find(ValBase.str() + 'f');
245 if (OptionIter == OptionStrings.end()) {
246 // The input name did not match any known option string.
247 D.Diag(diag::err_drv_unknown_argument) << Val;
248 return;
249 }
250 // The option was specified without a float or double suffix.
251 // Make sure that the double entry was not already specified.
252 // The float entry will be checked below.
253 if (OptionStrings[ValBase.str() + 'd']) {
254 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
255 return;
256 }
257 }
258
259 if (OptionIter->second == true) {
260 // Duplicate option specified.
261 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
262 return;
263 }
264
265 // Mark the matched option as found. Do not allow duplicate specifiers.
266 OptionIter->second = true;
267
268 // If the precision was not specified, also mark the double entry as found.
269 if (ValBase.back() != 'f' && ValBase.back() != 'd')
270 OptionStrings[ValBase.str() + 'd'] = true;
271
272 // Build the output string.
273 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
274 Out = Args.MakeArgString(Out + Prefix + Val);
275 if (i != NumOptions - 1)
276 Out = Args.MakeArgString(Out + ",");
277 }
278
279 OutStrings.push_back(Args.MakeArgString(Out));
280}
281
Craig Topper9a724aa2017-12-11 21:09:19 +0000282/// The -mprefer-vector-width option accepts either a positive integer
283/// or the string "none".
284static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
285 ArgStringList &CmdArgs) {
286 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
287 if (!A)
288 return;
289
290 StringRef Value = A->getValue();
291 if (Value == "none") {
292 CmdArgs.push_back("-mprefer-vector-width=none");
293 } else {
294 unsigned Width;
295 if (Value.getAsInteger(10, Width)) {
296 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
297 return;
298 }
299 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
300 }
301}
302
David L. Jonesf561aba2017-03-08 01:02:16 +0000303static void getWebAssemblyTargetFeatures(const ArgList &Args,
304 std::vector<StringRef> &Features) {
305 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
306}
307
David L. Jonesf561aba2017-03-08 01:02:16 +0000308static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
309 const ArgList &Args, ArgStringList &CmdArgs,
310 bool ForAS) {
311 const Driver &D = TC.getDriver();
312 std::vector<StringRef> Features;
313 switch (Triple.getArch()) {
314 default:
315 break;
316 case llvm::Triple::mips:
317 case llvm::Triple::mipsel:
318 case llvm::Triple::mips64:
319 case llvm::Triple::mips64el:
320 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
321 break;
322
323 case llvm::Triple::arm:
324 case llvm::Triple::armeb:
325 case llvm::Triple::thumb:
326 case llvm::Triple::thumbeb:
327 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
328 break;
329
330 case llvm::Triple::ppc:
331 case llvm::Triple::ppc64:
332 case llvm::Triple::ppc64le:
333 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
334 break;
Alex Bradbury71f45452018-01-11 13:36:56 +0000335 case llvm::Triple::riscv32:
336 case llvm::Triple::riscv64:
337 riscv::getRISCVTargetFeatures(D, Args, Features);
338 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000339 case llvm::Triple::systemz:
340 systemz::getSystemZTargetFeatures(Args, Features);
341 break;
342 case llvm::Triple::aarch64:
343 case llvm::Triple::aarch64_be:
344 aarch64::getAArch64TargetFeatures(D, Args, Features);
345 break;
346 case llvm::Triple::x86:
347 case llvm::Triple::x86_64:
348 x86::getX86TargetFeatures(D, Triple, Args, Features);
349 break;
350 case llvm::Triple::hexagon:
Sumanth Gundapaneni57098f52017-10-18 18:10:13 +0000351 hexagon::getHexagonTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000352 break;
353 case llvm::Triple::wasm32:
354 case llvm::Triple::wasm64:
355 getWebAssemblyTargetFeatures(Args, Features);
356 break;
357 case llvm::Triple::sparc:
358 case llvm::Triple::sparcel:
359 case llvm::Triple::sparcv9:
360 sparc::getSparcTargetFeatures(D, Args, Features);
361 break;
362 case llvm::Triple::r600:
363 case llvm::Triple::amdgcn:
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +0000364 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000365 break;
366 }
367
368 // Find the last of each feature.
369 llvm::StringMap<unsigned> LastOpt;
370 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
371 StringRef Name = Features[I];
372 assert(Name[0] == '-' || Name[0] == '+');
373 LastOpt[Name.drop_front(1)] = I;
374 }
375
376 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
377 // If this feature was overridden, ignore it.
378 StringRef Name = Features[I];
379 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
380 assert(LastI != LastOpt.end());
381 unsigned Last = LastI->second;
382 if (Last != I)
383 continue;
384
385 CmdArgs.push_back("-target-feature");
386 CmdArgs.push_back(Name.data());
387 }
388}
389
390static bool
391shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
392 const llvm::Triple &Triple) {
393 // We use the zero-cost exception tables for Objective-C if the non-fragile
394 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
395 // later.
396 if (runtime.isNonFragile())
397 return true;
398
399 if (!Triple.isMacOSX())
400 return false;
401
402 return (!Triple.isMacOSXVersionLT(10, 5) &&
403 (Triple.getArch() == llvm::Triple::x86_64 ||
404 Triple.getArch() == llvm::Triple::arm));
405}
406
407/// Adds exception related arguments to the driver command arguments. There's a
408/// master flag, -fexceptions and also language specific flags to enable/disable
409/// C++ and Objective-C exceptions. This makes it possible to for example
410/// disable C++ exceptions but enable Objective-C exceptions.
411static void addExceptionArgs(const ArgList &Args, types::ID InputType,
412 const ToolChain &TC, bool KernelOrKext,
413 const ObjCRuntime &objcRuntime,
414 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000415 const llvm::Triple &Triple = TC.getTriple();
416
417 if (KernelOrKext) {
418 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
419 // arguments now to avoid warnings about unused arguments.
420 Args.ClaimAllArgs(options::OPT_fexceptions);
421 Args.ClaimAllArgs(options::OPT_fno_exceptions);
422 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
423 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
424 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
425 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
426 return;
427 }
428
429 // See if the user explicitly enabled exceptions.
430 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
431 false);
432
433 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
434 // is not necessarily sensible, but follows GCC.
435 if (types::isObjC(InputType) &&
436 Args.hasFlag(options::OPT_fobjc_exceptions,
437 options::OPT_fno_objc_exceptions, true)) {
438 CmdArgs.push_back("-fobjc-exceptions");
439
440 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
441 }
442
443 if (types::isCXX(InputType)) {
444 // Disable C++ EH by default on XCore and PS4.
445 bool CXXExceptionsEnabled =
446 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
447 Arg *ExceptionArg = Args.getLastArg(
448 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
449 options::OPT_fexceptions, options::OPT_fno_exceptions);
450 if (ExceptionArg)
451 CXXExceptionsEnabled =
452 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
453 ExceptionArg->getOption().matches(options::OPT_fexceptions);
454
455 if (CXXExceptionsEnabled) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000456 CmdArgs.push_back("-fcxx-exceptions");
457
458 EH = true;
459 }
460 }
461
462 if (EH)
463 CmdArgs.push_back("-fexceptions");
464}
465
466static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
467 bool Default = true;
468 if (TC.getTriple().isOSDarwin()) {
469 // The native darwin assembler doesn't support the linker_option directives,
470 // so we disable them if we think the .s file will be passed to it.
471 Default = TC.useIntegratedAs();
472 }
473 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
474 Default);
475}
476
477static bool ShouldDisableDwarfDirectory(const ArgList &Args,
478 const ToolChain &TC) {
479 bool UseDwarfDirectory =
480 Args.hasFlag(options::OPT_fdwarf_directory_asm,
481 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
482 return !UseDwarfDirectory;
483}
484
485// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
486// to the corresponding DebugInfoKind.
487static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
488 assert(A.getOption().matches(options::OPT_gN_Group) &&
489 "Not a -g option that specifies a debug-info level");
490 if (A.getOption().matches(options::OPT_g0) ||
491 A.getOption().matches(options::OPT_ggdb0))
492 return codegenoptions::NoDebugInfo;
493 if (A.getOption().matches(options::OPT_gline_tables_only) ||
494 A.getOption().matches(options::OPT_ggdb1))
495 return codegenoptions::DebugLineTablesOnly;
496 return codegenoptions::LimitedDebugInfo;
497}
498
499static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
500 switch (Triple.getArch()){
501 default:
502 return false;
503 case llvm::Triple::arm:
504 case llvm::Triple::thumb:
505 // ARM Darwin targets require a frame pointer to be always present to aid
506 // offline debugging via backtraces.
507 return Triple.isOSDarwin();
508 }
509}
510
511static bool useFramePointerForTargetByDefault(const ArgList &Args,
512 const llvm::Triple &Triple) {
513 switch (Triple.getArch()) {
514 case llvm::Triple::xcore:
515 case llvm::Triple::wasm32:
516 case llvm::Triple::wasm64:
517 // XCore never wants frame pointers, regardless of OS.
518 // WebAssembly never wants frame pointers.
519 return false;
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000520 case llvm::Triple::riscv32:
521 case llvm::Triple::riscv64:
522 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000523 default:
524 break;
525 }
526
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000527 if (Triple.getOS() == llvm::Triple::NetBSD) {
528 return !areOptimizationsEnabled(Args);
529 }
530
David L. Jonesf561aba2017-03-08 01:02:16 +0000531 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
532 switch (Triple.getArch()) {
533 // Don't use a frame pointer on linux if optimizing for certain targets.
534 case llvm::Triple::mips64:
535 case llvm::Triple::mips64el:
536 case llvm::Triple::mips:
537 case llvm::Triple::mipsel:
538 case llvm::Triple::ppc:
539 case llvm::Triple::ppc64:
540 case llvm::Triple::ppc64le:
541 case llvm::Triple::systemz:
542 case llvm::Triple::x86:
543 case llvm::Triple::x86_64:
544 return !areOptimizationsEnabled(Args);
545 default:
546 return true;
547 }
548 }
549
550 if (Triple.isOSWindows()) {
551 switch (Triple.getArch()) {
552 case llvm::Triple::x86:
553 return !areOptimizationsEnabled(Args);
554 case llvm::Triple::x86_64:
555 return Triple.isOSBinFormatMachO();
556 case llvm::Triple::arm:
557 case llvm::Triple::thumb:
558 // Windows on ARM builds with FPO disabled to aid fast stack walking
559 return true;
560 default:
561 // All other supported Windows ISAs use xdata unwind information, so frame
562 // pointers are not generally useful.
563 return false;
564 }
565 }
566
567 return true;
568}
569
570static bool shouldUseFramePointer(const ArgList &Args,
571 const llvm::Triple &Triple) {
572 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
573 options::OPT_fomit_frame_pointer))
574 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
575 mustUseNonLeafFramePointerForTarget(Triple);
576
577 if (Args.hasArg(options::OPT_pg))
578 return true;
579
580 return useFramePointerForTargetByDefault(Args, Triple);
581}
582
583static bool shouldUseLeafFramePointer(const ArgList &Args,
584 const llvm::Triple &Triple) {
585 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
586 options::OPT_momit_leaf_frame_pointer))
587 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
588
589 if (Args.hasArg(options::OPT_pg))
590 return true;
591
592 if (Triple.isPS4CPU())
593 return false;
594
595 return useFramePointerForTargetByDefault(Args, Triple);
596}
597
598/// Add a CC1 option to specify the debug compilation directory.
599static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
600 SmallString<128> cwd;
601 if (!llvm::sys::fs::current_path(cwd)) {
602 CmdArgs.push_back("-fdebug-compilation-dir");
603 CmdArgs.push_back(Args.MakeArgString(cwd));
604 }
605}
606
Paul Robinson9b292b42018-07-10 15:15:24 +0000607/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
608static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
609 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
610 StringRef Map = A->getValue();
611 if (Map.find('=') == StringRef::npos)
612 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
613 else
614 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
615 A->claim();
616 }
617}
618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000619/// Vectorize at all optimization levels greater than 1 except for -Oz.
David L. Jonesf561aba2017-03-08 01:02:16 +0000620/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
621static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
622 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
623 if (A->getOption().matches(options::OPT_O4) ||
624 A->getOption().matches(options::OPT_Ofast))
625 return true;
626
627 if (A->getOption().matches(options::OPT_O0))
628 return false;
629
630 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
631
632 // Vectorize -Os.
633 StringRef S(A->getValue());
634 if (S == "s")
635 return true;
636
637 // Don't vectorize -Oz, unless it's the slp vectorizer.
638 if (S == "z")
639 return isSlpVec;
640
641 unsigned OptLevel = 0;
642 if (S.getAsInteger(10, OptLevel))
643 return false;
644
645 return OptLevel > 1;
646 }
647
648 return false;
649}
650
651/// Add -x lang to \p CmdArgs for \p Input.
652static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
653 ArgStringList &CmdArgs) {
654 // When using -verify-pch, we don't want to provide the type
655 // 'precompiled-header' if it was inferred from the file extension
656 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
657 return;
658
659 CmdArgs.push_back("-x");
660 if (Args.hasArg(options::OPT_rewrite_objc))
661 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000662 else {
663 // Map the driver type to the frontend type. This is mostly an identity
664 // mapping, except that the distinction between module interface units
665 // and other source files does not exist at the frontend layer.
666 const char *ClangType;
667 switch (Input.getType()) {
668 case types::TY_CXXModule:
669 ClangType = "c++";
670 break;
671 case types::TY_PP_CXXModule:
672 ClangType = "c++-cpp-output";
673 break;
674 default:
675 ClangType = types::getTypeName(Input.getType());
676 break;
677 }
678 CmdArgs.push_back(ClangType);
679 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000680}
681
682static void appendUserToPath(SmallVectorImpl<char> &Result) {
683#ifdef LLVM_ON_UNIX
684 const char *Username = getenv("LOGNAME");
685#else
686 const char *Username = getenv("USERNAME");
687#endif
688 if (Username) {
689 // Validate that LoginName can be used in a path, and get its length.
690 size_t Len = 0;
691 for (const char *P = Username; *P; ++P, ++Len) {
692 if (!clang::isAlphanumeric(*P) && *P != '_') {
693 Username = nullptr;
694 break;
695 }
696 }
697
698 if (Username && Len > 0) {
699 Result.append(Username, Username + Len);
700 return;
701 }
702 }
703
704// Fallback to user id.
705#ifdef LLVM_ON_UNIX
706 std::string UID = llvm::utostr(getuid());
707#else
708 // FIXME: Windows seems to have an 'SID' that might work.
709 std::string UID = "9999";
710#endif
711 Result.append(UID.begin(), UID.end());
712}
713
714static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
715 const InputInfo &Output, const ArgList &Args,
716 ArgStringList &CmdArgs) {
717
718 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
719 options::OPT_fprofile_generate_EQ,
720 options::OPT_fno_profile_generate);
721 if (PGOGenerateArg &&
722 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
723 PGOGenerateArg = nullptr;
724
725 auto *ProfileGenerateArg = Args.getLastArg(
726 options::OPT_fprofile_instr_generate,
727 options::OPT_fprofile_instr_generate_EQ,
728 options::OPT_fno_profile_instr_generate);
729 if (ProfileGenerateArg &&
730 ProfileGenerateArg->getOption().matches(
731 options::OPT_fno_profile_instr_generate))
732 ProfileGenerateArg = nullptr;
733
734 if (PGOGenerateArg && ProfileGenerateArg)
735 D.Diag(diag::err_drv_argument_not_allowed_with)
736 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
737
738 auto *ProfileUseArg = getLastProfileUseArg(Args);
739
740 if (PGOGenerateArg && ProfileUseArg)
741 D.Diag(diag::err_drv_argument_not_allowed_with)
742 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
743
744 if (ProfileGenerateArg && ProfileUseArg)
745 D.Diag(diag::err_drv_argument_not_allowed_with)
746 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
747
748 if (ProfileGenerateArg) {
749 if (ProfileGenerateArg->getOption().matches(
750 options::OPT_fprofile_instr_generate_EQ))
751 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
752 ProfileGenerateArg->getValue()));
753 // The default is to use Clang Instrumentation.
754 CmdArgs.push_back("-fprofile-instrument=clang");
755 }
756
757 if (PGOGenerateArg) {
758 CmdArgs.push_back("-fprofile-instrument=llvm");
759 if (PGOGenerateArg->getOption().matches(
760 options::OPT_fprofile_generate_EQ)) {
761 SmallString<128> Path(PGOGenerateArg->getValue());
762 llvm::sys::path::append(Path, "default_%m.profraw");
763 CmdArgs.push_back(
764 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
765 }
766 }
767
768 if (ProfileUseArg) {
769 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
770 CmdArgs.push_back(Args.MakeArgString(
771 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
772 else if ((ProfileUseArg->getOption().matches(
773 options::OPT_fprofile_use_EQ) ||
774 ProfileUseArg->getOption().matches(
775 options::OPT_fprofile_instr_use))) {
776 SmallString<128> Path(
777 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
778 if (Path.empty() || llvm::sys::fs::is_directory(Path))
779 llvm::sys::path::append(Path, "default.profdata");
780 CmdArgs.push_back(
781 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
782 }
783 }
784
785 if (Args.hasArg(options::OPT_ftest_coverage) ||
786 Args.hasArg(options::OPT_coverage))
787 CmdArgs.push_back("-femit-coverage-notes");
788 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
789 false) ||
790 Args.hasArg(options::OPT_coverage))
791 CmdArgs.push_back("-femit-coverage-data");
792
793 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000794 options::OPT_fno_coverage_mapping, false)) {
795 if (!ProfileGenerateArg)
796 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
797 << "-fcoverage-mapping"
798 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000799
David L. Jonesf561aba2017-03-08 01:02:16 +0000800 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000801 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000802
803 if (C.getArgs().hasArg(options::OPT_c) ||
804 C.getArgs().hasArg(options::OPT_S)) {
805 if (Output.isFilename()) {
806 CmdArgs.push_back("-coverage-notes-file");
807 SmallString<128> OutputFilename;
808 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
809 OutputFilename = FinalOutput->getValue();
810 else
811 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
812 SmallString<128> CoverageFilename = OutputFilename;
813 if (llvm::sys::path::is_relative(CoverageFilename)) {
814 SmallString<128> Pwd;
815 if (!llvm::sys::fs::current_path(Pwd)) {
816 llvm::sys::path::append(Pwd, CoverageFilename);
817 CoverageFilename.swap(Pwd);
818 }
819 }
820 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
821 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
822
823 // Leave -fprofile-dir= an unused argument unless .gcda emission is
824 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
825 // the flag used. There is no -fno-profile-dir, so the user has no
826 // targeted way to suppress the warning.
827 if (Args.hasArg(options::OPT_fprofile_arcs) ||
828 Args.hasArg(options::OPT_coverage)) {
829 CmdArgs.push_back("-coverage-data-file");
830 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
831 CoverageFilename = FProfileDir->getValue();
832 llvm::sys::path::append(CoverageFilename, OutputFilename);
833 }
834 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
835 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
836 }
837 }
838 }
839}
840
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000841/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000842static bool ContainsCompileAction(const Action *A) {
843 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
844 return true;
845
846 for (const auto &AI : A->inputs())
847 if (ContainsCompileAction(AI))
848 return true;
849
850 return false;
851}
852
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000853/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000854/// This is done by default when compiling non-assembler source with -O0.
855static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
856 bool RelaxDefault = true;
857
858 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
859 RelaxDefault = A->getOption().matches(options::OPT_O0);
860
861 if (RelaxDefault) {
862 RelaxDefault = false;
863 for (const auto &Act : C.getActions()) {
864 if (ContainsCompileAction(Act)) {
865 RelaxDefault = true;
866 break;
867 }
868 }
869 }
870
871 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
872 RelaxDefault);
873}
874
875// Extract the integer N from a string spelled "-dwarf-N", returning 0
876// on mismatch. The StringRef input (rather than an Arg) allows
877// for use by the "-Xassembler" option parser.
878static unsigned DwarfVersionNum(StringRef ArgValue) {
879 return llvm::StringSwitch<unsigned>(ArgValue)
880 .Case("-gdwarf-2", 2)
881 .Case("-gdwarf-3", 3)
882 .Case("-gdwarf-4", 4)
883 .Case("-gdwarf-5", 5)
884 .Default(0);
885}
886
887static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
888 codegenoptions::DebugInfoKind DebugInfoKind,
889 unsigned DwarfVersion,
890 llvm::DebuggerKind DebuggerTuning) {
891 switch (DebugInfoKind) {
892 case codegenoptions::DebugLineTablesOnly:
893 CmdArgs.push_back("-debug-info-kind=line-tables-only");
894 break;
895 case codegenoptions::LimitedDebugInfo:
896 CmdArgs.push_back("-debug-info-kind=limited");
897 break;
898 case codegenoptions::FullDebugInfo:
899 CmdArgs.push_back("-debug-info-kind=standalone");
900 break;
901 default:
902 break;
903 }
904 if (DwarfVersion > 0)
905 CmdArgs.push_back(
906 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
907 switch (DebuggerTuning) {
908 case llvm::DebuggerKind::GDB:
909 CmdArgs.push_back("-debugger-tuning=gdb");
910 break;
911 case llvm::DebuggerKind::LLDB:
912 CmdArgs.push_back("-debugger-tuning=lldb");
913 break;
914 case llvm::DebuggerKind::SCE:
915 CmdArgs.push_back("-debugger-tuning=sce");
916 break;
917 default:
918 break;
919 }
920}
921
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000922static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
923 const Driver &D, const ToolChain &TC) {
924 assert(A && "Expected non-nullptr argument.");
925 if (TC.supportsDebugInfoOption(A))
926 return true;
927 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
928 << A->getAsString(Args) << TC.getTripleString();
929 return false;
930}
931
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000932static void RenderDebugInfoCompressionArgs(const ArgList &Args,
933 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000934 const Driver &D,
935 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000936 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
937 if (!A)
938 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000939 if (checkDebugInfoOption(A, Args, D, TC)) {
940 if (A->getOption().getID() == options::OPT_gz) {
941 if (llvm::zlib::isAvailable())
942 CmdArgs.push_back("-compress-debug-sections");
943 else
944 D.Diag(diag::warn_debug_compression_unavailable);
945 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000946 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000947
948 StringRef Value = A->getValue();
949 if (Value == "none") {
950 CmdArgs.push_back("-compress-debug-sections=none");
951 } else if (Value == "zlib" || Value == "zlib-gnu") {
952 if (llvm::zlib::isAvailable()) {
953 CmdArgs.push_back(
954 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
955 } else {
956 D.Diag(diag::warn_debug_compression_unavailable);
957 }
958 } else {
959 D.Diag(diag::err_drv_unsupported_option_argument)
960 << A->getOption().getName() << Value;
961 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000962 }
963}
964
David L. Jonesf561aba2017-03-08 01:02:16 +0000965static const char *RelocationModelName(llvm::Reloc::Model Model) {
966 switch (Model) {
967 case llvm::Reloc::Static:
968 return "static";
969 case llvm::Reloc::PIC_:
970 return "pic";
971 case llvm::Reloc::DynamicNoPIC:
972 return "dynamic-no-pic";
973 case llvm::Reloc::ROPI:
974 return "ropi";
975 case llvm::Reloc::RWPI:
976 return "rwpi";
977 case llvm::Reloc::ROPI_RWPI:
978 return "ropi-rwpi";
979 }
980 llvm_unreachable("Unknown Reloc::Model kind");
981}
982
983void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
984 const Driver &D, const ArgList &Args,
985 ArgStringList &CmdArgs,
986 const InputInfo &Output,
987 const InputInfoList &Inputs) const {
988 Arg *A;
989 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
990
991 CheckPreprocessingOptions(D, Args);
992
993 Args.AddLastArg(CmdArgs, options::OPT_C);
994 Args.AddLastArg(CmdArgs, options::OPT_CC);
995
996 // Handle dependency file generation.
997 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
998 (A = Args.getLastArg(options::OPT_MD)) ||
999 (A = Args.getLastArg(options::OPT_MMD))) {
1000 // Determine the output location.
1001 const char *DepFile;
1002 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1003 DepFile = MF->getValue();
1004 C.addFailureResultFile(DepFile, &JA);
1005 } else if (Output.getType() == types::TY_Dependencies) {
1006 DepFile = Output.getFilename();
1007 } else if (A->getOption().matches(options::OPT_M) ||
1008 A->getOption().matches(options::OPT_MM)) {
1009 DepFile = "-";
1010 } else {
1011 DepFile = getDependencyFileName(Args, Inputs);
1012 C.addFailureResultFile(DepFile, &JA);
1013 }
1014 CmdArgs.push_back("-dependency-file");
1015 CmdArgs.push_back(DepFile);
1016
1017 // Add a default target if one wasn't specified.
1018 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1019 const char *DepTarget;
1020
1021 // If user provided -o, that is the dependency target, except
1022 // when we are only generating a dependency file.
1023 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1024 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1025 DepTarget = OutputOpt->getValue();
1026 } else {
1027 // Otherwise derive from the base input.
1028 //
1029 // FIXME: This should use the computed output file location.
1030 SmallString<128> P(Inputs[0].getBaseInput());
1031 llvm::sys::path::replace_extension(P, "o");
1032 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1033 }
1034
Yuka Takahashicdb53482017-06-16 16:01:13 +00001035 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1036 CmdArgs.push_back("-w");
1037 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001038 CmdArgs.push_back("-MT");
1039 SmallString<128> Quoted;
1040 QuoteTarget(DepTarget, Quoted);
1041 CmdArgs.push_back(Args.MakeArgString(Quoted));
1042 }
1043
1044 if (A->getOption().matches(options::OPT_M) ||
1045 A->getOption().matches(options::OPT_MD))
1046 CmdArgs.push_back("-sys-header-deps");
1047 if ((isa<PrecompileJobAction>(JA) &&
1048 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1049 Args.hasArg(options::OPT_fmodule_file_deps))
1050 CmdArgs.push_back("-module-file-deps");
1051 }
1052
1053 if (Args.hasArg(options::OPT_MG)) {
1054 if (!A || A->getOption().matches(options::OPT_MD) ||
1055 A->getOption().matches(options::OPT_MMD))
1056 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1057 CmdArgs.push_back("-MG");
1058 }
1059
1060 Args.AddLastArg(CmdArgs, options::OPT_MP);
1061 Args.AddLastArg(CmdArgs, options::OPT_MV);
1062
1063 // Convert all -MQ <target> args to -MT <quoted target>
1064 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1065 A->claim();
1066
1067 if (A->getOption().matches(options::OPT_MQ)) {
1068 CmdArgs.push_back("-MT");
1069 SmallString<128> Quoted;
1070 QuoteTarget(A->getValue(), Quoted);
1071 CmdArgs.push_back(Args.MakeArgString(Quoted));
1072
1073 // -MT flag - no change
1074 } else {
1075 A->render(Args, CmdArgs);
1076 }
1077 }
1078
1079 // Add offload include arguments specific for CUDA. This must happen before
1080 // we -I or -include anything else, because we must pick up the CUDA headers
1081 // from the particular CUDA installation, rather than from e.g.
1082 // /usr/local/include.
1083 if (JA.isOffloading(Action::OFK_Cuda))
1084 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1085
1086 // Add -i* options, and automatically translate to
1087 // -include-pch/-include-pth for transparent PCH support. It's
1088 // wonky, but we include looking for .gch so we can support seamless
1089 // replacement into a build system already set up to be generating
1090 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001091
1092 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001093 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1094 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001095 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1096 JA.getKind() <= Action::AssembleJobClass) {
1097 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001098 }
Erich Keane76675de2018-07-05 17:22:13 +00001099 if (YcArg || YuArg) {
1100 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1101 if (!isa<PrecompileJobAction>(JA)) {
1102 CmdArgs.push_back("-include-pch");
1103 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(C, ThroughHeader)));
1104 }
1105 CmdArgs.push_back(
1106 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1107 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001108 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001109
1110 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001111 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001112 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001113 // Handling of gcc-style gch precompiled headers.
1114 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1115 RenderedImplicitInclude = true;
1116
1117 // Use PCH if the user requested it.
1118 bool UsePCH = D.CCCUsePCH;
1119
1120 bool FoundPTH = false;
1121 bool FoundPCH = false;
1122 SmallString<128> P(A->getValue());
1123 // We want the files to have a name like foo.h.pch. Add a dummy extension
1124 // so that replace_extension does the right thing.
1125 P += ".dummy";
1126 if (UsePCH) {
1127 llvm::sys::path::replace_extension(P, "pch");
1128 if (llvm::sys::fs::exists(P))
1129 FoundPCH = true;
1130 }
1131
1132 if (!FoundPCH) {
1133 llvm::sys::path::replace_extension(P, "pth");
1134 if (llvm::sys::fs::exists(P))
1135 FoundPTH = true;
1136 }
1137
1138 if (!FoundPCH && !FoundPTH) {
1139 llvm::sys::path::replace_extension(P, "gch");
1140 if (llvm::sys::fs::exists(P)) {
1141 FoundPCH = UsePCH;
1142 FoundPTH = !UsePCH;
1143 }
1144 }
1145
1146 if (FoundPCH || FoundPTH) {
1147 if (IsFirstImplicitInclude) {
1148 A->claim();
1149 if (UsePCH)
1150 CmdArgs.push_back("-include-pch");
1151 else
1152 CmdArgs.push_back("-include-pth");
1153 CmdArgs.push_back(Args.MakeArgString(P));
1154 continue;
1155 } else {
1156 // Ignore the PCH if not first on command line and emit warning.
1157 D.Diag(diag::warn_drv_pch_not_first_include) << P
1158 << A->getAsString(Args);
1159 }
1160 }
1161 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1162 // Handling of paths which must come late. These entries are handled by
1163 // the toolchain itself after the resource dir is inserted in the right
1164 // search order.
1165 // Do not claim the argument so that the use of the argument does not
1166 // silently go unnoticed on toolchains which do not honour the option.
1167 continue;
1168 }
1169
1170 // Not translated, render as usual.
1171 A->claim();
1172 A->render(Args, CmdArgs);
1173 }
1174
1175 Args.AddAllArgs(CmdArgs,
1176 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1177 options::OPT_F, options::OPT_index_header_map});
1178
1179 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1180
1181 // FIXME: There is a very unfortunate problem here, some troubled
1182 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1183 // really support that we would have to parse and then translate
1184 // those options. :(
1185 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1186 options::OPT_Xpreprocessor);
1187
1188 // -I- is a deprecated GCC feature, reject it.
1189 if (Arg *A = Args.getLastArg(options::OPT_I_))
1190 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1191
1192 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1193 // -isysroot to the CC1 invocation.
1194 StringRef sysroot = C.getSysRoot();
1195 if (sysroot != "") {
1196 if (!Args.hasArg(options::OPT_isysroot)) {
1197 CmdArgs.push_back("-isysroot");
1198 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1199 }
1200 }
1201
1202 // Parse additional include paths from environment variables.
1203 // FIXME: We should probably sink the logic for handling these from the
1204 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1205 // CPATH - included following the user specified includes (but prior to
1206 // builtin and standard includes).
1207 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1208 // C_INCLUDE_PATH - system includes enabled when compiling C.
1209 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1210 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1211 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1212 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1213 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1214 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1215 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1216
1217 // While adding the include arguments, we also attempt to retrieve the
1218 // arguments of related offloading toolchains or arguments that are specific
1219 // of an offloading programming model.
1220
1221 // Add C++ include arguments, if needed.
1222 if (types::isCXX(Inputs[0].getType()))
1223 forAllAssociatedToolChains(C, JA, getToolChain(),
1224 [&Args, &CmdArgs](const ToolChain &TC) {
1225 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1226 });
1227
1228 // Add system include arguments for all targets but IAMCU.
1229 if (!IsIAMCU)
1230 forAllAssociatedToolChains(C, JA, getToolChain(),
1231 [&Args, &CmdArgs](const ToolChain &TC) {
1232 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1233 });
1234 else {
1235 // For IAMCU add special include arguments.
1236 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1237 }
1238}
1239
1240// FIXME: Move to target hook.
1241static bool isSignedCharDefault(const llvm::Triple &Triple) {
1242 switch (Triple.getArch()) {
1243 default:
1244 return true;
1245
1246 case llvm::Triple::aarch64:
1247 case llvm::Triple::aarch64_be:
1248 case llvm::Triple::arm:
1249 case llvm::Triple::armeb:
1250 case llvm::Triple::thumb:
1251 case llvm::Triple::thumbeb:
1252 if (Triple.isOSDarwin() || Triple.isOSWindows())
1253 return true;
1254 return false;
1255
1256 case llvm::Triple::ppc:
1257 case llvm::Triple::ppc64:
1258 if (Triple.isOSDarwin())
1259 return true;
1260 return false;
1261
1262 case llvm::Triple::hexagon:
1263 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001264 case llvm::Triple::riscv32:
1265 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001266 case llvm::Triple::systemz:
1267 case llvm::Triple::xcore:
1268 return false;
1269 }
1270}
1271
1272static bool isNoCommonDefault(const llvm::Triple &Triple) {
1273 switch (Triple.getArch()) {
1274 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001275 if (Triple.isOSFuchsia())
1276 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001277 return false;
1278
1279 case llvm::Triple::xcore:
1280 case llvm::Triple::wasm32:
1281 case llvm::Triple::wasm64:
1282 return true;
1283 }
1284}
1285
1286void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1287 ArgStringList &CmdArgs, bool KernelOrKext) const {
1288 // Select the ABI to use.
1289 // FIXME: Support -meabi.
1290 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1291 const char *ABIName = nullptr;
Eric Christopher53b2cb72017-06-30 00:03:56 +00001292 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
David L. Jonesf561aba2017-03-08 01:02:16 +00001293 ABIName = A->getValue();
Eric Christopher53b2cb72017-06-30 00:03:56 +00001294 else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001295 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001296 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001297 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001298
David L. Jonesf561aba2017-03-08 01:02:16 +00001299 CmdArgs.push_back("-target-abi");
1300 CmdArgs.push_back(ABIName);
1301
1302 // Determine floating point ABI from the options & target defaults.
1303 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1304 if (ABI == arm::FloatABI::Soft) {
1305 // Floating point operations and argument passing are soft.
1306 // FIXME: This changes CPP defines, we need -target-soft-float.
1307 CmdArgs.push_back("-msoft-float");
1308 CmdArgs.push_back("-mfloat-abi");
1309 CmdArgs.push_back("soft");
1310 } else if (ABI == arm::FloatABI::SoftFP) {
1311 // Floating point operations are hard, but argument passing is soft.
1312 CmdArgs.push_back("-mfloat-abi");
1313 CmdArgs.push_back("soft");
1314 } else {
1315 // Floating point operations and argument passing are hard.
1316 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1317 CmdArgs.push_back("-mfloat-abi");
1318 CmdArgs.push_back("hard");
1319 }
1320
1321 // Forward the -mglobal-merge option for explicit control over the pass.
1322 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1323 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001324 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001325 if (A->getOption().matches(options::OPT_mno_global_merge))
1326 CmdArgs.push_back("-arm-global-merge=false");
1327 else
1328 CmdArgs.push_back("-arm-global-merge=true");
1329 }
1330
1331 if (!Args.hasFlag(options::OPT_mimplicit_float,
1332 options::OPT_mno_implicit_float, true))
1333 CmdArgs.push_back("-no-implicit-float");
1334}
1335
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001336void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1337 const ArgList &Args, bool KernelOrKext,
1338 ArgStringList &CmdArgs) const {
1339 const ToolChain &TC = getToolChain();
1340
1341 // Add the target features
1342 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1343
1344 // Add target specific flags.
1345 switch (TC.getArch()) {
1346 default:
1347 break;
1348
1349 case llvm::Triple::arm:
1350 case llvm::Triple::armeb:
1351 case llvm::Triple::thumb:
1352 case llvm::Triple::thumbeb:
1353 // Use the effective triple, which takes into account the deployment target.
1354 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1355 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1356 break;
1357
1358 case llvm::Triple::aarch64:
1359 case llvm::Triple::aarch64_be:
1360 AddAArch64TargetArgs(Args, CmdArgs);
1361 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1362 break;
1363
1364 case llvm::Triple::mips:
1365 case llvm::Triple::mipsel:
1366 case llvm::Triple::mips64:
1367 case llvm::Triple::mips64el:
1368 AddMIPSTargetArgs(Args, CmdArgs);
1369 break;
1370
1371 case llvm::Triple::ppc:
1372 case llvm::Triple::ppc64:
1373 case llvm::Triple::ppc64le:
1374 AddPPCTargetArgs(Args, CmdArgs);
1375 break;
1376
Alex Bradbury71f45452018-01-11 13:36:56 +00001377 case llvm::Triple::riscv32:
1378 case llvm::Triple::riscv64:
1379 AddRISCVTargetArgs(Args, CmdArgs);
1380 break;
1381
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001382 case llvm::Triple::sparc:
1383 case llvm::Triple::sparcel:
1384 case llvm::Triple::sparcv9:
1385 AddSparcTargetArgs(Args, CmdArgs);
1386 break;
1387
1388 case llvm::Triple::systemz:
1389 AddSystemZTargetArgs(Args, CmdArgs);
1390 break;
1391
1392 case llvm::Triple::x86:
1393 case llvm::Triple::x86_64:
1394 AddX86TargetArgs(Args, CmdArgs);
1395 break;
1396
1397 case llvm::Triple::lanai:
1398 AddLanaiTargetArgs(Args, CmdArgs);
1399 break;
1400
1401 case llvm::Triple::hexagon:
1402 AddHexagonTargetArgs(Args, CmdArgs);
1403 break;
1404
1405 case llvm::Triple::wasm32:
1406 case llvm::Triple::wasm64:
1407 AddWebAssemblyTargetArgs(Args, CmdArgs);
1408 break;
1409 }
1410}
1411
David L. Jonesf561aba2017-03-08 01:02:16 +00001412void Clang::AddAArch64TargetArgs(const ArgList &Args,
1413 ArgStringList &CmdArgs) const {
1414 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1415
1416 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1417 Args.hasArg(options::OPT_mkernel) ||
1418 Args.hasArg(options::OPT_fapple_kext))
1419 CmdArgs.push_back("-disable-red-zone");
1420
1421 if (!Args.hasFlag(options::OPT_mimplicit_float,
1422 options::OPT_mno_implicit_float, true))
1423 CmdArgs.push_back("-no-implicit-float");
1424
1425 const char *ABIName = nullptr;
1426 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1427 ABIName = A->getValue();
1428 else if (Triple.isOSDarwin())
1429 ABIName = "darwinpcs";
1430 else
1431 ABIName = "aapcs";
1432
1433 CmdArgs.push_back("-target-abi");
1434 CmdArgs.push_back(ABIName);
1435
1436 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1437 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001438 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001439 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1440 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1441 else
1442 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1443 } else if (Triple.isAndroid()) {
1444 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001445 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001446 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1447 }
1448
1449 // Forward the -mglobal-merge option for explicit control over the pass.
1450 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1451 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001452 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001453 if (A->getOption().matches(options::OPT_mno_global_merge))
1454 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1455 else
1456 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1457 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001458
1459 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address)) {
1460 CmdArgs.push_back(
1461 Args.MakeArgString(Twine("-msign-return-address=") + A->getValue()));
1462 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001463}
1464
1465void Clang::AddMIPSTargetArgs(const ArgList &Args,
1466 ArgStringList &CmdArgs) const {
1467 const Driver &D = getToolChain().getDriver();
1468 StringRef CPUName;
1469 StringRef ABIName;
1470 const llvm::Triple &Triple = getToolChain().getTriple();
1471 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1472
1473 CmdArgs.push_back("-target-abi");
1474 CmdArgs.push_back(ABIName.data());
1475
1476 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1477 if (ABI == mips::FloatABI::Soft) {
1478 // Floating point operations and argument passing are soft.
1479 CmdArgs.push_back("-msoft-float");
1480 CmdArgs.push_back("-mfloat-abi");
1481 CmdArgs.push_back("soft");
1482 } else {
1483 // Floating point operations and argument passing are hard.
1484 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1485 CmdArgs.push_back("-mfloat-abi");
1486 CmdArgs.push_back("hard");
1487 }
1488
1489 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1490 if (A->getOption().matches(options::OPT_mxgot)) {
1491 CmdArgs.push_back("-mllvm");
1492 CmdArgs.push_back("-mxgot");
1493 }
1494 }
1495
1496 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1497 options::OPT_mno_ldc1_sdc1)) {
1498 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1499 CmdArgs.push_back("-mllvm");
1500 CmdArgs.push_back("-mno-ldc1-sdc1");
1501 }
1502 }
1503
1504 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1505 options::OPT_mno_check_zero_division)) {
1506 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1507 CmdArgs.push_back("-mllvm");
1508 CmdArgs.push_back("-mno-check-zero-division");
1509 }
1510 }
1511
1512 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1513 StringRef v = A->getValue();
1514 CmdArgs.push_back("-mllvm");
1515 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1516 A->claim();
1517 }
1518
Simon Dardis31636a12017-07-20 14:04:12 +00001519 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1520 Arg *ABICalls =
1521 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1522
1523 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1524 // -mgpopt is the default for static, -fno-pic environments but these two
1525 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1526 // the only case where -mllvm -mgpopt is passed.
1527 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1528 // passed explicitly when compiling something with -mabicalls
1529 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001530 //
1531 // When the ABI in use is N64, we also need to determine the PIC mode that
1532 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001533 bool NoABICalls =
1534 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001535
1536 llvm::Reloc::Model RelocationModel;
1537 unsigned PICLevel;
1538 bool IsPIE;
1539 std::tie(RelocationModel, PICLevel, IsPIE) =
1540 ParsePICArgs(getToolChain(), Args);
1541
1542 NoABICalls = NoABICalls ||
1543 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1544
Simon Dardis31636a12017-07-20 14:04:12 +00001545 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1546 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1547 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1548 CmdArgs.push_back("-mllvm");
1549 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001550
1551 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1552 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001553 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001554 options::OPT_mno_extern_sdata);
1555 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1556 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001557 if (LocalSData) {
1558 CmdArgs.push_back("-mllvm");
1559 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1560 CmdArgs.push_back("-mlocal-sdata=1");
1561 } else {
1562 CmdArgs.push_back("-mlocal-sdata=0");
1563 }
1564 LocalSData->claim();
1565 }
1566
Simon Dardis7d318782017-07-24 14:02:09 +00001567 if (ExternSData) {
1568 CmdArgs.push_back("-mllvm");
1569 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1570 CmdArgs.push_back("-mextern-sdata=1");
1571 } else {
1572 CmdArgs.push_back("-mextern-sdata=0");
1573 }
1574 ExternSData->claim();
1575 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001576
1577 if (EmbeddedData) {
1578 CmdArgs.push_back("-mllvm");
1579 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1580 CmdArgs.push_back("-membedded-data=1");
1581 } else {
1582 CmdArgs.push_back("-membedded-data=0");
1583 }
1584 EmbeddedData->claim();
1585 }
1586
Simon Dardis31636a12017-07-20 14:04:12 +00001587 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1588 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1589
1590 if (GPOpt)
1591 GPOpt->claim();
1592
David L. Jonesf561aba2017-03-08 01:02:16 +00001593 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1594 StringRef Val = StringRef(A->getValue());
1595 if (mips::hasCompactBranches(CPUName)) {
1596 if (Val == "never" || Val == "always" || Val == "optimal") {
1597 CmdArgs.push_back("-mllvm");
1598 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1599 } else
1600 D.Diag(diag::err_drv_unsupported_option_argument)
1601 << A->getOption().getName() << Val;
1602 } else
1603 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1604 }
1605}
1606
1607void Clang::AddPPCTargetArgs(const ArgList &Args,
1608 ArgStringList &CmdArgs) const {
1609 // Select the ABI to use.
1610 const char *ABIName = nullptr;
1611 if (getToolChain().getTriple().isOSLinux())
1612 switch (getToolChain().getArch()) {
1613 case llvm::Triple::ppc64: {
1614 // When targeting a processor that supports QPX, or if QPX is
1615 // specifically enabled, default to using the ABI that supports QPX (so
1616 // long as it is not specifically disabled).
1617 bool HasQPX = false;
1618 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1619 HasQPX = A->getValue() == StringRef("a2q");
1620 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1621 if (HasQPX) {
1622 ABIName = "elfv1-qpx";
1623 break;
1624 }
1625
1626 ABIName = "elfv1";
1627 break;
1628 }
1629 case llvm::Triple::ppc64le:
1630 ABIName = "elfv2";
1631 break;
1632 default:
1633 break;
1634 }
1635
1636 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1637 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1638 // the option if given as we don't have backend support for any targets
1639 // that don't use the altivec abi.
1640 if (StringRef(A->getValue()) != "altivec")
1641 ABIName = A->getValue();
1642
1643 ppc::FloatABI FloatABI =
1644 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1645
1646 if (FloatABI == ppc::FloatABI::Soft) {
1647 // Floating point operations and argument passing are soft.
1648 CmdArgs.push_back("-msoft-float");
1649 CmdArgs.push_back("-mfloat-abi");
1650 CmdArgs.push_back("soft");
1651 } else {
1652 // Floating point operations and argument passing are hard.
1653 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1654 CmdArgs.push_back("-mfloat-abi");
1655 CmdArgs.push_back("hard");
1656 }
1657
1658 if (ABIName) {
1659 CmdArgs.push_back("-target-abi");
1660 CmdArgs.push_back(ABIName);
1661 }
1662}
1663
Alex Bradbury71f45452018-01-11 13:36:56 +00001664void Clang::AddRISCVTargetArgs(const ArgList &Args,
1665 ArgStringList &CmdArgs) const {
1666 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001667 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001668 const char *ABIName = nullptr;
1669 const llvm::Triple &Triple = getToolChain().getTriple();
1670 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1671 ABIName = A->getValue();
1672 else if (Triple.getArch() == llvm::Triple::riscv32)
1673 ABIName = "ilp32";
1674 else if (Triple.getArch() == llvm::Triple::riscv64)
1675 ABIName = "lp64";
1676 else
1677 llvm_unreachable("Unexpected triple!");
1678
1679 CmdArgs.push_back("-target-abi");
1680 CmdArgs.push_back(ABIName);
1681}
1682
David L. Jonesf561aba2017-03-08 01:02:16 +00001683void Clang::AddSparcTargetArgs(const ArgList &Args,
1684 ArgStringList &CmdArgs) const {
1685 sparc::FloatABI FloatABI =
1686 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1687
1688 if (FloatABI == sparc::FloatABI::Soft) {
1689 // Floating point operations and argument passing are soft.
1690 CmdArgs.push_back("-msoft-float");
1691 CmdArgs.push_back("-mfloat-abi");
1692 CmdArgs.push_back("soft");
1693 } else {
1694 // Floating point operations and argument passing are hard.
1695 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1696 CmdArgs.push_back("-mfloat-abi");
1697 CmdArgs.push_back("hard");
1698 }
1699}
1700
1701void Clang::AddSystemZTargetArgs(const ArgList &Args,
1702 ArgStringList &CmdArgs) const {
1703 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1704 CmdArgs.push_back("-mbackchain");
1705}
1706
1707void Clang::AddX86TargetArgs(const ArgList &Args,
1708 ArgStringList &CmdArgs) const {
1709 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1710 Args.hasArg(options::OPT_mkernel) ||
1711 Args.hasArg(options::OPT_fapple_kext))
1712 CmdArgs.push_back("-disable-red-zone");
1713
1714 // Default to avoid implicit floating-point for kernel/kext code, but allow
1715 // that to be overridden with -mno-soft-float.
1716 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1717 Args.hasArg(options::OPT_fapple_kext));
1718 if (Arg *A = Args.getLastArg(
1719 options::OPT_msoft_float, options::OPT_mno_soft_float,
1720 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1721 const Option &O = A->getOption();
1722 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1723 O.matches(options::OPT_msoft_float));
1724 }
1725 if (NoImplicitFloat)
1726 CmdArgs.push_back("-no-implicit-float");
1727
1728 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1729 StringRef Value = A->getValue();
1730 if (Value == "intel" || Value == "att") {
1731 CmdArgs.push_back("-mllvm");
1732 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1733 } else {
1734 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1735 << A->getOption().getName() << Value;
1736 }
Nico Webere3712cf2018-01-17 13:34:20 +00001737 } else if (getToolChain().getDriver().IsCLMode()) {
1738 CmdArgs.push_back("-mllvm");
1739 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001740 }
1741
1742 // Set flags to support MCU ABI.
1743 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1744 CmdArgs.push_back("-mfloat-abi");
1745 CmdArgs.push_back("soft");
1746 CmdArgs.push_back("-mstack-alignment=4");
1747 }
1748}
1749
1750void Clang::AddHexagonTargetArgs(const ArgList &Args,
1751 ArgStringList &CmdArgs) const {
1752 CmdArgs.push_back("-mqdsp6-compat");
1753 CmdArgs.push_back("-Wreturn-type");
1754
1755 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001756 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001757 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1758 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001759 }
1760
1761 if (!Args.hasArg(options::OPT_fno_short_enums))
1762 CmdArgs.push_back("-fshort-enums");
1763 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1764 CmdArgs.push_back("-mllvm");
1765 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1766 }
1767 CmdArgs.push_back("-mllvm");
1768 CmdArgs.push_back("-machine-sink-split=0");
1769}
1770
1771void Clang::AddLanaiTargetArgs(const ArgList &Args,
1772 ArgStringList &CmdArgs) const {
1773 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1774 StringRef CPUName = A->getValue();
1775
1776 CmdArgs.push_back("-target-cpu");
1777 CmdArgs.push_back(Args.MakeArgString(CPUName));
1778 }
1779 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1780 StringRef Value = A->getValue();
1781 // Only support mregparm=4 to support old usage. Report error for all other
1782 // cases.
1783 int Mregparm;
1784 if (Value.getAsInteger(10, Mregparm)) {
1785 if (Mregparm != 4) {
1786 getToolChain().getDriver().Diag(
1787 diag::err_drv_unsupported_option_argument)
1788 << A->getOption().getName() << Value;
1789 }
1790 }
1791 }
1792}
1793
1794void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1795 ArgStringList &CmdArgs) const {
1796 // Default to "hidden" visibility.
1797 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1798 options::OPT_fvisibility_ms_compat)) {
1799 CmdArgs.push_back("-fvisibility");
1800 CmdArgs.push_back("hidden");
1801 }
1802}
1803
1804void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1805 StringRef Target, const InputInfo &Output,
1806 const InputInfo &Input, const ArgList &Args) const {
1807 // If this is a dry run, do not create the compilation database file.
1808 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1809 return;
1810
1811 using llvm::yaml::escape;
1812 const Driver &D = getToolChain().getDriver();
1813
1814 if (!CompilationDatabase) {
1815 std::error_code EC;
1816 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1817 if (EC) {
1818 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1819 << EC.message();
1820 return;
1821 }
1822 CompilationDatabase = std::move(File);
1823 }
1824 auto &CDB = *CompilationDatabase;
1825 SmallString<128> Buf;
1826 if (llvm::sys::fs::current_path(Buf))
1827 Buf = ".";
1828 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1829 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1830 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1831 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1832 Buf = "-x";
1833 Buf += types::getTypeName(Input.getType());
1834 CDB << ", \"" << escape(Buf) << "\"";
1835 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1836 Buf = "--sysroot=";
1837 Buf += D.SysRoot;
1838 CDB << ", \"" << escape(Buf) << "\"";
1839 }
1840 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1841 for (auto &A: Args) {
1842 auto &O = A->getOption();
1843 // Skip language selection, which is positional.
1844 if (O.getID() == options::OPT_x)
1845 continue;
1846 // Skip writing dependency output and the compilation database itself.
1847 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1848 continue;
1849 // Skip inputs.
1850 if (O.getKind() == Option::InputClass)
1851 continue;
1852 // All other arguments are quoted and appended.
1853 ArgStringList ASL;
1854 A->render(Args, ASL);
1855 for (auto &it: ASL)
1856 CDB << ", \"" << escape(it) << "\"";
1857 }
1858 Buf = "--target=";
1859 Buf += Target;
1860 CDB << ", \"" << escape(Buf) << "\"]},\n";
1861}
1862
1863static void CollectArgsForIntegratedAssembler(Compilation &C,
1864 const ArgList &Args,
1865 ArgStringList &CmdArgs,
1866 const Driver &D) {
1867 if (UseRelaxAll(C, Args))
1868 CmdArgs.push_back("-mrelax-all");
1869
1870 // Only default to -mincremental-linker-compatible if we think we are
1871 // targeting the MSVC linker.
1872 bool DefaultIncrementalLinkerCompatible =
1873 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1874 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1875 options::OPT_mno_incremental_linker_compatible,
1876 DefaultIncrementalLinkerCompatible))
1877 CmdArgs.push_back("-mincremental-linker-compatible");
1878
1879 switch (C.getDefaultToolChain().getArch()) {
1880 case llvm::Triple::arm:
1881 case llvm::Triple::armeb:
1882 case llvm::Triple::thumb:
1883 case llvm::Triple::thumbeb:
1884 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1885 StringRef Value = A->getValue();
1886 if (Value == "always" || Value == "never" || Value == "arm" ||
1887 Value == "thumb") {
1888 CmdArgs.push_back("-mllvm");
1889 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1890 } else {
1891 D.Diag(diag::err_drv_unsupported_option_argument)
1892 << A->getOption().getName() << Value;
1893 }
1894 }
1895 break;
1896 default:
1897 break;
1898 }
1899
1900 // When passing -I arguments to the assembler we sometimes need to
1901 // unconditionally take the next argument. For example, when parsing
1902 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1903 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1904 // arg after parsing the '-I' arg.
1905 bool TakeNextArg = false;
1906
Petr Hosek5668d832017-11-22 01:38:31 +00001907 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00001908 const char *MipsTargetFeature = nullptr;
1909 for (const Arg *A :
1910 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1911 A->claim();
1912
1913 for (StringRef Value : A->getValues()) {
1914 if (TakeNextArg) {
1915 CmdArgs.push_back(Value.data());
1916 TakeNextArg = false;
1917 continue;
1918 }
1919
1920 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1921 Value == "-mbig-obj")
1922 continue; // LLVM handles bigobj automatically
1923
1924 switch (C.getDefaultToolChain().getArch()) {
1925 default:
1926 break;
Peter Smith3947cb32017-11-20 13:43:55 +00001927 case llvm::Triple::thumb:
1928 case llvm::Triple::thumbeb:
1929 case llvm::Triple::arm:
1930 case llvm::Triple::armeb:
1931 if (Value == "-mthumb")
1932 // -mthumb has already been processed in ComputeLLVMTriple()
1933 // recognize but skip over here.
1934 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00001935 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00001936 case llvm::Triple::mips:
1937 case llvm::Triple::mipsel:
1938 case llvm::Triple::mips64:
1939 case llvm::Triple::mips64el:
1940 if (Value == "--trap") {
1941 CmdArgs.push_back("-target-feature");
1942 CmdArgs.push_back("+use-tcc-in-div");
1943 continue;
1944 }
1945 if (Value == "--break") {
1946 CmdArgs.push_back("-target-feature");
1947 CmdArgs.push_back("-use-tcc-in-div");
1948 continue;
1949 }
1950 if (Value.startswith("-msoft-float")) {
1951 CmdArgs.push_back("-target-feature");
1952 CmdArgs.push_back("+soft-float");
1953 continue;
1954 }
1955 if (Value.startswith("-mhard-float")) {
1956 CmdArgs.push_back("-target-feature");
1957 CmdArgs.push_back("-soft-float");
1958 continue;
1959 }
1960
1961 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1962 .Case("-mips1", "+mips1")
1963 .Case("-mips2", "+mips2")
1964 .Case("-mips3", "+mips3")
1965 .Case("-mips4", "+mips4")
1966 .Case("-mips5", "+mips5")
1967 .Case("-mips32", "+mips32")
1968 .Case("-mips32r2", "+mips32r2")
1969 .Case("-mips32r3", "+mips32r3")
1970 .Case("-mips32r5", "+mips32r5")
1971 .Case("-mips32r6", "+mips32r6")
1972 .Case("-mips64", "+mips64")
1973 .Case("-mips64r2", "+mips64r2")
1974 .Case("-mips64r3", "+mips64r3")
1975 .Case("-mips64r5", "+mips64r5")
1976 .Case("-mips64r6", "+mips64r6")
1977 .Default(nullptr);
1978 if (MipsTargetFeature)
1979 continue;
1980 }
1981
1982 if (Value == "-force_cpusubtype_ALL") {
1983 // Do nothing, this is the default and we don't support anything else.
1984 } else if (Value == "-L") {
1985 CmdArgs.push_back("-msave-temp-labels");
1986 } else if (Value == "--fatal-warnings") {
1987 CmdArgs.push_back("-massembler-fatal-warnings");
1988 } else if (Value == "--noexecstack") {
1989 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001990 } else if (Value.startswith("-compress-debug-sections") ||
1991 Value.startswith("--compress-debug-sections") ||
1992 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00001993 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001994 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00001995 } else if (Value == "-mrelax-relocations=yes" ||
1996 Value == "--mrelax-relocations=yes") {
1997 UseRelaxRelocations = true;
1998 } else if (Value == "-mrelax-relocations=no" ||
1999 Value == "--mrelax-relocations=no") {
2000 UseRelaxRelocations = false;
2001 } else if (Value.startswith("-I")) {
2002 CmdArgs.push_back(Value.data());
2003 // We need to consume the next argument if the current arg is a plain
2004 // -I. The next arg will be the include directory.
2005 if (Value == "-I")
2006 TakeNextArg = true;
2007 } else if (Value.startswith("-gdwarf-")) {
2008 // "-gdwarf-N" options are not cc1as options.
2009 unsigned DwarfVersion = DwarfVersionNum(Value);
2010 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2011 CmdArgs.push_back(Value.data());
2012 } else {
2013 RenderDebugEnablingArgs(Args, CmdArgs,
2014 codegenoptions::LimitedDebugInfo,
2015 DwarfVersion, llvm::DebuggerKind::Default);
2016 }
2017 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2018 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2019 // Do nothing, we'll validate it later.
2020 } else if (Value == "-defsym") {
2021 if (A->getNumValues() != 2) {
2022 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2023 break;
2024 }
2025 const char *S = A->getValue(1);
2026 auto Pair = StringRef(S).split('=');
2027 auto Sym = Pair.first;
2028 auto SVal = Pair.second;
2029
2030 if (Sym.empty() || SVal.empty()) {
2031 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2032 break;
2033 }
2034 int64_t IVal;
2035 if (SVal.getAsInteger(0, IVal)) {
2036 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2037 break;
2038 }
2039 CmdArgs.push_back(Value.data());
2040 TakeNextArg = true;
2041 } else {
2042 D.Diag(diag::err_drv_unsupported_option_argument)
2043 << A->getOption().getName() << Value;
2044 }
2045 }
2046 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002047 if (UseRelaxRelocations)
2048 CmdArgs.push_back("--mrelax-relocations");
2049 if (MipsTargetFeature != nullptr) {
2050 CmdArgs.push_back("-target-feature");
2051 CmdArgs.push_back(MipsTargetFeature);
2052 }
2053}
2054
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002055static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2056 bool OFastEnabled, const ArgList &Args,
2057 ArgStringList &CmdArgs) {
2058 // Handle various floating point optimization flags, mapping them to the
2059 // appropriate LLVM code generation flags. This is complicated by several
2060 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002061 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002062 // LLVM flags based on the final state.
2063 bool HonorINFs = true;
2064 bool HonorNaNs = true;
2065 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2066 bool MathErrno = TC.IsMathErrnoDefault();
2067 bool AssociativeMath = false;
2068 bool ReciprocalMath = false;
2069 bool SignedZeros = true;
2070 bool TrappingMath = true;
2071 StringRef DenormalFPMath = "";
2072 StringRef FPContract = "";
2073
2074 for (const Arg *A : Args) {
2075 switch (A->getOption().getID()) {
2076 // If this isn't an FP option skip the claim below
2077 default: continue;
2078
2079 // Options controlling individual features
2080 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2081 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2082 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2083 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2084 case options::OPT_fmath_errno: MathErrno = true; break;
2085 case options::OPT_fno_math_errno: MathErrno = false; break;
2086 case options::OPT_fassociative_math: AssociativeMath = true; break;
2087 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2088 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2089 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2090 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2091 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2092 case options::OPT_ftrapping_math: TrappingMath = true; break;
2093 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2094
2095 case options::OPT_fdenormal_fp_math_EQ:
2096 DenormalFPMath = A->getValue();
2097 break;
2098
2099 // Validate and pass through -fp-contract option.
2100 case options::OPT_ffp_contract: {
2101 StringRef Val = A->getValue();
2102 if (Val == "fast" || Val == "on" || Val == "off")
2103 FPContract = Val;
2104 else
2105 D.Diag(diag::err_drv_unsupported_option_argument)
2106 << A->getOption().getName() << Val;
2107 break;
2108 }
2109
2110 case options::OPT_ffinite_math_only:
2111 HonorINFs = false;
2112 HonorNaNs = false;
2113 break;
2114 case options::OPT_fno_finite_math_only:
2115 HonorINFs = true;
2116 HonorNaNs = true;
2117 break;
2118
2119 case options::OPT_funsafe_math_optimizations:
2120 AssociativeMath = true;
2121 ReciprocalMath = true;
2122 SignedZeros = false;
2123 TrappingMath = false;
2124 break;
2125 case options::OPT_fno_unsafe_math_optimizations:
2126 AssociativeMath = false;
2127 ReciprocalMath = false;
2128 SignedZeros = true;
2129 TrappingMath = true;
2130 // -fno_unsafe_math_optimizations restores default denormal handling
2131 DenormalFPMath = "";
2132 break;
2133
2134 case options::OPT_Ofast:
2135 // If -Ofast is the optimization level, then -ffast-math should be enabled
2136 if (!OFastEnabled)
2137 continue;
2138 LLVM_FALLTHROUGH;
2139 case options::OPT_ffast_math:
2140 HonorINFs = false;
2141 HonorNaNs = false;
2142 MathErrno = false;
2143 AssociativeMath = true;
2144 ReciprocalMath = true;
2145 SignedZeros = false;
2146 TrappingMath = false;
2147 // If fast-math is set then set the fp-contract mode to fast.
2148 FPContract = "fast";
2149 break;
2150 case options::OPT_fno_fast_math:
2151 HonorINFs = true;
2152 HonorNaNs = true;
2153 // Turning on -ffast-math (with either flag) removes the need for
2154 // MathErrno. However, turning *off* -ffast-math merely restores the
2155 // toolchain default (which may be false).
2156 MathErrno = TC.IsMathErrnoDefault();
2157 AssociativeMath = false;
2158 ReciprocalMath = false;
2159 SignedZeros = true;
2160 TrappingMath = true;
2161 // -fno_fast_math restores default denormal and fpcontract handling
2162 DenormalFPMath = "";
2163 FPContract = "";
2164 break;
2165 }
2166
2167 // If we handled this option claim it
2168 A->claim();
2169 }
2170
2171 if (!HonorINFs)
2172 CmdArgs.push_back("-menable-no-infs");
2173
2174 if (!HonorNaNs)
2175 CmdArgs.push_back("-menable-no-nans");
2176
2177 if (MathErrno)
2178 CmdArgs.push_back("-fmath-errno");
2179
2180 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2181 !TrappingMath)
2182 CmdArgs.push_back("-menable-unsafe-fp-math");
2183
2184 if (!SignedZeros)
2185 CmdArgs.push_back("-fno-signed-zeros");
2186
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002187 if (AssociativeMath && !SignedZeros && !TrappingMath)
2188 CmdArgs.push_back("-mreassociate");
2189
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002190 if (ReciprocalMath)
2191 CmdArgs.push_back("-freciprocal-math");
2192
2193 if (!TrappingMath)
2194 CmdArgs.push_back("-fno-trapping-math");
2195
2196 if (!DenormalFPMath.empty())
2197 CmdArgs.push_back(
2198 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2199
2200 if (!FPContract.empty())
2201 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2202
2203 ParseMRecip(D, Args, CmdArgs);
2204
2205 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2206 // individual features enabled by -ffast-math instead of the option itself as
2207 // that's consistent with gcc's behaviour.
2208 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2209 ReciprocalMath && !SignedZeros && !TrappingMath)
2210 CmdArgs.push_back("-ffast-math");
2211
2212 // Handle __FINITE_MATH_ONLY__ similarly.
2213 if (!HonorINFs && !HonorNaNs)
2214 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002215
2216 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2217 CmdArgs.push_back("-mfpmath");
2218 CmdArgs.push_back(A->getValue());
2219 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002220
2221 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002222 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2223 options::OPT_fstrict_float_cast_overflow, false))
2224 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002225}
2226
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002227static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2228 const llvm::Triple &Triple,
2229 const InputInfo &Input) {
2230 // Enable region store model by default.
2231 CmdArgs.push_back("-analyzer-store=region");
2232
2233 // Treat blocks as analysis entry points.
2234 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2235
2236 CmdArgs.push_back("-analyzer-eagerly-assume");
2237
2238 // Add default argument set.
2239 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2240 CmdArgs.push_back("-analyzer-checker=core");
2241 CmdArgs.push_back("-analyzer-checker=apiModeling");
2242
2243 if (!Triple.isWindowsMSVCEnvironment()) {
2244 CmdArgs.push_back("-analyzer-checker=unix");
2245 } else {
2246 // Enable "unix" checkers that also work on Windows.
2247 CmdArgs.push_back("-analyzer-checker=unix.API");
2248 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2249 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2250 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2251 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2252 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2253 }
2254
2255 // Disable some unix checkers for PS4.
2256 if (Triple.isPS4CPU()) {
2257 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2258 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2259 }
2260
2261 if (Triple.isOSDarwin())
2262 CmdArgs.push_back("-analyzer-checker=osx");
2263
2264 CmdArgs.push_back("-analyzer-checker=deadcode");
2265
2266 if (types::isCXX(Input.getType()))
2267 CmdArgs.push_back("-analyzer-checker=cplusplus");
2268
2269 if (!Triple.isPS4CPU()) {
2270 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2271 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2272 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2273 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2274 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2275 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2276 }
2277
2278 // Default nullability checks.
2279 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2280 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2281 }
2282
2283 // Set the output format. The default is plist, for (lame) historical reasons.
2284 CmdArgs.push_back("-analyzer-output");
2285 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2286 CmdArgs.push_back(A->getValue());
2287 else
2288 CmdArgs.push_back("plist");
2289
2290 // Disable the presentation of standard compiler warnings when using
2291 // --analyze. We only want to show static analyzer diagnostics or frontend
2292 // errors.
2293 CmdArgs.push_back("-w");
2294
2295 // Add -Xanalyzer arguments when running as analyzer.
2296 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2297}
2298
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002299static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002300 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002301 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2302
2303 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2304 // doesn't even have a stack!
2305 if (EffectiveTriple.isNVPTX())
2306 return;
2307
2308 // -stack-protector=0 is default.
2309 unsigned StackProtectorLevel = 0;
2310 unsigned DefaultStackProtectorLevel =
2311 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2312
2313 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2314 options::OPT_fstack_protector_all,
2315 options::OPT_fstack_protector_strong,
2316 options::OPT_fstack_protector)) {
2317 if (A->getOption().matches(options::OPT_fstack_protector))
2318 StackProtectorLevel =
2319 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2320 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2321 StackProtectorLevel = LangOptions::SSPStrong;
2322 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2323 StackProtectorLevel = LangOptions::SSPReq;
2324 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002325 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002326 }
2327
2328 if (StackProtectorLevel) {
2329 CmdArgs.push_back("-stack-protector");
2330 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2331 }
2332
2333 // --param ssp-buffer-size=
2334 for (const Arg *A : Args.filtered(options::OPT__param)) {
2335 StringRef Str(A->getValue());
2336 if (Str.startswith("ssp-buffer-size=")) {
2337 if (StackProtectorLevel) {
2338 CmdArgs.push_back("-stack-protector-buffer-size");
2339 // FIXME: Verify the argument is a valid integer.
2340 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2341 }
2342 A->claim();
2343 }
2344 }
2345}
2346
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002347static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2348 const unsigned ForwardedArguments[] = {
2349 options::OPT_cl_opt_disable,
2350 options::OPT_cl_strict_aliasing,
2351 options::OPT_cl_single_precision_constant,
2352 options::OPT_cl_finite_math_only,
2353 options::OPT_cl_kernel_arg_info,
2354 options::OPT_cl_unsafe_math_optimizations,
2355 options::OPT_cl_fast_relaxed_math,
2356 options::OPT_cl_mad_enable,
2357 options::OPT_cl_no_signed_zeros,
2358 options::OPT_cl_denorms_are_zero,
2359 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002360 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002361 };
2362
2363 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2364 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2365 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2366 }
2367
2368 for (const auto &Arg : ForwardedArguments)
2369 if (const auto *A = Args.getLastArg(Arg))
2370 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2371}
2372
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002373static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2374 ArgStringList &CmdArgs) {
2375 bool ARCMTEnabled = false;
2376 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2377 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2378 options::OPT_ccc_arcmt_modify,
2379 options::OPT_ccc_arcmt_migrate)) {
2380 ARCMTEnabled = true;
2381 switch (A->getOption().getID()) {
2382 default: llvm_unreachable("missed a case");
2383 case options::OPT_ccc_arcmt_check:
2384 CmdArgs.push_back("-arcmt-check");
2385 break;
2386 case options::OPT_ccc_arcmt_modify:
2387 CmdArgs.push_back("-arcmt-modify");
2388 break;
2389 case options::OPT_ccc_arcmt_migrate:
2390 CmdArgs.push_back("-arcmt-migrate");
2391 CmdArgs.push_back("-mt-migrate-directory");
2392 CmdArgs.push_back(A->getValue());
2393
2394 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2395 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2396 break;
2397 }
2398 }
2399 } else {
2400 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2401 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2402 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2403 }
2404
2405 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2406 if (ARCMTEnabled)
2407 D.Diag(diag::err_drv_argument_not_allowed_with)
2408 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2409
2410 CmdArgs.push_back("-mt-migrate-directory");
2411 CmdArgs.push_back(A->getValue());
2412
2413 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2414 options::OPT_objcmt_migrate_subscripting,
2415 options::OPT_objcmt_migrate_property)) {
2416 // None specified, means enable them all.
2417 CmdArgs.push_back("-objcmt-migrate-literals");
2418 CmdArgs.push_back("-objcmt-migrate-subscripting");
2419 CmdArgs.push_back("-objcmt-migrate-property");
2420 } else {
2421 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2422 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2423 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2424 }
2425 } else {
2426 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2427 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2428 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2429 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2430 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2431 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2432 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2433 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2434 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2435 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2436 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2437 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2438 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2439 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2440 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2441 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2442 }
2443}
2444
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002445static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2446 const ArgList &Args, ArgStringList &CmdArgs) {
2447 // -fbuiltin is default unless -mkernel is used.
2448 bool UseBuiltins =
2449 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2450 !Args.hasArg(options::OPT_mkernel));
2451 if (!UseBuiltins)
2452 CmdArgs.push_back("-fno-builtin");
2453
2454 // -ffreestanding implies -fno-builtin.
2455 if (Args.hasArg(options::OPT_ffreestanding))
2456 UseBuiltins = false;
2457
2458 // Process the -fno-builtin-* options.
2459 for (const auto &Arg : Args) {
2460 const Option &O = Arg->getOption();
2461 if (!O.matches(options::OPT_fno_builtin_))
2462 continue;
2463
2464 Arg->claim();
2465
2466 // If -fno-builtin is specified, then there's no need to pass the option to
2467 // the frontend.
2468 if (!UseBuiltins)
2469 continue;
2470
2471 StringRef FuncName = Arg->getValue();
2472 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2473 }
2474
2475 // le32-specific flags:
2476 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2477 // by default.
2478 if (TC.getArch() == llvm::Triple::le32)
2479 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002480}
2481
Adrian Prantl70599032018-02-09 18:43:10 +00002482void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2483 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2484 llvm::sys::path::append(Result, "org.llvm.clang.");
2485 appendUserToPath(Result);
2486 llvm::sys::path::append(Result, "ModuleCache");
2487}
2488
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002489static void RenderModulesOptions(Compilation &C, const Driver &D,
2490 const ArgList &Args, const InputInfo &Input,
2491 const InputInfo &Output,
2492 ArgStringList &CmdArgs, bool &HaveModules) {
2493 // -fmodules enables the use of precompiled modules (off by default).
2494 // Users can pass -fno-cxx-modules to turn off modules support for
2495 // C++/Objective-C++ programs.
2496 bool HaveClangModules = false;
2497 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2498 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2499 options::OPT_fno_cxx_modules, true);
2500 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2501 CmdArgs.push_back("-fmodules");
2502 HaveClangModules = true;
2503 }
2504 }
2505
2506 HaveModules = HaveClangModules;
2507 if (Args.hasArg(options::OPT_fmodules_ts)) {
2508 CmdArgs.push_back("-fmodules-ts");
2509 HaveModules = true;
2510 }
2511
2512 // -fmodule-maps enables implicit reading of module map files. By default,
2513 // this is enabled if we are using Clang's flavor of precompiled modules.
2514 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2515 options::OPT_fno_implicit_module_maps, HaveClangModules))
2516 CmdArgs.push_back("-fimplicit-module-maps");
2517
2518 // -fmodules-decluse checks that modules used are declared so (off by default)
2519 if (Args.hasFlag(options::OPT_fmodules_decluse,
2520 options::OPT_fno_modules_decluse, false))
2521 CmdArgs.push_back("-fmodules-decluse");
2522
2523 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2524 // all #included headers are part of modules.
2525 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2526 options::OPT_fno_modules_strict_decluse, false))
2527 CmdArgs.push_back("-fmodules-strict-decluse");
2528
2529 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002530 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002531 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2532 options::OPT_fno_implicit_modules, HaveClangModules)) {
2533 if (HaveModules)
2534 CmdArgs.push_back("-fno-implicit-modules");
2535 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002536 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002537 // -fmodule-cache-path specifies where our implicitly-built module files
2538 // should be written.
2539 SmallString<128> Path;
2540 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2541 Path = A->getValue();
2542
2543 if (C.isForDiagnostics()) {
2544 // When generating crash reports, we want to emit the modules along with
2545 // the reproduction sources, so we ignore any provided module path.
2546 Path = Output.getFilename();
2547 llvm::sys::path::replace_extension(Path, ".cache");
2548 llvm::sys::path::append(Path, "modules");
2549 } else if (Path.empty()) {
2550 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002551 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002552 }
2553
2554 const char Arg[] = "-fmodules-cache-path=";
2555 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2556 CmdArgs.push_back(Args.MakeArgString(Path));
2557 }
2558
2559 if (HaveModules) {
2560 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2561 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2562 CmdArgs.push_back(Args.MakeArgString(
2563 std::string("-fprebuilt-module-path=") + A->getValue()));
2564 A->claim();
2565 }
2566 }
2567
2568 // -fmodule-name specifies the module that is currently being built (or
2569 // used for header checking by -fmodule-maps).
2570 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2571
2572 // -fmodule-map-file can be used to specify files containing module
2573 // definitions.
2574 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2575
2576 // -fbuiltin-module-map can be used to load the clang
2577 // builtin headers modulemap file.
2578 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2579 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2580 llvm::sys::path::append(BuiltinModuleMap, "include");
2581 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2582 if (llvm::sys::fs::exists(BuiltinModuleMap))
2583 CmdArgs.push_back(
2584 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2585 }
2586
2587 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2588 // names to precompiled module files (the module is loaded only if used).
2589 // The -fmodule-file=<file> form can be used to unconditionally load
2590 // precompiled module files (whether used or not).
2591 if (HaveModules)
2592 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2593 else
2594 Args.ClaimAllArgs(options::OPT_fmodule_file);
2595
2596 // When building modules and generating crashdumps, we need to dump a module
2597 // dependency VFS alongside the output.
2598 if (HaveClangModules && C.isForDiagnostics()) {
2599 SmallString<128> VFSDir(Output.getFilename());
2600 llvm::sys::path::replace_extension(VFSDir, ".cache");
2601 // Add the cache directory as a temp so the crash diagnostics pick it up.
2602 C.addTempFile(Args.MakeArgString(VFSDir));
2603
2604 llvm::sys::path::append(VFSDir, "vfs");
2605 CmdArgs.push_back("-module-dependency-dir");
2606 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2607 }
2608
2609 if (HaveClangModules)
2610 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2611
2612 // Pass through all -fmodules-ignore-macro arguments.
2613 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2614 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2615 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2616
2617 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2618
2619 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2620 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2621 D.Diag(diag::err_drv_argument_not_allowed_with)
2622 << A->getAsString(Args) << "-fbuild-session-timestamp";
2623
2624 llvm::sys::fs::file_status Status;
2625 if (llvm::sys::fs::status(A->getValue(), Status))
2626 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2627 CmdArgs.push_back(
2628 Args.MakeArgString("-fbuild-session-timestamp=" +
2629 Twine((uint64_t)Status.getLastModificationTime()
2630 .time_since_epoch()
2631 .count())));
2632 }
2633
2634 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2635 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2636 options::OPT_fbuild_session_file))
2637 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2638
2639 Args.AddLastArg(CmdArgs,
2640 options::OPT_fmodules_validate_once_per_build_session);
2641 }
2642
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002643 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2644 options::OPT_fno_modules_validate_system_headers,
2645 ImplicitModules))
2646 CmdArgs.push_back("-fmodules-validate-system-headers");
2647
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002648 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2649}
2650
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002651static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2652 ArgStringList &CmdArgs) {
2653 // -fsigned-char is default.
2654 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2655 options::OPT_fno_signed_char,
2656 options::OPT_funsigned_char,
2657 options::OPT_fno_unsigned_char)) {
2658 if (A->getOption().matches(options::OPT_funsigned_char) ||
2659 A->getOption().matches(options::OPT_fno_signed_char)) {
2660 CmdArgs.push_back("-fno-signed-char");
2661 }
2662 } else if (!isSignedCharDefault(T)) {
2663 CmdArgs.push_back("-fno-signed-char");
2664 }
2665
Richard Smith3a8244d2018-05-01 05:02:45 +00002666 if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2667 CmdArgs.push_back("-fchar8_t");
2668
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002669 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2670 options::OPT_fno_short_wchar)) {
2671 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2672 CmdArgs.push_back("-fwchar-type=short");
2673 CmdArgs.push_back("-fno-signed-wchar");
2674 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002675 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002676 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002677 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2678 T.getOS() == llvm::Triple::OpenBSD))
2679 CmdArgs.push_back("-fno-signed-wchar");
2680 else
2681 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002682 }
2683 }
2684}
2685
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002686static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2687 const llvm::Triple &T, const ArgList &Args,
2688 ObjCRuntime &Runtime, bool InferCovariantReturns,
2689 const InputInfo &Input, ArgStringList &CmdArgs) {
2690 const llvm::Triple::ArchType Arch = TC.getArch();
2691
2692 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2693 // is the default. Except for deployment target of 10.5, next runtime is
2694 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2695 if (Runtime.isNonFragile()) {
2696 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2697 options::OPT_fno_objc_legacy_dispatch,
2698 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2699 if (TC.UseObjCMixedDispatch())
2700 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2701 else
2702 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2703 }
2704 }
2705
2706 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2707 // to do Array/Dictionary subscripting by default.
2708 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2709 !T.isMacOSXVersionLT(10, 7) &&
2710 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2711 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2712
2713 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2714 // NOTE: This logic is duplicated in ToolChains.cpp.
2715 if (isObjCAutoRefCount(Args)) {
2716 TC.CheckObjCARC();
2717
2718 CmdArgs.push_back("-fobjc-arc");
2719
2720 // FIXME: It seems like this entire block, and several around it should be
2721 // wrapped in isObjC, but for now we just use it here as this is where it
2722 // was being used previously.
2723 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2724 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2725 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2726 else
2727 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2728 }
2729
2730 // Allow the user to enable full exceptions code emission.
2731 // We default off for Objective-C, on for Objective-C++.
2732 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2733 options::OPT_fno_objc_arc_exceptions,
2734 /*default=*/types::isCXX(Input.getType())))
2735 CmdArgs.push_back("-fobjc-arc-exceptions");
2736 }
2737
2738 // Silence warning for full exception code emission options when explicitly
2739 // set to use no ARC.
2740 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2741 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2742 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2743 }
2744
2745 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2746 // rewriter.
2747 if (InferCovariantReturns)
2748 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2749
2750 // Pass down -fobjc-weak or -fno-objc-weak if present.
2751 if (types::isObjC(Input.getType())) {
2752 auto WeakArg =
2753 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2754 if (!WeakArg) {
2755 // nothing to do
2756 } else if (!Runtime.allowsWeak()) {
2757 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2758 D.Diag(diag::err_objc_weak_unsupported);
2759 } else {
2760 WeakArg->render(Args, CmdArgs);
2761 }
2762 }
2763}
2764
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002765static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2766 ArgStringList &CmdArgs) {
2767 bool CaretDefault = true;
2768 bool ColumnDefault = true;
2769
2770 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2771 options::OPT__SLASH_diagnostics_column,
2772 options::OPT__SLASH_diagnostics_caret)) {
2773 switch (A->getOption().getID()) {
2774 case options::OPT__SLASH_diagnostics_caret:
2775 CaretDefault = true;
2776 ColumnDefault = true;
2777 break;
2778 case options::OPT__SLASH_diagnostics_column:
2779 CaretDefault = false;
2780 ColumnDefault = true;
2781 break;
2782 case options::OPT__SLASH_diagnostics_classic:
2783 CaretDefault = false;
2784 ColumnDefault = false;
2785 break;
2786 }
2787 }
2788
2789 // -fcaret-diagnostics is default.
2790 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2791 options::OPT_fno_caret_diagnostics, CaretDefault))
2792 CmdArgs.push_back("-fno-caret-diagnostics");
2793
2794 // -fdiagnostics-fixit-info is default, only pass non-default.
2795 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2796 options::OPT_fno_diagnostics_fixit_info))
2797 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2798
2799 // Enable -fdiagnostics-show-option by default.
2800 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2801 options::OPT_fno_diagnostics_show_option))
2802 CmdArgs.push_back("-fdiagnostics-show-option");
2803
2804 if (const Arg *A =
2805 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2806 CmdArgs.push_back("-fdiagnostics-show-category");
2807 CmdArgs.push_back(A->getValue());
2808 }
2809
2810 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2811 options::OPT_fno_diagnostics_show_hotness, false))
2812 CmdArgs.push_back("-fdiagnostics-show-hotness");
2813
2814 if (const Arg *A =
2815 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2816 std::string Opt =
2817 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2818 CmdArgs.push_back(Args.MakeArgString(Opt));
2819 }
2820
2821 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2822 CmdArgs.push_back("-fdiagnostics-format");
2823 CmdArgs.push_back(A->getValue());
2824 }
2825
2826 if (const Arg *A = Args.getLastArg(
2827 options::OPT_fdiagnostics_show_note_include_stack,
2828 options::OPT_fno_diagnostics_show_note_include_stack)) {
2829 const Option &O = A->getOption();
2830 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2831 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2832 else
2833 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2834 }
2835
2836 // Color diagnostics are parsed by the driver directly from argv and later
2837 // re-parsed to construct this job; claim any possible color diagnostic here
2838 // to avoid warn_drv_unused_argument and diagnose bad
2839 // OPT_fdiagnostics_color_EQ values.
2840 for (const Arg *A : Args) {
2841 const Option &O = A->getOption();
2842 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2843 !O.matches(options::OPT_fdiagnostics_color) &&
2844 !O.matches(options::OPT_fno_color_diagnostics) &&
2845 !O.matches(options::OPT_fno_diagnostics_color) &&
2846 !O.matches(options::OPT_fdiagnostics_color_EQ))
2847 continue;
2848
2849 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2850 StringRef Value(A->getValue());
2851 if (Value != "always" && Value != "never" && Value != "auto")
2852 D.Diag(diag::err_drv_clang_unsupported)
2853 << ("-fdiagnostics-color=" + Value).str();
2854 }
2855 A->claim();
2856 }
2857
2858 if (D.getDiags().getDiagnosticOptions().ShowColors)
2859 CmdArgs.push_back("-fcolor-diagnostics");
2860
2861 if (Args.hasArg(options::OPT_fansi_escape_codes))
2862 CmdArgs.push_back("-fansi-escape-codes");
2863
2864 if (!Args.hasFlag(options::OPT_fshow_source_location,
2865 options::OPT_fno_show_source_location))
2866 CmdArgs.push_back("-fno-show-source-location");
2867
2868 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2869 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2870
2871 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2872 ColumnDefault))
2873 CmdArgs.push_back("-fno-show-column");
2874
2875 if (!Args.hasFlag(options::OPT_fspell_checking,
2876 options::OPT_fno_spell_checking))
2877 CmdArgs.push_back("-fno-spell-checking");
2878}
2879
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002880static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2881 const llvm::Triple &T, const ArgList &Args,
2882 bool EmitCodeView, bool IsWindowsMSVC,
2883 ArgStringList &CmdArgs,
2884 codegenoptions::DebugInfoKind &DebugInfoKind,
2885 const Arg *&SplitDWARFArg) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002886 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002887 options::OPT_fno_debug_info_for_profiling, false) &&
2888 checkDebugInfoOption(
2889 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002890 CmdArgs.push_back("-fdebug-info-for-profiling");
2891
2892 // The 'g' groups options involve a somewhat intricate sequence of decisions
2893 // about what to pass from the driver to the frontend, but by the time they
2894 // reach cc1 they've been factored into three well-defined orthogonal choices:
2895 // * what level of debug info to generate
2896 // * what dwarf version to write
2897 // * what debugger tuning to use
2898 // This avoids having to monkey around further in cc1 other than to disable
2899 // codeview if not running in a Windows environment. Perhaps even that
2900 // decision should be made in the driver as well though.
2901 unsigned DWARFVersion = 0;
2902 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2903
2904 bool SplitDWARFInlining =
2905 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2906 options::OPT_fno_split_dwarf_inlining, true);
2907
2908 Args.ClaimAllArgs(options::OPT_g_Group);
2909
2910 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2911
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002912 if (SplitDWARFArg && !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
2913 SplitDWARFArg = nullptr;
2914 SplitDWARFInlining = false;
2915 }
2916
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002917 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002918 if (checkDebugInfoOption(A, Args, D, TC)) {
2919 // If the last option explicitly specified a debug-info level, use it.
2920 if (A->getOption().matches(options::OPT_gN_Group)) {
2921 DebugInfoKind = DebugLevelToInfoKind(*A);
2922 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2923 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2924 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2925 // This gets a bit more complicated if you've disabled inline info in
2926 // the skeleton CUs (SplitDWARFInlining) - then there's value in
2927 // composing split-dwarf and line-tables-only, so let those compose
2928 // naturally in that case. And if you just turned off debug info,
2929 // (-gsplit-dwarf -g0) - do that.
2930 if (SplitDWARFArg) {
2931 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2932 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2933 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2934 SplitDWARFInlining))
2935 SplitDWARFArg = nullptr;
2936 } else if (SplitDWARFInlining)
2937 DebugInfoKind = codegenoptions::NoDebugInfo;
2938 }
2939 } else {
2940 // For any other 'g' option, use Limited.
2941 DebugInfoKind = codegenoptions::LimitedDebugInfo;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002942 }
2943 } else {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002944 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2945 }
2946 }
2947
2948 // If a debugger tuning argument appeared, remember it.
2949 if (const Arg *A =
2950 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002951 if (checkDebugInfoOption(A, Args, D, TC)) {
2952 if (A->getOption().matches(options::OPT_glldb))
2953 DebuggerTuning = llvm::DebuggerKind::LLDB;
2954 else if (A->getOption().matches(options::OPT_gsce))
2955 DebuggerTuning = llvm::DebuggerKind::SCE;
2956 else
2957 DebuggerTuning = llvm::DebuggerKind::GDB;
2958 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002959 }
2960
2961 // If a -gdwarf argument appeared, remember it.
2962 if (const Arg *A =
2963 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2964 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002965 if (checkDebugInfoOption(A, Args, D, TC))
2966 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002967
2968 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2969 // argument parsing.
Reid Kleckner54af3e72018-02-26 22:55:33 +00002970 if (EmitCodeView) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002971 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
2972 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
2973 if (EmitCodeView) {
2974 // DWARFVersion remains at 0 if no explicit choice was made.
2975 CmdArgs.push_back("-gcodeview");
2976 }
2977 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002978 }
2979
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002980 if (!EmitCodeView && DWARFVersion == 0 &&
2981 DebugInfoKind != codegenoptions::NoDebugInfo)
2982 DWARFVersion = TC.GetDefaultDwarfVersion();
2983
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002984 // We ignore flag -gstrict-dwarf for now.
2985 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2986 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2987
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002988 // Column info is included by default for everything except SCE and
2989 // CodeView. Clang doesn't track end columns, just starting columns, which,
2990 // in theory, is fine for CodeView (and PDB). In practice, however, the
2991 // Microsoft debuggers don't handle missing end columns well, so it's better
2992 // not to include any column info.
2993 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
2994 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002995 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00002996 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00002997 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002998 CmdArgs.push_back("-dwarf-column-info");
2999
3000 // FIXME: Move backend command line options to the module.
3001 // If -gline-tables-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003002 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3003 if (checkDebugInfoOption(A, Args, D, TC)) {
3004 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly) {
3005 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3006 CmdArgs.push_back("-dwarf-ext-refs");
3007 CmdArgs.push_back("-fmodule-format=obj");
3008 }
3009 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003010
3011 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3012 // splitting and extraction.
3013 // FIXME: Currently only works on Linux.
3014 if (T.isOSLinux()) {
3015 if (!SplitDWARFInlining)
3016 CmdArgs.push_back("-fno-split-dwarf-inlining");
3017
3018 if (SplitDWARFArg) {
3019 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3020 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3021 CmdArgs.push_back("-enable-split-dwarf");
3022 }
3023 }
3024
3025 // After we've dealt with all combinations of things that could
3026 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3027 // figure out if we need to "upgrade" it to standalone debug info.
3028 // We parse these two '-f' options whether or not they will be used,
3029 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3030 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3031 options::OPT_fno_standalone_debug,
3032 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003033 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3034 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003035 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3036 DebugInfoKind = codegenoptions::FullDebugInfo;
3037
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003038 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3039 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003040 // Source embedding is a vendor extension to DWARF v5. By now we have
3041 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003042 // fallen back to the target default, so if this is still not at least 5
3043 // we emit an error.
3044 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003045 if (DWARFVersion < 5)
3046 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003047 << A->getAsString(Args) << "-gdwarf-5";
3048 else if (checkDebugInfoOption(A, Args, D, TC))
3049 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003050 }
3051
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003052 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3053 DebuggerTuning);
3054
3055 // -fdebug-macro turns on macro debug info generation.
3056 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3057 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003058 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3059 D, TC))
3060 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003061
3062 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikiecb7b6af2018-06-28 22:58:04 +00003063 if (Args.hasFlag(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3064 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003065 if (checkDebugInfoOption(Args.getLastArg(options::OPT_ggnu_pubnames), Args,
3066 D, TC))
3067 CmdArgs.push_back("-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003068
3069 // -gdwarf-aranges turns on the emission of the aranges section in the
3070 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003071 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003072 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3073 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3074 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3075 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003076 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003077 CmdArgs.push_back("-generate-arange-section");
3078 }
3079
3080 if (Args.hasFlag(options::OPT_fdebug_types_section,
3081 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003082 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003083 D.Diag(diag::err_drv_unsupported_opt_for_target)
3084 << Args.getLastArg(options::OPT_fdebug_types_section)
3085 ->getAsString(Args)
3086 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003087 } else if (checkDebugInfoOption(
3088 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3089 TC)) {
3090 CmdArgs.push_back("-mllvm");
3091 CmdArgs.push_back("-generate-type-units");
3092 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003093 }
3094
Paul Robinson1787f812017-09-28 18:37:02 +00003095 // Decide how to render forward declarations of template instantiations.
3096 // SCE wants full descriptions, others just get them in the name.
3097 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3098 CmdArgs.push_back("-debug-forward-template-params");
3099
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003100 // Do we need to explicitly import anonymous namespaces into the parent
3101 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003102 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3103 CmdArgs.push_back("-dwarf-explicit-import");
3104
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003105 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003106}
3107
David L. Jonesf561aba2017-03-08 01:02:16 +00003108void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3109 const InputInfo &Output, const InputInfoList &Inputs,
3110 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003111 const llvm::Triple &RawTriple = getToolChain().getTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003112 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3113 const std::string &TripleStr = Triple.getTriple();
3114
3115 bool KernelOrKext =
3116 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3117 const Driver &D = getToolChain().getDriver();
3118 ArgStringList CmdArgs;
3119
3120 // Check number of inputs for sanity. We need at least one input.
3121 assert(Inputs.size() >= 1 && "Must have at least one input.");
3122 const InputInfo &Input = Inputs[0];
Yaxun Liu398612b2018-05-08 21:02:12 +00003123 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003124 // device-side compilations). OpenMP device jobs also take the host IR as a
3125 // second input. All other jobs are expected to have exactly one
3126 // input.
3127 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003128 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003129 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Yaxun Liu398612b2018-05-08 21:02:12 +00003130 assert((IsCuda || IsHIP || (IsOpenMPDevice && Inputs.size() == 2) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003131 Inputs.size() == 1) &&
3132 "Unable to handle multiple inputs.");
3133
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00003134 const llvm::Triple *AuxTriple =
3135 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3136
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003137 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3138 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3139 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003140 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003141
Yaxun Liu398612b2018-05-08 21:02:12 +00003142 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3143 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3144 // Windows), we need to pass Windows-specific flags to cc1.
3145 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003146 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3147 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3148 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3149 }
3150
3151 // C++ is not supported for IAMCU.
3152 if (IsIAMCU && types::isCXX(Input.getType()))
3153 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3154
3155 // Invoke ourselves in -cc1 mode.
3156 //
3157 // FIXME: Implement custom jobs for internal actions.
3158 CmdArgs.push_back("-cc1");
3159
3160 // Add the "effective" target triple.
3161 CmdArgs.push_back("-triple");
3162 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3163
3164 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3165 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3166 Args.ClaimAllArgs(options::OPT_MJ);
3167 }
3168
Yaxun Liu398612b2018-05-08 21:02:12 +00003169 if (IsCuda || IsHIP) {
3170 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3171 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003172 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003173 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3174 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003175 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3176 ->getTriple()
3177 .normalize();
3178 else
Yaxun Liu398612b2018-05-08 21:02:12 +00003179 NormalizedTriple =
3180 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3181 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3182 ->getTriple()
3183 .normalize();
David L. Jonesf561aba2017-03-08 01:02:16 +00003184
3185 CmdArgs.push_back("-aux-triple");
3186 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3187 }
3188
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003189 if (IsOpenMPDevice) {
3190 // We have to pass the triple of the host if compiling for an OpenMP device.
3191 std::string NormalizedTriple =
3192 C.getSingleOffloadToolChain<Action::OFK_Host>()
3193 ->getTriple()
3194 .normalize();
3195 CmdArgs.push_back("-aux-triple");
3196 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3197 }
3198
David L. Jonesf561aba2017-03-08 01:02:16 +00003199 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3200 Triple.getArch() == llvm::Triple::thumb)) {
3201 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3202 unsigned Version;
3203 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3204 if (Version < 7)
3205 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3206 << TripleStr;
3207 }
3208
3209 // Push all default warning arguments that are specific to
3210 // the given target. These come before user provided warning options
3211 // are provided.
3212 getToolChain().addClangWarningOptions(CmdArgs);
3213
3214 // Select the appropriate action.
3215 RewriteKind rewriteKind = RK_None;
3216
3217 if (isa<AnalyzeJobAction>(JA)) {
3218 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3219 CmdArgs.push_back("-analyze");
3220 } else if (isa<MigrateJobAction>(JA)) {
3221 CmdArgs.push_back("-migrate");
3222 } else if (isa<PreprocessJobAction>(JA)) {
3223 if (Output.getType() == types::TY_Dependencies)
3224 CmdArgs.push_back("-Eonly");
3225 else {
3226 CmdArgs.push_back("-E");
3227 if (Args.hasArg(options::OPT_rewrite_objc) &&
3228 !Args.hasArg(options::OPT_g_Group))
3229 CmdArgs.push_back("-P");
3230 }
3231 } else if (isa<AssembleJobAction>(JA)) {
3232 CmdArgs.push_back("-emit-obj");
3233
3234 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3235
3236 // Also ignore explicit -force_cpusubtype_ALL option.
3237 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3238 } else if (isa<PrecompileJobAction>(JA)) {
3239 // Use PCH if the user requested it.
3240 bool UsePCH = D.CCCUsePCH;
3241
3242 if (JA.getType() == types::TY_Nothing)
3243 CmdArgs.push_back("-fsyntax-only");
3244 else if (JA.getType() == types::TY_ModuleFile)
3245 CmdArgs.push_back("-emit-module-interface");
3246 else if (UsePCH)
3247 CmdArgs.push_back("-emit-pch");
3248 else
3249 CmdArgs.push_back("-emit-pth");
3250 } else if (isa<VerifyPCHJobAction>(JA)) {
3251 CmdArgs.push_back("-verify-pch");
3252 } else {
3253 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3254 "Invalid action for clang tool.");
3255 if (JA.getType() == types::TY_Nothing) {
3256 CmdArgs.push_back("-fsyntax-only");
3257 } else if (JA.getType() == types::TY_LLVM_IR ||
3258 JA.getType() == types::TY_LTO_IR) {
3259 CmdArgs.push_back("-emit-llvm");
3260 } else if (JA.getType() == types::TY_LLVM_BC ||
3261 JA.getType() == types::TY_LTO_BC) {
3262 CmdArgs.push_back("-emit-llvm-bc");
3263 } else if (JA.getType() == types::TY_PP_Asm) {
3264 CmdArgs.push_back("-S");
3265 } else if (JA.getType() == types::TY_AST) {
3266 CmdArgs.push_back("-emit-pch");
3267 } else if (JA.getType() == types::TY_ModuleFile) {
3268 CmdArgs.push_back("-module-file-info");
3269 } else if (JA.getType() == types::TY_RewrittenObjC) {
3270 CmdArgs.push_back("-rewrite-objc");
3271 rewriteKind = RK_NonFragile;
3272 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3273 CmdArgs.push_back("-rewrite-objc");
3274 rewriteKind = RK_Fragile;
3275 } else {
3276 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3277 }
3278
3279 // Preserve use-list order by default when emitting bitcode, so that
3280 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3281 // same result as running passes here. For LTO, we don't need to preserve
3282 // the use-list order, since serialization to bitcode is part of the flow.
3283 if (JA.getType() == types::TY_LLVM_BC)
3284 CmdArgs.push_back("-emit-llvm-uselists");
3285
Artem Belevichecb178b2018-03-21 22:22:59 +00003286 // Device-side jobs do not support LTO.
3287 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3288 JA.isDeviceOffloading(Action::OFK_Host));
3289
3290 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003291 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3292
Paul Robinsond23f2a82017-07-13 21:25:47 +00003293 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3294 // does not support LTO unit features (CFI, whole program vtable opt)
3295 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003296 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003297 D.getLTOMode() == LTOK_Full)
3298 CmdArgs.push_back("-flto-unit");
3299 }
3300 }
3301
3302 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3303 if (!types::isLLVMIR(Input.getType()))
3304 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3305 << "-x ir";
3306 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3307 }
3308
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003309 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003310 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3311
David L. Jonesf561aba2017-03-08 01:02:16 +00003312 // Embed-bitcode option.
3313 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3314 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3315 // Add flags implied by -fembed-bitcode.
3316 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3317 // Disable all llvm IR level optimizations.
3318 CmdArgs.push_back("-disable-llvm-passes");
3319 }
3320 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3321 CmdArgs.push_back("-fembed-bitcode=marker");
3322
3323 // We normally speed up the clang process a bit by skipping destructors at
3324 // exit, but when we're generating diagnostics we can rely on some of the
3325 // cleanup.
3326 if (!C.isForDiagnostics())
3327 CmdArgs.push_back("-disable-free");
3328
David L. Jonesf561aba2017-03-08 01:02:16 +00003329#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003330 const bool IsAssertBuild = false;
3331#else
3332 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003333#endif
3334
Eric Fiselier123c7492018-02-07 18:36:51 +00003335 // Disable the verification pass in -asserts builds.
3336 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003337 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003338
3339 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003340 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3341 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003342 CmdArgs.push_back("-discard-value-names");
3343
David L. Jonesf561aba2017-03-08 01:02:16 +00003344 // Set the main file name, so that debug info works even with
3345 // -save-temps.
3346 CmdArgs.push_back("-main-file-name");
3347 CmdArgs.push_back(getBaseInputName(Args, Input));
3348
3349 // Some flags which affect the language (via preprocessor
3350 // defines).
3351 if (Args.hasArg(options::OPT_static))
3352 CmdArgs.push_back("-static-define");
3353
Martin Storsjo434ef832018-08-06 19:48:44 +00003354 if (Args.hasArg(options::OPT_municode))
3355 CmdArgs.push_back("-DUNICODE");
3356
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003357 if (isa<AnalyzeJobAction>(JA))
3358 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003359
3360 CheckCodeGenerationOptions(D, Args);
3361
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003362 unsigned FunctionAlignment = ParseFunctionAlignment(getToolChain(), Args);
3363 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3364 if (FunctionAlignment) {
3365 CmdArgs.push_back("-function-alignment");
3366 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3367 }
3368
David L. Jonesf561aba2017-03-08 01:02:16 +00003369 llvm::Reloc::Model RelocationModel;
3370 unsigned PICLevel;
3371 bool IsPIE;
3372 std::tie(RelocationModel, PICLevel, IsPIE) =
3373 ParsePICArgs(getToolChain(), Args);
3374
3375 const char *RMName = RelocationModelName(RelocationModel);
3376
3377 if ((RelocationModel == llvm::Reloc::ROPI ||
3378 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3379 types::isCXX(Input.getType()) &&
3380 !Args.hasArg(options::OPT_fallow_unsupported))
3381 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3382
3383 if (RMName) {
3384 CmdArgs.push_back("-mrelocation-model");
3385 CmdArgs.push_back(RMName);
3386 }
3387 if (PICLevel > 0) {
3388 CmdArgs.push_back("-pic-level");
3389 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3390 if (IsPIE)
3391 CmdArgs.push_back("-pic-is-pie");
3392 }
3393
3394 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3395 CmdArgs.push_back("-meabi");
3396 CmdArgs.push_back(A->getValue());
3397 }
3398
3399 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003400 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3401 if (!getToolChain().isThreadModelSupported(A->getValue()))
3402 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3403 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003404 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003405 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003406 else
3407 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3408
3409 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3410
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003411 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3412 options::OPT_fno_merge_all_constants, false))
3413 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003414
Manoj Guptada08f6a2018-07-19 00:44:52 +00003415 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3416 options::OPT_fdelete_null_pointer_checks, false))
3417 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3418
David L. Jonesf561aba2017-03-08 01:02:16 +00003419 // LLVM Code Generator Options.
3420
3421 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3422 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3423 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3424 options::OPT_frewrite_map_file_EQ)) {
3425 StringRef Map = A->getValue();
3426 if (!llvm::sys::fs::exists(Map)) {
3427 D.Diag(diag::err_drv_no_such_file) << Map;
3428 } else {
3429 CmdArgs.push_back("-frewrite-map-file");
3430 CmdArgs.push_back(A->getValue());
3431 A->claim();
3432 }
3433 }
3434 }
3435
3436 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3437 StringRef v = A->getValue();
3438 CmdArgs.push_back("-mllvm");
3439 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3440 A->claim();
3441 }
3442
3443 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3444 true))
3445 CmdArgs.push_back("-fno-jump-tables");
3446
Dehao Chen5e97f232017-08-24 21:37:33 +00003447 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3448 options::OPT_fno_profile_sample_accurate, false))
3449 CmdArgs.push_back("-fprofile-sample-accurate");
3450
David L. Jonesf561aba2017-03-08 01:02:16 +00003451 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3452 options::OPT_fno_preserve_as_comments, true))
3453 CmdArgs.push_back("-fno-preserve-as-comments");
3454
3455 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3456 CmdArgs.push_back("-mregparm");
3457 CmdArgs.push_back(A->getValue());
3458 }
3459
3460 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3461 options::OPT_freg_struct_return)) {
3462 if (getToolChain().getArch() != llvm::Triple::x86) {
3463 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003464 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003465 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3466 CmdArgs.push_back("-fpcc-struct-return");
3467 } else {
3468 assert(A->getOption().matches(options::OPT_freg_struct_return));
3469 CmdArgs.push_back("-freg-struct-return");
3470 }
3471 }
3472
3473 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3474 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3475
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003476 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003477 CmdArgs.push_back("-mdisable-fp-elim");
3478 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3479 options::OPT_fno_zero_initialized_in_bss))
3480 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3481
3482 bool OFastEnabled = isOptimizationLevelFast(Args);
3483 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3484 // enabled. This alias option is being used to simplify the hasFlag logic.
3485 OptSpecifier StrictAliasingAliasOption =
3486 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3487 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3488 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003489 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003490 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3491 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3492 CmdArgs.push_back("-relaxed-aliasing");
3493 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3494 options::OPT_fno_struct_path_tbaa))
3495 CmdArgs.push_back("-no-struct-path-tbaa");
3496 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3497 false))
3498 CmdArgs.push_back("-fstrict-enums");
3499 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3500 true))
3501 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003502 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3503 options::OPT_fno_allow_editor_placeholders, false))
3504 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003505 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3506 options::OPT_fno_strict_vtable_pointers,
3507 false))
3508 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003509 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3510 options::OPT_fno_force_emit_vtables,
3511 false))
3512 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00003513 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3514 options::OPT_fno_optimize_sibling_calls))
3515 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003516 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003517 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003518 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003519
Wei Mi9b3d6272017-10-16 16:50:27 +00003520 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3521 options::OPT_fno_fine_grained_bitfield_accesses);
3522
David L. Jonesf561aba2017-03-08 01:02:16 +00003523 // Handle segmented stacks.
3524 if (Args.hasArg(options::OPT_fsplit_stack))
3525 CmdArgs.push_back("-split-stacks");
3526
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00003527 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003528
3529 // Decide whether to use verbose asm. Verbose assembly is the default on
3530 // toolchains which have the integrated assembler on by default.
3531 bool IsIntegratedAssemblerDefault =
3532 getToolChain().IsIntegratedAssemblerDefault();
3533 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3534 IsIntegratedAssemblerDefault) ||
3535 Args.hasArg(options::OPT_dA))
3536 CmdArgs.push_back("-masm-verbose");
3537
Peter Collingbourned86ca942018-06-14 00:03:41 +00003538 if (!getToolChain().useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00003539 CmdArgs.push_back("-no-integrated-as");
3540
3541 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3542 CmdArgs.push_back("-mdebug-pass");
3543 CmdArgs.push_back("Structure");
3544 }
3545 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3546 CmdArgs.push_back("-mdebug-pass");
3547 CmdArgs.push_back("Arguments");
3548 }
3549
3550 // Enable -mconstructor-aliases except on darwin, where we have to work around
3551 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3552 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003553 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003554 CmdArgs.push_back("-mconstructor-aliases");
3555
3556 // Darwin's kernel doesn't support guard variables; just die if we
3557 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003558 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003559 CmdArgs.push_back("-fforbid-guard-variables");
3560
3561 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3562 false)) {
3563 CmdArgs.push_back("-mms-bitfields");
3564 }
3565
3566 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3567 options::OPT_mno_pie_copy_relocations,
3568 false)) {
3569 CmdArgs.push_back("-mpie-copy-relocations");
3570 }
3571
Sriraman Tallam5c651482017-11-07 19:37:51 +00003572 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3573 CmdArgs.push_back("-fno-plt");
3574 }
3575
Vedant Kumardf502592017-09-12 22:51:53 +00003576 // -fhosted is default.
3577 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3578 // use Freestanding.
3579 bool Freestanding =
3580 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3581 KernelOrKext;
3582 if (Freestanding)
3583 CmdArgs.push_back("-ffreestanding");
3584
David L. Jonesf561aba2017-03-08 01:02:16 +00003585 // This is a coarse approximation of what llvm-gcc actually does, both
3586 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3587 // complicated ways.
3588 bool AsynchronousUnwindTables =
3589 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3590 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00003591 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003592 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003593 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003594 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3595 AsynchronousUnwindTables))
3596 CmdArgs.push_back("-munwind-tables");
3597
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00003598 getToolChain().addClangTargetOptions(Args, CmdArgs,
3599 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003600
3601 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3602 CmdArgs.push_back("-mlimit-float-precision");
3603 CmdArgs.push_back(A->getValue());
3604 }
3605
3606 // FIXME: Handle -mtune=.
3607 (void)Args.hasArg(options::OPT_mtune_EQ);
3608
3609 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3610 CmdArgs.push_back("-mcode-model");
3611 CmdArgs.push_back(A->getValue());
3612 }
3613
3614 // Add the target cpu
3615 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3616 if (!CPU.empty()) {
3617 CmdArgs.push_back("-target-cpu");
3618 CmdArgs.push_back(Args.MakeArgString(CPU));
3619 }
3620
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003621 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003622
David L. Jonesf561aba2017-03-08 01:02:16 +00003623 // These two are potentially updated by AddClangCLArgs.
3624 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3625 bool EmitCodeView = false;
3626
3627 // Add clang-cl arguments.
3628 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003629 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003630 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
Reid Kleckner54af3e72018-02-26 22:55:33 +00003631 else
3632 EmitCodeView = Args.hasArg(options::OPT_gcodeview);
David L. Jonesf561aba2017-03-08 01:02:16 +00003633
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003634 const Arg *SplitDWARFArg = nullptr;
3635 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3636 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3637
3638 // Add the split debug info name to the command lines here so we
3639 // can propagate it to the backend.
3640 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3641 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3642 isa<BackendJobAction>(JA));
3643 const char *SplitDWARFOut;
3644 if (SplitDWARF) {
3645 CmdArgs.push_back("-split-dwarf-file");
3646 SplitDWARFOut = SplitDebugName(Args, Input);
3647 CmdArgs.push_back(SplitDWARFOut);
3648 }
3649
David L. Jonesf561aba2017-03-08 01:02:16 +00003650 // Pass the linker version in use.
3651 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3652 CmdArgs.push_back("-target-linker-version");
3653 CmdArgs.push_back(A->getValue());
3654 }
3655
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003656 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003657 CmdArgs.push_back("-momit-leaf-frame-pointer");
3658
3659 // Explicitly error on some things we know we don't support and can't just
3660 // ignore.
3661 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3662 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003663 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
David L. Jonesf561aba2017-03-08 01:02:16 +00003664 getToolChain().getArch() == llvm::Triple::x86) {
3665 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3666 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3667 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3668 << Unsupported->getOption().getName();
3669 }
Eric Christopher758aad72017-03-21 22:06:18 +00003670 // The faltivec option has been superseded by the maltivec option.
3671 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3672 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3673 << Unsupported->getOption().getName()
3674 << "please use -maltivec and include altivec.h explicitly";
3675 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3676 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3677 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00003678 }
3679
3680 Args.AddAllArgs(CmdArgs, options::OPT_v);
3681 Args.AddLastArg(CmdArgs, options::OPT_H);
3682 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3683 CmdArgs.push_back("-header-include-file");
3684 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3685 : "-");
3686 }
3687 Args.AddLastArg(CmdArgs, options::OPT_P);
3688 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3689
3690 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3691 CmdArgs.push_back("-diagnostic-log-file");
3692 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3693 : "-");
3694 }
3695
David L. Jonesf561aba2017-03-08 01:02:16 +00003696 bool UseSeparateSections = isUseSeparateSections(Triple);
3697
3698 if (Args.hasFlag(options::OPT_ffunction_sections,
3699 options::OPT_fno_function_sections, UseSeparateSections)) {
3700 CmdArgs.push_back("-ffunction-sections");
3701 }
3702
3703 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3704 UseSeparateSections)) {
3705 CmdArgs.push_back("-fdata-sections");
3706 }
3707
3708 if (!Args.hasFlag(options::OPT_funique_section_names,
3709 options::OPT_fno_unique_section_names, true))
3710 CmdArgs.push_back("-fno-unique-section-names");
3711
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00003712 if (auto *A = Args.getLastArg(
3713 options::OPT_finstrument_functions,
3714 options::OPT_finstrument_functions_after_inlining,
3715 options::OPT_finstrument_function_entry_bare))
3716 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003717
Artem Belevichc30bcad2018-01-24 17:41:02 +00003718 // NVPTX doesn't support PGO or coverage. There's no runtime support for
3719 // sampling, overhead of call arc collection is way too high and there's no
3720 // way to collect the output.
3721 if (!Triple.isNVPTX())
3722 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003723
Richard Smithf667ad52017-08-26 01:04:35 +00003724 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3725 ABICompatArg->render(Args, CmdArgs);
3726
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003727 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
3728 if (RawTriple.isPS4CPU()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003729 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003730 PS4cpu::addSanitizerArgs(getToolChain(), CmdArgs);
3731 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003732
3733 // Pass options for controlling the default header search paths.
3734 if (Args.hasArg(options::OPT_nostdinc)) {
3735 CmdArgs.push_back("-nostdsysteminc");
3736 CmdArgs.push_back("-nobuiltininc");
3737 } else {
3738 if (Args.hasArg(options::OPT_nostdlibinc))
3739 CmdArgs.push_back("-nostdsysteminc");
3740 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3741 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3742 }
3743
3744 // Pass the path to compiler resource files.
3745 CmdArgs.push_back("-resource-dir");
3746 CmdArgs.push_back(D.ResourceDir.c_str());
3747
3748 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3749
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00003750 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003751
3752 // Add preprocessing options like -I, -D, etc. if we are using the
3753 // preprocessor.
3754 //
3755 // FIXME: Support -fpreprocessed
3756 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3757 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3758
3759 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3760 // that "The compiler can only warn and ignore the option if not recognized".
3761 // When building with ccache, it will pass -D options to clang even on
3762 // preprocessed inputs and configure concludes that -fPIC is not supported.
3763 Args.ClaimAllArgs(options::OPT_D);
3764
3765 // Manually translate -O4 to -O3; let clang reject others.
3766 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3767 if (A->getOption().matches(options::OPT_O4)) {
3768 CmdArgs.push_back("-O3");
3769 D.Diag(diag::warn_O4_is_O3);
3770 } else {
3771 A->render(Args, CmdArgs);
3772 }
3773 }
3774
3775 // Warn about ignored options to clang.
3776 for (const Arg *A :
3777 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3778 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3779 A->claim();
3780 }
3781
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003782 for (const Arg *A :
3783 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3784 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3785 A->claim();
3786 }
3787
David L. Jonesf561aba2017-03-08 01:02:16 +00003788 claimNoWarnArgs(Args);
3789
3790 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3791
3792 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3793 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3794 CmdArgs.push_back("-pedantic");
3795 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3796 Args.AddLastArg(CmdArgs, options::OPT_w);
3797
Leonard Chanf921d852018-06-04 16:07:52 +00003798 // Fixed point flags
3799 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
3800 /*Default=*/false))
3801 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
3802
David L. Jonesf561aba2017-03-08 01:02:16 +00003803 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3804 // (-ansi is equivalent to -std=c89 or -std=c++98).
3805 //
3806 // If a std is supplied, only add -trigraphs if it follows the
3807 // option.
3808 bool ImplyVCPPCXXVer = false;
3809 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3810 if (Std->getOption().matches(options::OPT_ansi))
3811 if (types::isCXX(InputType))
3812 CmdArgs.push_back("-std=c++98");
3813 else
3814 CmdArgs.push_back("-std=c89");
3815 else
3816 Std->render(Args, CmdArgs);
3817
3818 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3819 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3820 options::OPT_ftrigraphs,
3821 options::OPT_fno_trigraphs))
3822 if (A != Std)
3823 A->render(Args, CmdArgs);
3824 } else {
3825 // Honor -std-default.
3826 //
3827 // FIXME: Clang doesn't correctly handle -std= when the input language
3828 // doesn't match. For the time being just ignore this for C++ inputs;
3829 // eventually we want to do all the standard defaulting here instead of
3830 // splitting it between the driver and clang -cc1.
3831 if (!types::isCXX(InputType))
3832 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3833 /*Joined=*/true);
3834 else if (IsWindowsMSVC)
3835 ImplyVCPPCXXVer = true;
3836
3837 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3838 options::OPT_fno_trigraphs);
3839 }
3840
3841 // GCC's behavior for -Wwrite-strings is a bit strange:
3842 // * In C, this "warning flag" changes the types of string literals from
3843 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3844 // for the discarded qualifier.
3845 // * In C++, this is just a normal warning flag.
3846 //
3847 // Implementing this warning correctly in C is hard, so we follow GCC's
3848 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3849 // a non-const char* in C, rather than using this crude hack.
3850 if (!types::isCXX(InputType)) {
3851 // FIXME: This should behave just like a warning flag, and thus should also
3852 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3853 Arg *WriteStrings =
3854 Args.getLastArg(options::OPT_Wwrite_strings,
3855 options::OPT_Wno_write_strings, options::OPT_w);
3856 if (WriteStrings &&
3857 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3858 CmdArgs.push_back("-fconst-strings");
3859 }
3860
3861 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3862 // during C++ compilation, which it is by default. GCC keeps this define even
3863 // in the presence of '-w', match this behavior bug-for-bug.
3864 if (types::isCXX(InputType) &&
3865 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3866 true)) {
3867 CmdArgs.push_back("-fdeprecated-macro");
3868 }
3869
3870 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3871 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3872 if (Asm->getOption().matches(options::OPT_fasm))
3873 CmdArgs.push_back("-fgnu-keywords");
3874 else
3875 CmdArgs.push_back("-fno-gnu-keywords");
3876 }
3877
3878 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3879 CmdArgs.push_back("-fno-dwarf-directory-asm");
3880
3881 if (ShouldDisableAutolink(Args, getToolChain()))
3882 CmdArgs.push_back("-fno-autolink");
3883
3884 // Add in -fdebug-compilation-dir if necessary.
3885 addDebugCompDirArg(Args, CmdArgs);
3886
Paul Robinson9b292b42018-07-10 15:15:24 +00003887 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003888
3889 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3890 options::OPT_ftemplate_depth_EQ)) {
3891 CmdArgs.push_back("-ftemplate-depth");
3892 CmdArgs.push_back(A->getValue());
3893 }
3894
3895 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3896 CmdArgs.push_back("-foperator-arrow-depth");
3897 CmdArgs.push_back(A->getValue());
3898 }
3899
3900 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3901 CmdArgs.push_back("-fconstexpr-depth");
3902 CmdArgs.push_back(A->getValue());
3903 }
3904
3905 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3906 CmdArgs.push_back("-fconstexpr-steps");
3907 CmdArgs.push_back(A->getValue());
3908 }
3909
3910 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3911 CmdArgs.push_back("-fbracket-depth");
3912 CmdArgs.push_back(A->getValue());
3913 }
3914
3915 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3916 options::OPT_Wlarge_by_value_copy_def)) {
3917 if (A->getNumValues()) {
3918 StringRef bytes = A->getValue();
3919 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3920 } else
3921 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3922 }
3923
3924 if (Args.hasArg(options::OPT_relocatable_pch))
3925 CmdArgs.push_back("-relocatable-pch");
3926
3927 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3928 CmdArgs.push_back("-fconstant-string-class");
3929 CmdArgs.push_back(A->getValue());
3930 }
3931
3932 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3933 CmdArgs.push_back("-ftabstop");
3934 CmdArgs.push_back(A->getValue());
3935 }
3936
Sean Eveson5110d4f2018-01-08 13:42:26 +00003937 if (Args.hasFlag(options::OPT_fstack_size_section,
3938 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3939 CmdArgs.push_back("-fstack-size-section");
3940
David L. Jonesf561aba2017-03-08 01:02:16 +00003941 CmdArgs.push_back("-ferror-limit");
3942 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3943 CmdArgs.push_back(A->getValue());
3944 else
3945 CmdArgs.push_back("19");
3946
3947 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3948 CmdArgs.push_back("-fmacro-backtrace-limit");
3949 CmdArgs.push_back(A->getValue());
3950 }
3951
3952 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3953 CmdArgs.push_back("-ftemplate-backtrace-limit");
3954 CmdArgs.push_back(A->getValue());
3955 }
3956
3957 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3958 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3959 CmdArgs.push_back(A->getValue());
3960 }
3961
3962 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3963 CmdArgs.push_back("-fspell-checking-limit");
3964 CmdArgs.push_back(A->getValue());
3965 }
3966
3967 // Pass -fmessage-length=.
3968 CmdArgs.push_back("-fmessage-length");
3969 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3970 CmdArgs.push_back(A->getValue());
3971 } else {
3972 // If -fmessage-length=N was not specified, determine whether this is a
3973 // terminal and, if so, implicitly define -fmessage-length appropriately.
3974 unsigned N = llvm::sys::Process::StandardErrColumns();
3975 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3976 }
3977
3978 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3979 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3980 options::OPT_fvisibility_ms_compat)) {
3981 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3982 CmdArgs.push_back("-fvisibility");
3983 CmdArgs.push_back(A->getValue());
3984 } else {
3985 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3986 CmdArgs.push_back("-fvisibility");
3987 CmdArgs.push_back("hidden");
3988 CmdArgs.push_back("-ftype-visibility");
3989 CmdArgs.push_back("default");
3990 }
3991 }
3992
3993 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3994
3995 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3996
David L. Jonesf561aba2017-03-08 01:02:16 +00003997 // Forward -f (flag) options which we can pass directly.
3998 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3999 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004000 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004001 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004002 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4003 options::OPT_fno_emulated_tls);
4004
David L. Jonesf561aba2017-03-08 01:02:16 +00004005 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004006 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004007 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004008
David L. Jonesf561aba2017-03-08 01:02:16 +00004009 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4010 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4011
4012 // Forward flags for OpenMP. We don't do this if the current action is an
4013 // device offloading action other than OpenMP.
4014 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4015 options::OPT_fno_openmp, false) &&
4016 (JA.isDeviceOffloading(Action::OFK_None) ||
4017 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004018 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004019 case Driver::OMPRT_OMP:
4020 case Driver::OMPRT_IOMP5:
4021 // Clang can generate useful OpenMP code for these two runtime libraries.
4022 CmdArgs.push_back("-fopenmp");
4023
4024 // If no option regarding the use of TLS in OpenMP codegeneration is
4025 // given, decide a default based on the target. Otherwise rely on the
4026 // options and pass the right information to the frontend.
4027 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4028 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4029 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004030 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4031 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004032 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Carlo Bertolli79712092018-02-28 20:48:35 +00004033
4034 // When in OpenMP offloading mode with NVPTX target, forward
4035 // cuda-mode flag
4036 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_cuda_mode,
4037 options::OPT_fno_openmp_cuda_mode);
David L. Jonesf561aba2017-03-08 01:02:16 +00004038 break;
4039 default:
4040 // By default, if Clang doesn't know how to generate useful OpenMP code
4041 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4042 // down to the actual compilation.
4043 // FIXME: It would be better to have a mode which *only* omits IR
4044 // generation based on the OpenMP support so that we get consistent
4045 // semantic analysis, etc.
4046 break;
4047 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004048 } else {
4049 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4050 options::OPT_fno_openmp_simd);
4051 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004052 }
4053
4054 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4055 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4056
Dean Michael Berris835832d2017-03-30 00:29:36 +00004057 const XRayArgs &XRay = getToolChain().getXRayArgs();
4058 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
4059
David L. Jonesf561aba2017-03-08 01:02:16 +00004060 if (getToolChain().SupportsProfiling())
4061 Args.AddLastArg(CmdArgs, options::OPT_pg);
4062
4063 if (getToolChain().SupportsProfiling())
4064 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4065
4066 // -flax-vector-conversions is default.
4067 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4068 options::OPT_fno_lax_vector_conversions))
4069 CmdArgs.push_back("-fno-lax-vector-conversions");
4070
4071 if (Args.getLastArg(options::OPT_fapple_kext) ||
4072 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4073 CmdArgs.push_back("-fapple-kext");
4074
4075 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4076 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4077 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4078 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4079 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4080
4081 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4082 CmdArgs.push_back("-ftrapv-handler");
4083 CmdArgs.push_back(A->getValue());
4084 }
4085
4086 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4087
4088 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4089 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4090 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4091 if (A->getOption().matches(options::OPT_fwrapv))
4092 CmdArgs.push_back("-fwrapv");
4093 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4094 options::OPT_fno_strict_overflow)) {
4095 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4096 CmdArgs.push_back("-fwrapv");
4097 }
4098
4099 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4100 options::OPT_fno_reroll_loops))
4101 if (A->getOption().matches(options::OPT_freroll_loops))
4102 CmdArgs.push_back("-freroll-loops");
4103
4104 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4105 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4106 options::OPT_fno_unroll_loops);
4107
4108 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4109
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00004110 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004111
4112 // Translate -mstackrealign
4113 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4114 false))
4115 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4116
4117 if (Args.hasArg(options::OPT_mstack_alignment)) {
4118 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4119 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4120 }
4121
4122 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4123 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4124
4125 if (!Size.empty())
4126 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4127 else
4128 CmdArgs.push_back("-mstack-probe-size=0");
4129 }
4130
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004131 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4132 options::OPT_mno_stack_arg_probe, true))
4133 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4134
David L. Jonesf561aba2017-03-08 01:02:16 +00004135 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4136 options::OPT_mno_restrict_it)) {
4137 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004138 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004139 CmdArgs.push_back("-arm-restrict-it");
4140 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004141 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004142 CmdArgs.push_back("-arm-no-restrict-it");
4143 }
4144 } else if (Triple.isOSWindows() &&
4145 (Triple.getArch() == llvm::Triple::arm ||
4146 Triple.getArch() == llvm::Triple::thumb)) {
4147 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004148 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004149 CmdArgs.push_back("-arm-restrict-it");
4150 }
4151
4152 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004153 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004154
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004155 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4156 CmdArgs.push_back(
4157 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4158 }
4159
David L. Jonesf561aba2017-03-08 01:02:16 +00004160 // Forward -f options with positive and negative forms; we translate
4161 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004162 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004163 StringRef fname = A->getValue();
4164 if (!llvm::sys::fs::exists(fname))
4165 D.Diag(diag::err_drv_no_such_file) << fname;
4166 else
4167 A->render(Args, CmdArgs);
4168 }
4169
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00004170 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004171
4172 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4173 options::OPT_fno_assume_sane_operator_new))
4174 CmdArgs.push_back("-fno-assume-sane-operator-new");
4175
4176 // -fblocks=0 is default.
4177 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4178 getToolChain().IsBlocksDefault()) ||
4179 (Args.hasArg(options::OPT_fgnu_runtime) &&
4180 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4181 !Args.hasArg(options::OPT_fno_blocks))) {
4182 CmdArgs.push_back("-fblocks");
4183
4184 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4185 !getToolChain().hasBlocksRuntime())
4186 CmdArgs.push_back("-fblocks-runtime-optional");
4187 }
4188
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004189 // -fencode-extended-block-signature=1 is default.
4190 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4191 CmdArgs.push_back("-fencode-extended-block-signature");
4192
David L. Jonesf561aba2017-03-08 01:02:16 +00004193 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4194 false) &&
4195 types::isCXX(InputType)) {
4196 CmdArgs.push_back("-fcoroutines-ts");
4197 }
4198
Aaron Ballman61736552017-10-21 20:28:58 +00004199 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4200 options::OPT_fno_double_square_bracket_attributes);
4201
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004202 bool HaveModules = false;
4203 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004204
4205 // -faccess-control is default.
4206 if (Args.hasFlag(options::OPT_fno_access_control,
4207 options::OPT_faccess_control, false))
4208 CmdArgs.push_back("-fno-access-control");
4209
4210 // -felide-constructors is the default.
4211 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4212 options::OPT_felide_constructors, false))
4213 CmdArgs.push_back("-fno-elide-constructors");
4214
4215 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4216
4217 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004218 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004219 CmdArgs.push_back("-fno-rtti");
4220
4221 // -fshort-enums=0 is default for all architectures except Hexagon.
4222 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4223 getToolChain().getArch() == llvm::Triple::hexagon))
4224 CmdArgs.push_back("-fshort-enums");
4225
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004226 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004227
4228 // -fuse-cxa-atexit is default.
4229 if (!Args.hasFlag(
4230 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004231 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004232 RawTriple.getOS() != llvm::Triple::Solaris &&
David L. Jonesf561aba2017-03-08 01:02:16 +00004233 getToolChain().getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004234 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4235 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004236 KernelOrKext)
4237 CmdArgs.push_back("-fno-use-cxa-atexit");
4238
Akira Hatanaka617e2612018-04-17 18:41:52 +00004239 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4240 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004241 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004242 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4243
David L. Jonesf561aba2017-03-08 01:02:16 +00004244 // -fms-extensions=0 is default.
4245 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4246 IsWindowsMSVC))
4247 CmdArgs.push_back("-fms-extensions");
4248
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004249 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004250 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004251 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004252 CmdArgs.push_back("-fuse-line-directives");
4253
4254 // -fms-compatibility=0 is default.
4255 if (Args.hasFlag(options::OPT_fms_compatibility,
4256 options::OPT_fno_ms_compatibility,
4257 (IsWindowsMSVC &&
4258 Args.hasFlag(options::OPT_fms_extensions,
4259 options::OPT_fno_ms_extensions, true))))
4260 CmdArgs.push_back("-fms-compatibility");
4261
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004262 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004263 if (!MSVT.empty())
4264 CmdArgs.push_back(
4265 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4266
4267 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4268 if (ImplyVCPPCXXVer) {
4269 StringRef LanguageStandard;
4270 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4271 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4272 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004273 .Case("c++17", "-std=c++17")
4274 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004275 .Default("");
4276 if (LanguageStandard.empty())
4277 D.Diag(clang::diag::warn_drv_unused_argument)
4278 << StdArg->getAsString(Args);
4279 }
4280
4281 if (LanguageStandard.empty()) {
4282 if (IsMSVC2015Compatible)
4283 LanguageStandard = "-std=c++14";
4284 else
4285 LanguageStandard = "-std=c++11";
4286 }
4287
4288 CmdArgs.push_back(LanguageStandard.data());
4289 }
4290
4291 // -fno-borland-extensions is default.
4292 if (Args.hasFlag(options::OPT_fborland_extensions,
4293 options::OPT_fno_borland_extensions, false))
4294 CmdArgs.push_back("-fborland-extensions");
4295
4296 // -fno-declspec is default, except for PS4.
4297 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004298 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004299 CmdArgs.push_back("-fdeclspec");
4300 else if (Args.hasArg(options::OPT_fno_declspec))
4301 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4302
4303 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4304 // than 19.
4305 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4306 options::OPT_fno_threadsafe_statics,
4307 !IsWindowsMSVC || IsMSVC2015Compatible))
4308 CmdArgs.push_back("-fno-threadsafe-statics");
4309
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004310 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004311 // Many old Windows SDK versions require this to parse.
4312 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4313 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004314 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4315 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4316 CmdArgs.push_back("-fdelayed-template-parsing");
4317
4318 // -fgnu-keywords default varies depending on language; only pass if
4319 // specified.
4320 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4321 options::OPT_fno_gnu_keywords))
4322 A->render(Args, CmdArgs);
4323
4324 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4325 false))
4326 CmdArgs.push_back("-fgnu89-inline");
4327
4328 if (Args.hasArg(options::OPT_fno_inline))
4329 CmdArgs.push_back("-fno-inline");
4330
4331 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4332 options::OPT_finline_hint_functions,
4333 options::OPT_fno_inline_functions))
4334 InlineArg->render(Args, CmdArgs);
4335
4336 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4337 options::OPT_fno_experimental_new_pass_manager);
4338
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004339 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4340 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4341 rewriteKind != RK_None, Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004342
4343 if (Args.hasFlag(options::OPT_fapplication_extension,
4344 options::OPT_fno_application_extension, false))
4345 CmdArgs.push_back("-fapplication-extension");
4346
4347 // Handle GCC-style exception args.
4348 if (!C.getDriver().IsCLMode())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004349 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
David L. Jonesf561aba2017-03-08 01:02:16 +00004350 CmdArgs);
4351
Martell Malonec950c652017-11-29 07:25:12 +00004352 // Handle exception personalities
4353 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4354 options::OPT_fseh_exceptions,
4355 options::OPT_fdwarf_exceptions);
4356 if (A) {
4357 const Option &Opt = A->getOption();
4358 if (Opt.matches(options::OPT_fsjlj_exceptions))
4359 CmdArgs.push_back("-fsjlj-exceptions");
4360 if (Opt.matches(options::OPT_fseh_exceptions))
4361 CmdArgs.push_back("-fseh-exceptions");
4362 if (Opt.matches(options::OPT_fdwarf_exceptions))
4363 CmdArgs.push_back("-fdwarf-exceptions");
4364 } else {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004365 switch (getToolChain().GetExceptionModel(Args)) {
4366 default:
4367 break;
4368 case llvm::ExceptionHandling::DwarfCFI:
4369 CmdArgs.push_back("-fdwarf-exceptions");
4370 break;
4371 case llvm::ExceptionHandling::SjLj:
4372 CmdArgs.push_back("-fsjlj-exceptions");
4373 break;
4374 case llvm::ExceptionHandling::WinEH:
4375 CmdArgs.push_back("-fseh-exceptions");
4376 break;
Martell Malonec950c652017-11-29 07:25:12 +00004377 }
4378 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004379
4380 // C++ "sane" operator new.
4381 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4382 options::OPT_fno_assume_sane_operator_new))
4383 CmdArgs.push_back("-fno-assume-sane-operator-new");
4384
4385 // -frelaxed-template-template-args is off by default, as it is a severe
4386 // breaking change until a corresponding change to template partial ordering
4387 // is provided.
4388 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4389 options::OPT_fno_relaxed_template_template_args, false))
4390 CmdArgs.push_back("-frelaxed-template-template-args");
4391
4392 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4393 // most platforms.
4394 if (Args.hasFlag(options::OPT_fsized_deallocation,
4395 options::OPT_fno_sized_deallocation, false))
4396 CmdArgs.push_back("-fsized-deallocation");
4397
4398 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4399 // by default.
4400 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4401 options::OPT_fno_aligned_allocation,
4402 options::OPT_faligned_new_EQ)) {
4403 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4404 CmdArgs.push_back("-fno-aligned-allocation");
4405 else
4406 CmdArgs.push_back("-faligned-allocation");
4407 }
4408
4409 // The default new alignment can be specified using a dedicated option or via
4410 // a GCC-compatible option that also turns on aligned allocation.
4411 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4412 options::OPT_faligned_new_EQ))
4413 CmdArgs.push_back(
4414 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4415
4416 // -fconstant-cfstrings is default, and may be subject to argument translation
4417 // on Darwin.
4418 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4419 options::OPT_fno_constant_cfstrings) ||
4420 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4421 options::OPT_mno_constant_cfstrings))
4422 CmdArgs.push_back("-fno-constant-cfstrings");
4423
David L. Jonesf561aba2017-03-08 01:02:16 +00004424 // -fno-pascal-strings is default, only pass non-default.
4425 if (Args.hasFlag(options::OPT_fpascal_strings,
4426 options::OPT_fno_pascal_strings, false))
4427 CmdArgs.push_back("-fpascal-strings");
4428
4429 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4430 // -fno-pack-struct doesn't apply to -fpack-struct=.
4431 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4432 std::string PackStructStr = "-fpack-struct=";
4433 PackStructStr += A->getValue();
4434 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4435 } else if (Args.hasFlag(options::OPT_fpack_struct,
4436 options::OPT_fno_pack_struct, false)) {
4437 CmdArgs.push_back("-fpack-struct=1");
4438 }
4439
4440 // Handle -fmax-type-align=N and -fno-type-align
4441 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4442 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4443 if (!SkipMaxTypeAlign) {
4444 std::string MaxTypeAlignStr = "-fmax-type-align=";
4445 MaxTypeAlignStr += A->getValue();
4446 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4447 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004448 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004449 if (!SkipMaxTypeAlign) {
4450 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4451 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4452 }
4453 }
4454
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004455 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4456 CmdArgs.push_back("-Qn");
4457
David L. Jonesf561aba2017-03-08 01:02:16 +00004458 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004459 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004460 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4461 !NoCommonDefault))
4462 CmdArgs.push_back("-fno-common");
4463
4464 // -fsigned-bitfields is default, and clang doesn't yet support
4465 // -funsigned-bitfields.
4466 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4467 options::OPT_funsigned_bitfields))
4468 D.Diag(diag::warn_drv_clang_unsupported)
4469 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4470
4471 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4472 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4473 D.Diag(diag::err_drv_clang_unsupported)
4474 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4475
4476 // -finput_charset=UTF-8 is default. Reject others
4477 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4478 StringRef value = inputCharset->getValue();
4479 if (!value.equals_lower("utf-8"))
4480 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4481 << value;
4482 }
4483
4484 // -fexec_charset=UTF-8 is default. Reject others
4485 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4486 StringRef value = execCharset->getValue();
4487 if (!value.equals_lower("utf-8"))
4488 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4489 << value;
4490 }
4491
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004492 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004493
4494 // -fno-asm-blocks is default.
4495 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4496 false))
4497 CmdArgs.push_back("-fasm-blocks");
4498
4499 // -fgnu-inline-asm is default.
4500 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4501 options::OPT_fno_gnu_inline_asm, true))
4502 CmdArgs.push_back("-fno-gnu-inline-asm");
4503
4504 // Enable vectorization per default according to the optimization level
4505 // selected. For optimization levels that want vectorization we use the alias
4506 // option to simplify the hasFlag logic.
4507 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4508 OptSpecifier VectorizeAliasOption =
4509 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4510 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4511 options::OPT_fno_vectorize, EnableVec))
4512 CmdArgs.push_back("-vectorize-loops");
4513
4514 // -fslp-vectorize is enabled based on the optimization level selected.
4515 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4516 OptSpecifier SLPVectAliasOption =
4517 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4518 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4519 options::OPT_fno_slp_vectorize, EnableSLPVec))
4520 CmdArgs.push_back("-vectorize-slp");
4521
Craig Topper9a724aa2017-12-11 21:09:19 +00004522 ParseMPreferVectorWidth(D, Args, CmdArgs);
4523
David L. Jonesf561aba2017-03-08 01:02:16 +00004524 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4525 A->render(Args, CmdArgs);
4526
4527 if (Arg *A = Args.getLastArg(
4528 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4529 A->render(Args, CmdArgs);
4530
4531 // -fdollars-in-identifiers default varies depending on platform and
4532 // language; only pass if specified.
4533 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4534 options::OPT_fno_dollars_in_identifiers)) {
4535 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4536 CmdArgs.push_back("-fdollars-in-identifiers");
4537 else
4538 CmdArgs.push_back("-fno-dollars-in-identifiers");
4539 }
4540
4541 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4542 // practical purposes.
4543 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4544 options::OPT_fno_unit_at_a_time)) {
4545 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4546 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4547 }
4548
4549 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4550 options::OPT_fno_apple_pragma_pack, false))
4551 CmdArgs.push_back("-fapple-pragma-pack");
4552
David L. Jonesf561aba2017-03-08 01:02:16 +00004553 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004554 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004555 options::OPT_fno_save_optimization_record, false)) {
4556 CmdArgs.push_back("-opt-record-file");
4557
4558 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4559 if (A) {
4560 CmdArgs.push_back(A->getValue());
4561 } else {
4562 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004563
4564 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4565 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4566 F = FinalOutput->getValue();
4567 }
4568
4569 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004570 // Use the input filename.
4571 F = llvm::sys::path::stem(Input.getBaseInput());
4572
4573 // If we're compiling for an offload architecture (i.e. a CUDA device),
4574 // we need to make the file name for the device compilation different
4575 // from the host compilation.
4576 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4577 !JA.isDeviceOffloading(Action::OFK_Host)) {
4578 llvm::sys::path::replace_extension(F, "");
4579 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4580 Triple.normalize());
4581 F += "-";
4582 F += JA.getOffloadingArch();
4583 }
4584 }
4585
4586 llvm::sys::path::replace_extension(F, "opt.yaml");
4587 CmdArgs.push_back(Args.MakeArgString(F));
4588 }
4589 }
4590
Richard Smith86a3ef52017-06-09 21:24:02 +00004591 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4592 options::OPT_fno_rewrite_imports, false);
4593 if (RewriteImports)
4594 CmdArgs.push_back("-frewrite-imports");
4595
David L. Jonesf561aba2017-03-08 01:02:16 +00004596 // Enable rewrite includes if the user's asked for it or if we're generating
4597 // diagnostics.
4598 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4599 // nice to enable this when doing a crashdump for modules as well.
4600 if (Args.hasFlag(options::OPT_frewrite_includes,
4601 options::OPT_fno_rewrite_includes, false) ||
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004602 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004603 CmdArgs.push_back("-frewrite-includes");
4604
4605 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4606 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4607 options::OPT_traditional_cpp)) {
4608 if (isa<PreprocessJobAction>(JA))
4609 CmdArgs.push_back("-traditional-cpp");
4610 else
4611 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4612 }
4613
4614 Args.AddLastArg(CmdArgs, options::OPT_dM);
4615 Args.AddLastArg(CmdArgs, options::OPT_dD);
4616
4617 // Handle serialized diagnostics.
4618 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4619 CmdArgs.push_back("-serialize-diagnostic-file");
4620 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4621 }
4622
4623 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4624 CmdArgs.push_back("-fretain-comments-from-system-headers");
4625
4626 // Forward -fcomment-block-commands to -cc1.
4627 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4628 // Forward -fparse-all-comments to -cc1.
4629 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4630
4631 // Turn -fplugin=name.so into -load name.so
4632 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4633 CmdArgs.push_back("-load");
4634 CmdArgs.push_back(A->getValue());
4635 A->claim();
4636 }
4637
4638 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00004639 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4640 if (!StatsFile.empty())
4641 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00004642
4643 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4644 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004645 // -finclude-default-header flag is for preprocessor,
4646 // do not pass it to other cc1 commands when save-temps is enabled
4647 if (C.getDriver().isSaveTempsEnabled() &&
4648 !isa<PreprocessJobAction>(JA)) {
4649 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4650 Arg->claim();
4651 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4652 CmdArgs.push_back(Arg->getValue());
4653 }
4654 }
4655 else {
4656 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4657 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004658 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4659 A->claim();
4660
4661 // We translate this by hand to the -cc1 argument, since nightly test uses
4662 // it and developers have been trained to spell it with -mllvm. Both
4663 // spellings are now deprecated and should be removed.
4664 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4665 CmdArgs.push_back("-disable-llvm-optzns");
4666 } else {
4667 A->render(Args, CmdArgs);
4668 }
4669 }
4670
4671 // With -save-temps, we want to save the unoptimized bitcode output from the
4672 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4673 // by the frontend.
4674 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4675 // has slightly different breakdown between stages.
4676 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4677 // pristine IR generated by the frontend. Ideally, a new compile action should
4678 // be added so both IR can be captured.
4679 if (C.getDriver().isSaveTempsEnabled() &&
4680 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4681 isa<CompileJobAction>(JA))
4682 CmdArgs.push_back("-disable-llvm-passes");
4683
4684 if (Output.getType() == types::TY_Dependencies) {
4685 // Handled with other dependency code.
4686 } else if (Output.isFilename()) {
4687 CmdArgs.push_back("-o");
4688 CmdArgs.push_back(Output.getFilename());
4689 } else {
4690 assert(Output.isNothing() && "Invalid output.");
4691 }
4692
4693 addDashXForInput(Args, Input, CmdArgs);
4694
4695 if (Input.isFilename())
4696 CmdArgs.push_back(Input.getFilename());
4697 else
4698 Input.getInputArg().renderAsInput(Args, CmdArgs);
4699
4700 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4701
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004702 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00004703
4704 // Optionally embed the -cc1 level arguments into the debug info, for build
4705 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004706 // Also record command line arguments into the debug info if
4707 // -grecord-gcc-switches options is set on.
4708 // By default, -gno-record-gcc-switches is set on and no recording.
4709 if (getToolChain().UseDwarfDebugFlags() ||
4710 Args.hasFlag(options::OPT_grecord_gcc_switches,
4711 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004712 ArgStringList OriginalArgs;
4713 for (const auto &Arg : Args)
4714 Arg->render(Args, OriginalArgs);
4715
4716 SmallString<256> Flags;
4717 Flags += Exec;
4718 for (const char *OriginalArg : OriginalArgs) {
4719 SmallString<128> EscapedArg;
4720 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4721 Flags += " ";
4722 Flags += EscapedArg;
4723 }
4724 CmdArgs.push_back("-dwarf-debug-flags");
4725 CmdArgs.push_back(Args.MakeArgString(Flags));
4726 }
4727
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004728 if (IsCuda) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004729 // Host-side cuda compilation receives all device-side outputs in a single
4730 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004731 if (Inputs.size() > 1) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004732 assert(Inputs.size() == 2 && "More than one GPU binary!");
4733 CmdArgs.push_back("-fcuda-include-gpubinary");
4734 CmdArgs.push_back(Inputs[1].getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00004735 }
4736
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004737 if (Args.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc, false))
4738 CmdArgs.push_back("-fcuda-rdc");
Artem Belevich679dafe2018-05-09 23:10:09 +00004739 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
4740 options::OPT_fno_cuda_short_ptr, false))
4741 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004742 }
4743
David L. Jonesf561aba2017-03-08 01:02:16 +00004744 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4745 // to specify the result of the compile phase on the host, so the meaningful
4746 // device declarations can be identified. Also, -fopenmp-is-device is passed
4747 // along to tell the frontend that it is generating code for a device, so that
4748 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004749 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004750 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004751 if (Inputs.size() == 2) {
4752 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4753 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4754 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004755 }
4756
4757 // For all the host OpenMP offloading compile jobs we need to pass the targets
4758 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00004759 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004760 SmallString<128> TargetInfo("-fopenmp-targets=");
4761
4762 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4763 assert(Tgts && Tgts->getNumValues() &&
4764 "OpenMP offloading has to have targets specified.");
4765 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4766 if (i)
4767 TargetInfo += ',';
4768 // We need to get the string from the triple because it may be not exactly
4769 // the same as the one we get directly from the arguments.
4770 llvm::Triple T(Tgts->getValue(i));
4771 TargetInfo += T.getTriple();
4772 }
4773 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4774 }
4775
4776 bool WholeProgramVTables =
4777 Args.hasFlag(options::OPT_fwhole_program_vtables,
4778 options::OPT_fno_whole_program_vtables, false);
4779 if (WholeProgramVTables) {
4780 if (!D.isUsingLTO())
4781 D.Diag(diag::err_drv_argument_only_allowed_with)
4782 << "-fwhole-program-vtables"
4783 << "-flto";
4784 CmdArgs.push_back("-fwhole-program-vtables");
4785 }
4786
Amara Emerson4ee9f822018-01-26 00:27:22 +00004787 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4788 options::OPT_fno_experimental_isel)) {
4789 CmdArgs.push_back("-mllvm");
4790 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4791 CmdArgs.push_back("-global-isel=1");
4792
4793 // GISel is on by default on AArch64 -O0, so don't bother adding
4794 // the fallback remarks for it. Other combinations will add a warning of
4795 // some kind.
4796 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4797 bool IsOptLevelSupported = false;
4798
4799 Arg *A = Args.getLastArg(options::OPT_O_Group);
4800 if (Triple.getArch() == llvm::Triple::aarch64) {
4801 if (!A || A->getOption().matches(options::OPT_O0))
4802 IsOptLevelSupported = true;
4803 }
4804 if (!IsArchSupported || !IsOptLevelSupported) {
4805 CmdArgs.push_back("-mllvm");
4806 CmdArgs.push_back("-global-isel-abort=2");
4807
4808 if (!IsArchSupported)
4809 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4810 else
4811 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4812 }
4813 } else {
4814 CmdArgs.push_back("-global-isel=0");
4815 }
4816 }
4817
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00004818 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
4819 options::OPT_fno_force_enable_int128)) {
4820 if (A->getOption().matches(options::OPT_fforce_enable_int128))
4821 CmdArgs.push_back("-fforce-enable-int128");
4822 }
4823
Peter Collingbourne54d13b42018-05-30 03:40:04 +00004824 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
4825 options::OPT_fno_complete_member_pointers, false))
4826 CmdArgs.push_back("-fcomplete-member-pointers");
4827
Jessica Paquette36a25672018-06-29 18:06:10 +00004828 if (Arg *A = Args.getLastArg(options::OPT_moutline,
4829 options::OPT_mno_outline)) {
4830 if (A->getOption().matches(options::OPT_moutline)) {
4831 // We only support -moutline in AArch64 right now. If we're not compiling
4832 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
4833 // proper mllvm flags.
4834 if (Triple.getArch() != llvm::Triple::aarch64) {
4835 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
4836 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00004837 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00004838 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00004839 }
Jessica Paquette36a25672018-06-29 18:06:10 +00004840 } else {
4841 // Disable all outlining behaviour.
4842 CmdArgs.push_back("-mllvm");
4843 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00004844 }
4845 }
4846
Peter Collingbourne14b468b2018-07-18 00:27:07 +00004847 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
4848 getToolChain().getTriple().isOSBinFormatELF() &&
4849 getToolChain().useIntegratedAs()))
4850 CmdArgs.push_back("-faddrsig");
4851
David L. Jonesf561aba2017-03-08 01:02:16 +00004852 // Finally add the compile command to the compilation.
4853 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4854 Output.getType() == types::TY_Object &&
4855 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4856 auto CLCommand =
4857 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4858 C.addCommand(llvm::make_unique<FallbackCommand>(
4859 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4860 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4861 isa<PrecompileJobAction>(JA)) {
4862 // In /fallback builds, run the main compilation even if the pch generation
4863 // fails, so that the main compilation's fallback to cl.exe runs.
4864 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4865 CmdArgs, Inputs));
4866 } else {
4867 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4868 }
4869
David L. Jonesf561aba2017-03-08 01:02:16 +00004870 if (Arg *A = Args.getLastArg(options::OPT_pg))
4871 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4872 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4873 << A->getAsString(Args);
4874
4875 // Claim some arguments which clang supports automatically.
4876
4877 // -fpch-preprocess is used with gcc to add a special marker in the output to
4878 // include the PCH file. Clang's PTH solution is completely transparent, so we
4879 // do not need to deal with it at all.
4880 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4881
4882 // Claim some arguments which clang doesn't support, but we don't
4883 // care to warn the user about.
4884 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4885 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4886
4887 // Disable warnings for clang -E -emit-llvm foo.c
4888 Args.ClaimAllArgs(options::OPT_emit_llvm);
4889}
4890
4891Clang::Clang(const ToolChain &TC)
4892 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4893 // as it is for other tools. Some operations on a Tool actually test
4894 // whether that tool is Clang based on the Tool's Name as a string.
4895 : Tool("clang", "clang frontend", TC, RF_Full) {}
4896
4897Clang::~Clang() {}
4898
4899/// Add options related to the Objective-C runtime/ABI.
4900///
4901/// Returns true if the runtime is non-fragile.
4902ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4903 ArgStringList &cmdArgs,
4904 RewriteKind rewriteKind) const {
4905 // Look for the controlling runtime option.
4906 Arg *runtimeArg =
4907 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4908 options::OPT_fobjc_runtime_EQ);
4909
4910 // Just forward -fobjc-runtime= to the frontend. This supercedes
4911 // options about fragility.
4912 if (runtimeArg &&
4913 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4914 ObjCRuntime runtime;
4915 StringRef value = runtimeArg->getValue();
4916 if (runtime.tryParse(value)) {
4917 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4918 << value;
4919 }
David Chisnall404bbcb2018-05-22 10:13:06 +00004920 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
4921 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnall93ce0182018-08-10 12:53:13 +00004922 if (!getToolChain().getTriple().isOSBinFormatELF() &&
4923 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004924 getToolChain().getDriver().Diag(
4925 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
4926 << runtime.getVersion().getMajor();
4927 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004928
4929 runtimeArg->render(args, cmdArgs);
4930 return runtime;
4931 }
4932
4933 // Otherwise, we'll need the ABI "version". Version numbers are
4934 // slightly confusing for historical reasons:
4935 // 1 - Traditional "fragile" ABI
4936 // 2 - Non-fragile ABI, version 1
4937 // 3 - Non-fragile ABI, version 2
4938 unsigned objcABIVersion = 1;
4939 // If -fobjc-abi-version= is present, use that to set the version.
4940 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4941 StringRef value = abiArg->getValue();
4942 if (value == "1")
4943 objcABIVersion = 1;
4944 else if (value == "2")
4945 objcABIVersion = 2;
4946 else if (value == "3")
4947 objcABIVersion = 3;
4948 else
4949 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4950 } else {
4951 // Otherwise, determine if we are using the non-fragile ABI.
4952 bool nonFragileABIIsDefault =
4953 (rewriteKind == RK_NonFragile ||
4954 (rewriteKind == RK_None &&
4955 getToolChain().IsObjCNonFragileABIDefault()));
4956 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4957 options::OPT_fno_objc_nonfragile_abi,
4958 nonFragileABIIsDefault)) {
4959// Determine the non-fragile ABI version to use.
4960#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4961 unsigned nonFragileABIVersion = 1;
4962#else
4963 unsigned nonFragileABIVersion = 2;
4964#endif
4965
4966 if (Arg *abiArg =
4967 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4968 StringRef value = abiArg->getValue();
4969 if (value == "1")
4970 nonFragileABIVersion = 1;
4971 else if (value == "2")
4972 nonFragileABIVersion = 2;
4973 else
4974 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4975 << value;
4976 }
4977
4978 objcABIVersion = 1 + nonFragileABIVersion;
4979 } else {
4980 objcABIVersion = 1;
4981 }
4982 }
4983
4984 // We don't actually care about the ABI version other than whether
4985 // it's non-fragile.
4986 bool isNonFragile = objcABIVersion != 1;
4987
4988 // If we have no runtime argument, ask the toolchain for its default runtime.
4989 // However, the rewriter only really supports the Mac runtime, so assume that.
4990 ObjCRuntime runtime;
4991 if (!runtimeArg) {
4992 switch (rewriteKind) {
4993 case RK_None:
4994 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4995 break;
4996 case RK_Fragile:
4997 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4998 break;
4999 case RK_NonFragile:
5000 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5001 break;
5002 }
5003
5004 // -fnext-runtime
5005 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5006 // On Darwin, make this use the default behavior for the toolchain.
5007 if (getToolChain().getTriple().isOSDarwin()) {
5008 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5009
5010 // Otherwise, build for a generic macosx port.
5011 } else {
5012 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5013 }
5014
5015 // -fgnu-runtime
5016 } else {
5017 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5018 // Legacy behaviour is to target the gnustep runtime if we are in
5019 // non-fragile mode or the GCC runtime in fragile mode.
5020 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005021 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005022 else
5023 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5024 }
5025
5026 cmdArgs.push_back(
5027 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5028 return runtime;
5029}
5030
5031static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5032 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5033 I += HaveDash;
5034 return !HaveDash;
5035}
5036
5037namespace {
5038struct EHFlags {
5039 bool Synch = false;
5040 bool Asynch = false;
5041 bool NoUnwindC = false;
5042};
5043} // end anonymous namespace
5044
5045/// /EH controls whether to run destructor cleanups when exceptions are
5046/// thrown. There are three modifiers:
5047/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5048/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5049/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5050/// - c: Assume that extern "C" functions are implicitly nounwind.
5051/// The default is /EHs-c-, meaning cleanups are disabled.
5052static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5053 EHFlags EH;
5054
5055 std::vector<std::string> EHArgs =
5056 Args.getAllArgValues(options::OPT__SLASH_EH);
5057 for (auto EHVal : EHArgs) {
5058 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5059 switch (EHVal[I]) {
5060 case 'a':
5061 EH.Asynch = maybeConsumeDash(EHVal, I);
5062 if (EH.Asynch)
5063 EH.Synch = false;
5064 continue;
5065 case 'c':
5066 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5067 continue;
5068 case 's':
5069 EH.Synch = maybeConsumeDash(EHVal, I);
5070 if (EH.Synch)
5071 EH.Asynch = false;
5072 continue;
5073 default:
5074 break;
5075 }
5076 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5077 break;
5078 }
5079 }
5080 // The /GX, /GX- flags are only processed if there are not /EH flags.
5081 // The default is that /GX is not specified.
5082 if (EHArgs.empty() &&
5083 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5084 /*default=*/false)) {
5085 EH.Synch = true;
5086 EH.NoUnwindC = true;
5087 }
5088
5089 return EH;
5090}
5091
5092void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5093 ArgStringList &CmdArgs,
5094 codegenoptions::DebugInfoKind *DebugInfoKind,
5095 bool *EmitCodeView) const {
5096 unsigned RTOptionID = options::OPT__SLASH_MT;
5097
5098 if (Args.hasArg(options::OPT__SLASH_LDd))
5099 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5100 // but defining _DEBUG is sticky.
5101 RTOptionID = options::OPT__SLASH_MTd;
5102
5103 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5104 RTOptionID = A->getOption().getID();
5105
5106 StringRef FlagForCRT;
5107 switch (RTOptionID) {
5108 case options::OPT__SLASH_MD:
5109 if (Args.hasArg(options::OPT__SLASH_LDd))
5110 CmdArgs.push_back("-D_DEBUG");
5111 CmdArgs.push_back("-D_MT");
5112 CmdArgs.push_back("-D_DLL");
5113 FlagForCRT = "--dependent-lib=msvcrt";
5114 break;
5115 case options::OPT__SLASH_MDd:
5116 CmdArgs.push_back("-D_DEBUG");
5117 CmdArgs.push_back("-D_MT");
5118 CmdArgs.push_back("-D_DLL");
5119 FlagForCRT = "--dependent-lib=msvcrtd";
5120 break;
5121 case options::OPT__SLASH_MT:
5122 if (Args.hasArg(options::OPT__SLASH_LDd))
5123 CmdArgs.push_back("-D_DEBUG");
5124 CmdArgs.push_back("-D_MT");
5125 CmdArgs.push_back("-flto-visibility-public-std");
5126 FlagForCRT = "--dependent-lib=libcmt";
5127 break;
5128 case options::OPT__SLASH_MTd:
5129 CmdArgs.push_back("-D_DEBUG");
5130 CmdArgs.push_back("-D_MT");
5131 CmdArgs.push_back("-flto-visibility-public-std");
5132 FlagForCRT = "--dependent-lib=libcmtd";
5133 break;
5134 default:
5135 llvm_unreachable("Unexpected option ID.");
5136 }
5137
5138 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5139 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5140 } else {
5141 CmdArgs.push_back(FlagForCRT.data());
5142
5143 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5144 // users want. The /Za flag to cl.exe turns this off, but it's not
5145 // implemented in clang.
5146 CmdArgs.push_back("--dependent-lib=oldnames");
5147 }
5148
Erich Keane425f48d2018-05-04 15:58:31 +00005149 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5150 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005151
5152 // This controls whether or not we emit RTTI data for polymorphic types.
5153 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5154 /*default=*/false))
5155 CmdArgs.push_back("-fno-rtti-data");
5156
5157 // This controls whether or not we emit stack-protector instrumentation.
5158 // In MSVC, Buffer Security Check (/GS) is on by default.
5159 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5160 /*default=*/true)) {
5161 CmdArgs.push_back("-stack-protector");
5162 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5163 }
5164
5165 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5166 if (Arg *DebugInfoArg =
5167 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5168 options::OPT_gline_tables_only)) {
5169 *EmitCodeView = true;
5170 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5171 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5172 else
5173 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5174 CmdArgs.push_back("-gcodeview");
5175 } else {
5176 *EmitCodeView = false;
5177 }
5178
5179 const Driver &D = getToolChain().getDriver();
5180 EHFlags EH = parseClangCLEHFlags(D, Args);
5181 if (EH.Synch || EH.Asynch) {
5182 if (types::isCXX(InputType))
5183 CmdArgs.push_back("-fcxx-exceptions");
5184 CmdArgs.push_back("-fexceptions");
5185 }
5186 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5187 CmdArgs.push_back("-fexternc-nounwind");
5188
5189 // /EP should expand to -E -P.
5190 if (Args.hasArg(options::OPT__SLASH_EP)) {
5191 CmdArgs.push_back("-E");
5192 CmdArgs.push_back("-P");
5193 }
5194
5195 unsigned VolatileOptionID;
5196 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5197 getToolChain().getArch() == llvm::Triple::x86)
5198 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5199 else
5200 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5201
5202 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5203 VolatileOptionID = A->getOption().getID();
5204
5205 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5206 CmdArgs.push_back("-fms-volatile");
5207
5208 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5209 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5210 if (MostGeneralArg && BestCaseArg)
5211 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5212 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5213
5214 if (MostGeneralArg) {
5215 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5216 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5217 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5218
5219 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5220 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5221 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5222 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5223 << FirstConflict->getAsString(Args)
5224 << SecondConflict->getAsString(Args);
5225
5226 if (SingleArg)
5227 CmdArgs.push_back("-fms-memptr-rep=single");
5228 else if (MultipleArg)
5229 CmdArgs.push_back("-fms-memptr-rep=multiple");
5230 else
5231 CmdArgs.push_back("-fms-memptr-rep=virtual");
5232 }
5233
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005234 // Parse the default calling convention options.
5235 if (Arg *CCArg =
5236 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005237 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5238 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005239 unsigned DCCOptId = CCArg->getOption().getID();
5240 const char *DCCFlag = nullptr;
5241 bool ArchSupported = true;
5242 llvm::Triple::ArchType Arch = getToolChain().getArch();
5243 switch (DCCOptId) {
5244 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005245 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005246 break;
5247 case options::OPT__SLASH_Gr:
5248 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005249 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005250 break;
5251 case options::OPT__SLASH_Gz:
5252 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005253 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005254 break;
5255 case options::OPT__SLASH_Gv:
5256 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005257 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005258 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005259 case options::OPT__SLASH_Gregcall:
5260 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5261 DCCFlag = "-fdefault-calling-conv=regcall";
5262 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005263 }
5264
5265 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5266 if (ArchSupported && DCCFlag)
5267 CmdArgs.push_back(DCCFlag);
5268 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005269
5270 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5271 A->render(Args, CmdArgs);
5272
5273 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5274 CmdArgs.push_back("-fdiagnostics-format");
5275 if (Args.hasArg(options::OPT__SLASH_fallback))
5276 CmdArgs.push_back("msvc-fallback");
5277 else
5278 CmdArgs.push_back("msvc");
5279 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005280
Hans Wennborga912e3e2018-08-10 09:49:21 +00005281 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5282 SmallVector<StringRef, 1> SplitArgs;
5283 StringRef(A->getValue()).split(SplitArgs, ",");
5284 bool Instrument = false;
5285 bool NoChecks = false;
5286 for (StringRef Arg : SplitArgs) {
5287 if (Arg.equals_lower("cf"))
5288 Instrument = true;
5289 else if (Arg.equals_lower("cf-"))
5290 Instrument = false;
5291 else if (Arg.equals_lower("nochecks"))
5292 NoChecks = true;
5293 else if (Arg.equals_lower("nochecks-"))
5294 NoChecks = false;
5295 else
5296 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5297 }
5298 // Currently there's no support emitting CFG instrumentation; the flag only
5299 // emits the table of address-taken functions.
5300 if (Instrument || NoChecks)
5301 CmdArgs.push_back("-cfguard");
5302 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005303}
5304
5305visualstudio::Compiler *Clang::getCLFallback() const {
5306 if (!CLFallback)
5307 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5308 return CLFallback.get();
5309}
5310
5311
5312const char *Clang::getBaseInputName(const ArgList &Args,
5313 const InputInfo &Input) {
5314 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5315}
5316
5317const char *Clang::getBaseInputStem(const ArgList &Args,
5318 const InputInfoList &Inputs) {
5319 const char *Str = getBaseInputName(Args, Inputs[0]);
5320
5321 if (const char *End = strrchr(Str, '.'))
5322 return Args.MakeArgString(std::string(Str, End));
5323
5324 return Str;
5325}
5326
5327const char *Clang::getDependencyFileName(const ArgList &Args,
5328 const InputInfoList &Inputs) {
5329 // FIXME: Think about this more.
5330 std::string Res;
5331
5332 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5333 std::string Str(OutputOpt->getValue());
5334 Res = Str.substr(0, Str.rfind('.'));
5335 } else {
5336 Res = getBaseInputStem(Args, Inputs);
5337 }
5338 return Args.MakeArgString(Res + ".d");
5339}
5340
5341// Begin ClangAs
5342
5343void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5344 ArgStringList &CmdArgs) const {
5345 StringRef CPUName;
5346 StringRef ABIName;
5347 const llvm::Triple &Triple = getToolChain().getTriple();
5348 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5349
5350 CmdArgs.push_back("-target-abi");
5351 CmdArgs.push_back(ABIName.data());
5352}
5353
5354void ClangAs::AddX86TargetArgs(const ArgList &Args,
5355 ArgStringList &CmdArgs) const {
5356 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5357 StringRef Value = A->getValue();
5358 if (Value == "intel" || Value == "att") {
5359 CmdArgs.push_back("-mllvm");
5360 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5361 } else {
5362 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5363 << A->getOption().getName() << Value;
5364 }
5365 }
5366}
5367
5368void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5369 const InputInfo &Output, const InputInfoList &Inputs,
5370 const ArgList &Args,
5371 const char *LinkingOutput) const {
5372 ArgStringList CmdArgs;
5373
5374 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5375 const InputInfo &Input = Inputs[0];
5376
5377 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5378 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005379 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005380
5381 // Don't warn about "clang -w -c foo.s"
5382 Args.ClaimAllArgs(options::OPT_w);
5383 // and "clang -emit-llvm -c foo.s"
5384 Args.ClaimAllArgs(options::OPT_emit_llvm);
5385
5386 claimNoWarnArgs(Args);
5387
5388 // Invoke ourselves in -cc1as mode.
5389 //
5390 // FIXME: Implement custom jobs for internal actions.
5391 CmdArgs.push_back("-cc1as");
5392
5393 // Add the "effective" target triple.
5394 CmdArgs.push_back("-triple");
5395 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5396
5397 // Set the output mode, we currently only expect to be used as a real
5398 // assembler.
5399 CmdArgs.push_back("-filetype");
5400 CmdArgs.push_back("obj");
5401
5402 // Set the main file name, so that debug info works even with
5403 // -save-temps or preprocessed assembly.
5404 CmdArgs.push_back("-main-file-name");
5405 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5406
5407 // Add the target cpu
5408 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5409 if (!CPU.empty()) {
5410 CmdArgs.push_back("-target-cpu");
5411 CmdArgs.push_back(Args.MakeArgString(CPU));
5412 }
5413
5414 // Add the target features
5415 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5416
5417 // Ignore explicit -force_cpusubtype_ALL option.
5418 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5419
5420 // Pass along any -I options so we get proper .include search paths.
5421 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5422
5423 // Determine the original source input.
5424 const Action *SourceAction = &JA;
5425 while (SourceAction->getKind() != Action::InputClass) {
5426 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5427 SourceAction = SourceAction->getInputs()[0];
5428 }
5429
5430 // Forward -g and handle debug info related flags, assuming we are dealing
5431 // with an actual assembly file.
5432 bool WantDebug = false;
5433 unsigned DwarfVersion = 0;
5434 Args.ClaimAllArgs(options::OPT_g_Group);
5435 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5436 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5437 !A->getOption().matches(options::OPT_ggdb0);
5438 if (WantDebug)
5439 DwarfVersion = DwarfVersionNum(A->getSpelling());
5440 }
5441 if (DwarfVersion == 0)
5442 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5443
5444 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5445
5446 if (SourceAction->getType() == types::TY_Asm ||
5447 SourceAction->getType() == types::TY_PP_Asm) {
5448 // You might think that it would be ok to set DebugInfoKind outside of
5449 // the guard for source type, however there is a test which asserts
5450 // that some assembler invocation receives no -debug-info-kind,
5451 // and it's not clear whether that test is just overly restrictive.
5452 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5453 : codegenoptions::NoDebugInfo);
5454 // Add the -fdebug-compilation-dir flag if needed.
5455 addDebugCompDirArg(Args, CmdArgs);
5456
Paul Robinson9b292b42018-07-10 15:15:24 +00005457 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5458
David L. Jonesf561aba2017-03-08 01:02:16 +00005459 // Set the AT_producer to the clang version when using the integrated
5460 // assembler on assembly source files.
5461 CmdArgs.push_back("-dwarf-debug-producer");
5462 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5463
5464 // And pass along -I options
5465 Args.AddAllArgs(CmdArgs, options::OPT_I);
5466 }
5467 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5468 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00005469 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005470
David L. Jonesf561aba2017-03-08 01:02:16 +00005471
5472 // Handle -fPIC et al -- the relocation-model affects the assembler
5473 // for some targets.
5474 llvm::Reloc::Model RelocationModel;
5475 unsigned PICLevel;
5476 bool IsPIE;
5477 std::tie(RelocationModel, PICLevel, IsPIE) =
5478 ParsePICArgs(getToolChain(), Args);
5479
5480 const char *RMName = RelocationModelName(RelocationModel);
5481 if (RMName) {
5482 CmdArgs.push_back("-mrelocation-model");
5483 CmdArgs.push_back(RMName);
5484 }
5485
5486 // Optionally embed the -cc1as level arguments into the debug info, for build
5487 // analysis.
5488 if (getToolChain().UseDwarfDebugFlags()) {
5489 ArgStringList OriginalArgs;
5490 for (const auto &Arg : Args)
5491 Arg->render(Args, OriginalArgs);
5492
5493 SmallString<256> Flags;
5494 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5495 Flags += Exec;
5496 for (const char *OriginalArg : OriginalArgs) {
5497 SmallString<128> EscapedArg;
5498 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5499 Flags += " ";
5500 Flags += EscapedArg;
5501 }
5502 CmdArgs.push_back("-dwarf-debug-flags");
5503 CmdArgs.push_back(Args.MakeArgString(Flags));
5504 }
5505
5506 // FIXME: Add -static support, once we have it.
5507
5508 // Add target specific flags.
5509 switch (getToolChain().getArch()) {
5510 default:
5511 break;
5512
5513 case llvm::Triple::mips:
5514 case llvm::Triple::mipsel:
5515 case llvm::Triple::mips64:
5516 case llvm::Triple::mips64el:
5517 AddMIPSTargetArgs(Args, CmdArgs);
5518 break;
5519
5520 case llvm::Triple::x86:
5521 case llvm::Triple::x86_64:
5522 AddX86TargetArgs(Args, CmdArgs);
5523 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005524
5525 case llvm::Triple::arm:
5526 case llvm::Triple::armeb:
5527 case llvm::Triple::thumb:
5528 case llvm::Triple::thumbeb:
5529 // This isn't in AddARMTargetArgs because we want to do this for assembly
5530 // only, not C/C++.
5531 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5532 options::OPT_mno_default_build_attributes, true)) {
5533 CmdArgs.push_back("-mllvm");
5534 CmdArgs.push_back("-arm-add-build-attributes");
5535 }
5536 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005537 }
5538
5539 // Consume all the warning flags. Usually this would be handled more
5540 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5541 // doesn't handle that so rather than warning about unused flags that are
5542 // actually used, we'll lie by omission instead.
5543 // FIXME: Stop lying and consume only the appropriate driver flags
5544 Args.ClaimAllArgs(options::OPT_W_Group);
5545
5546 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5547 getToolChain().getDriver());
5548
5549 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5550
5551 assert(Output.isFilename() && "Unexpected lipo output.");
5552 CmdArgs.push_back("-o");
5553 CmdArgs.push_back(Output.getFilename());
5554
Peter Collingbourne91d02842018-05-22 18:52:37 +00005555 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5556 getToolChain().getTriple().isOSLinux()) {
5557 CmdArgs.push_back("-split-dwarf-file");
5558 CmdArgs.push_back(SplitDebugName(Args, Input));
5559 }
5560
David L. Jonesf561aba2017-03-08 01:02:16 +00005561 assert(Input.isFilename() && "Invalid input.");
5562 CmdArgs.push_back(Input.getFilename());
5563
5564 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5565 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005566}
5567
5568// Begin OffloadBundler
5569
5570void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5571 const InputInfo &Output,
5572 const InputInfoList &Inputs,
5573 const llvm::opt::ArgList &TCArgs,
5574 const char *LinkingOutput) const {
5575 // The version with only one output is expected to refer to a bundling job.
5576 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5577
5578 // The bundling command looks like this:
5579 // clang-offload-bundler -type=bc
5580 // -targets=host-triple,openmp-triple1,openmp-triple2
5581 // -outputs=input_file
5582 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5583
5584 ArgStringList CmdArgs;
5585
5586 // Get the type.
5587 CmdArgs.push_back(TCArgs.MakeArgString(
5588 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5589
5590 assert(JA.getInputs().size() == Inputs.size() &&
5591 "Not have inputs for all dependence actions??");
5592
5593 // Get the targets.
5594 SmallString<128> Triples;
5595 Triples += "-targets=";
5596 for (unsigned I = 0; I < Inputs.size(); ++I) {
5597 if (I)
5598 Triples += ',';
5599
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005600 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005601 Action::OffloadKind CurKind = Action::OFK_Host;
5602 const ToolChain *CurTC = &getToolChain();
5603 const Action *CurDep = JA.getInputs()[I];
5604
5605 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005606 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00005607 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005608 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00005609 CurKind = A->getOffloadingDeviceKind();
5610 CurTC = TC;
5611 });
5612 }
5613 Triples += Action::GetOffloadKindName(CurKind);
5614 Triples += '-';
5615 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005616 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
5617 Triples += '-';
5618 Triples += CurDep->getOffloadingArch();
5619 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005620 }
5621 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5622
5623 // Get bundled file command.
5624 CmdArgs.push_back(
5625 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5626
5627 // Get unbundled files command.
5628 SmallString<128> UB;
5629 UB += "-inputs=";
5630 for (unsigned I = 0; I < Inputs.size(); ++I) {
5631 if (I)
5632 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005633
5634 // Find ToolChain for this input.
5635 const ToolChain *CurTC = &getToolChain();
5636 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5637 CurTC = nullptr;
5638 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5639 assert(CurTC == nullptr && "Expected one dependence!");
5640 CurTC = TC;
5641 });
5642 }
5643 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005644 }
5645 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5646
5647 // All the inputs are encoded as commands.
5648 C.addCommand(llvm::make_unique<Command>(
5649 JA, *this,
5650 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5651 CmdArgs, None));
5652}
5653
5654void OffloadBundler::ConstructJobMultipleOutputs(
5655 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5656 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5657 const char *LinkingOutput) const {
5658 // The version with multiple outputs is expected to refer to a unbundling job.
5659 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5660
5661 // The unbundling command looks like this:
5662 // clang-offload-bundler -type=bc
5663 // -targets=host-triple,openmp-triple1,openmp-triple2
5664 // -inputs=input_file
5665 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5666 // -unbundle
5667
5668 ArgStringList CmdArgs;
5669
5670 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5671 InputInfo Input = Inputs.front();
5672
5673 // Get the type.
5674 CmdArgs.push_back(TCArgs.MakeArgString(
5675 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5676
5677 // Get the targets.
5678 SmallString<128> Triples;
5679 Triples += "-targets=";
5680 auto DepInfo = UA.getDependentActionsInfo();
5681 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5682 if (I)
5683 Triples += ',';
5684
5685 auto &Dep = DepInfo[I];
5686 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5687 Triples += '-';
5688 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005689 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
5690 !Dep.DependentBoundArch.empty()) {
5691 Triples += '-';
5692 Triples += Dep.DependentBoundArch;
5693 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005694 }
5695
5696 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5697
5698 // Get bundled file command.
5699 CmdArgs.push_back(
5700 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5701
5702 // Get unbundled files command.
5703 SmallString<128> UB;
5704 UB += "-outputs=";
5705 for (unsigned I = 0; I < Outputs.size(); ++I) {
5706 if (I)
5707 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005708 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005709 }
5710 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5711 CmdArgs.push_back("-unbundle");
5712
5713 // All the inputs are encoded as commands.
5714 C.addCommand(llvm::make_unique<Command>(
5715 JA, *this,
5716 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5717 CmdArgs, None));
5718}