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