blob: 9d222a21357a2c16879b893b6f7445095e9a5a06 [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"
15#include "Arch/Sparc.h"
16#include "Arch/SystemZ.h"
17#include "Arch/X86.h"
18#include "CommonArgs.h"
19#include "Hexagon.h"
20#include "InputInfo.h"
21#include "PS4CPU.h"
22#include "clang/Basic/CharInfo.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/ObjCRuntime.h"
25#include "clang/Basic/Version.h"
26#include "clang/Config/config.h"
27#include "clang/Driver/DriverDiagnostic.h"
28#include "clang/Driver/Options.h"
29#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000030#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000031#include "llvm/ADT/StringExtras.h"
32#include "llvm/Option/ArgList.h"
33#include "llvm/Support/CodeGen.h"
34#include "llvm/Support/Compression.h"
35#include "llvm/Support/FileSystem.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Process.h"
38#include "llvm/Support/YAMLParser.h"
39
40#ifdef LLVM_ON_UNIX
41#include <unistd.h> // For getuid().
42#endif
43
44using namespace clang::driver;
45using namespace clang::driver::tools;
46using namespace clang;
47using namespace llvm::opt;
48
49static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
50 if (Arg *A =
51 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
52 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
53 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
54 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
55 << A->getBaseArg().getAsString(Args)
56 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
57 }
58 }
59}
60
61static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
62 // In gcc, only ARM checks this, but it seems reasonable to check universally.
63 if (Args.hasArg(options::OPT_static))
64 if (const Arg *A =
65 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
66 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
67 << "-static";
68}
69
70// Add backslashes to escape spaces and other backslashes.
71// This is used for the space-separated argument list specified with
72// the -dwarf-debug-flags option.
73static void EscapeSpacesAndBackslashes(const char *Arg,
74 SmallVectorImpl<char> &Res) {
75 for (; *Arg; ++Arg) {
76 switch (*Arg) {
77 default:
78 break;
79 case ' ':
80 case '\\':
81 Res.push_back('\\');
82 break;
83 }
84 Res.push_back(*Arg);
85 }
86}
87
88// Quote target names for inclusion in GNU Make dependency files.
89// Only the characters '$', '#', ' ', '\t' are quoted.
90static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
91 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
92 switch (Target[i]) {
93 case ' ':
94 case '\t':
95 // Escape the preceding backslashes
96 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
97 Res.push_back('\\');
98
99 // Escape the space/tab
100 Res.push_back('\\');
101 break;
102 case '$':
103 Res.push_back('$');
104 break;
105 case '#':
106 Res.push_back('\\');
107 break;
108 default:
109 break;
110 }
111
112 Res.push_back(Target[i]);
113 }
114}
115
116/// Apply \a Work on the current tool chain \a RegularToolChain and any other
117/// offloading tool chain that is associated with the current action \a JA.
118static void
119forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
120 const ToolChain &RegularToolChain,
121 llvm::function_ref<void(const ToolChain &)> Work) {
122 // Apply Work on the current/regular tool chain.
123 Work(RegularToolChain);
124
125 // Apply Work on all the offloading tool chains associated with the current
126 // action.
127 if (JA.isHostOffloading(Action::OFK_Cuda))
128 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
129 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
130 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
131
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000132 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
133 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
134 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
135 Work(*II->second);
136 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
138
David L. Jonesf561aba2017-03-08 01:02:16 +0000139 //
140 // TODO: Add support for other offloading programming models here.
141 //
142}
143
144/// This is a helper function for validating the optional refinement step
145/// parameter in reciprocal argument strings. Return false if there is an error
146/// parsing the refinement step. Otherwise, return true and set the Position
147/// of the refinement step in the input string.
148static bool getRefinementStep(StringRef In, const Driver &D,
149 const Arg &A, size_t &Position) {
150 const char RefinementStepToken = ':';
151 Position = In.find(RefinementStepToken);
152 if (Position != StringRef::npos) {
153 StringRef Option = A.getOption().getName();
154 StringRef RefStep = In.substr(Position + 1);
155 // Allow exactly one numeric character for the additional refinement
156 // step parameter. This is reasonable for all currently-supported
157 // operations and architectures because we would expect that a larger value
158 // of refinement steps would cause the estimate "optimization" to
159 // under-perform the native operation. Also, if the estimate does not
160 // converge quickly, it probably will not ever converge, so further
161 // refinement steps will not produce a better answer.
162 if (RefStep.size() != 1) {
163 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
164 return false;
165 }
166 char RefStepChar = RefStep[0];
167 if (RefStepChar < '0' || RefStepChar > '9') {
168 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
169 return false;
170 }
171 }
172 return true;
173}
174
175/// The -mrecip flag requires processing of many optional parameters.
176static void ParseMRecip(const Driver &D, const ArgList &Args,
177 ArgStringList &OutStrings) {
178 StringRef DisabledPrefixIn = "!";
179 StringRef DisabledPrefixOut = "!";
180 StringRef EnabledPrefixOut = "";
181 StringRef Out = "-mrecip=";
182
183 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
184 if (!A)
185 return;
186
187 unsigned NumOptions = A->getNumValues();
188 if (NumOptions == 0) {
189 // No option is the same as "all".
190 OutStrings.push_back(Args.MakeArgString(Out + "all"));
191 return;
192 }
193
194 // Pass through "all", "none", or "default" with an optional refinement step.
195 if (NumOptions == 1) {
196 StringRef Val = A->getValue(0);
197 size_t RefStepLoc;
198 if (!getRefinementStep(Val, D, *A, RefStepLoc))
199 return;
200 StringRef ValBase = Val.slice(0, RefStepLoc);
201 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
202 OutStrings.push_back(Args.MakeArgString(Out + Val));
203 return;
204 }
205 }
206
207 // Each reciprocal type may be enabled or disabled individually.
208 // Check each input value for validity, concatenate them all back together,
209 // and pass through.
210
211 llvm::StringMap<bool> OptionStrings;
212 OptionStrings.insert(std::make_pair("divd", false));
213 OptionStrings.insert(std::make_pair("divf", false));
214 OptionStrings.insert(std::make_pair("vec-divd", false));
215 OptionStrings.insert(std::make_pair("vec-divf", false));
216 OptionStrings.insert(std::make_pair("sqrtd", false));
217 OptionStrings.insert(std::make_pair("sqrtf", false));
218 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
219 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
220
221 for (unsigned i = 0; i != NumOptions; ++i) {
222 StringRef Val = A->getValue(i);
223
224 bool IsDisabled = Val.startswith(DisabledPrefixIn);
225 // Ignore the disablement token for string matching.
226 if (IsDisabled)
227 Val = Val.substr(1);
228
229 size_t RefStep;
230 if (!getRefinementStep(Val, D, *A, RefStep))
231 return;
232
233 StringRef ValBase = Val.slice(0, RefStep);
234 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
235 if (OptionIter == OptionStrings.end()) {
236 // Try again specifying float suffix.
237 OptionIter = OptionStrings.find(ValBase.str() + 'f');
238 if (OptionIter == OptionStrings.end()) {
239 // The input name did not match any known option string.
240 D.Diag(diag::err_drv_unknown_argument) << Val;
241 return;
242 }
243 // The option was specified without a float or double suffix.
244 // Make sure that the double entry was not already specified.
245 // The float entry will be checked below.
246 if (OptionStrings[ValBase.str() + 'd']) {
247 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
248 return;
249 }
250 }
251
252 if (OptionIter->second == true) {
253 // Duplicate option specified.
254 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
255 return;
256 }
257
258 // Mark the matched option as found. Do not allow duplicate specifiers.
259 OptionIter->second = true;
260
261 // If the precision was not specified, also mark the double entry as found.
262 if (ValBase.back() != 'f' && ValBase.back() != 'd')
263 OptionStrings[ValBase.str() + 'd'] = true;
264
265 // Build the output string.
266 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
267 Out = Args.MakeArgString(Out + Prefix + Val);
268 if (i != NumOptions - 1)
269 Out = Args.MakeArgString(Out + ",");
270 }
271
272 OutStrings.push_back(Args.MakeArgString(Out));
273}
274
275static void getHexagonTargetFeatures(const ArgList &Args,
276 std::vector<StringRef> &Features) {
277 handleTargetFeaturesGroup(Args, Features,
278 options::OPT_m_hexagon_Features_Group);
279
280 bool UseLongCalls = false;
281 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
282 options::OPT_mno_long_calls)) {
283 if (A->getOption().matches(options::OPT_mlong_calls))
284 UseLongCalls = true;
285 }
286
287 Features.push_back(UseLongCalls ? "+long-calls" : "-long-calls");
288}
289
290static void getWebAssemblyTargetFeatures(const ArgList &Args,
291 std::vector<StringRef> &Features) {
292 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
293}
294
295static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
296 std::vector<StringRef> &Features) {
297 if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
298 StringRef value = dAbi->getValue();
299 if (value == "1.0") {
300 Features.push_back("+amdgpu-debugger-insert-nops");
301 Features.push_back("+amdgpu-debugger-reserve-regs");
302 Features.push_back("+amdgpu-debugger-emit-prologue");
303 } else {
304 D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
305 }
306 }
307
308 handleTargetFeaturesGroup(
309 Args, Features, options::OPT_m_amdgpu_Features_Group);
310}
311
312static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
313 const ArgList &Args, ArgStringList &CmdArgs,
314 bool ForAS) {
315 const Driver &D = TC.getDriver();
316 std::vector<StringRef> Features;
317 switch (Triple.getArch()) {
318 default:
319 break;
320 case llvm::Triple::mips:
321 case llvm::Triple::mipsel:
322 case llvm::Triple::mips64:
323 case llvm::Triple::mips64el:
324 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
325 break;
326
327 case llvm::Triple::arm:
328 case llvm::Triple::armeb:
329 case llvm::Triple::thumb:
330 case llvm::Triple::thumbeb:
331 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
332 break;
333
334 case llvm::Triple::ppc:
335 case llvm::Triple::ppc64:
336 case llvm::Triple::ppc64le:
337 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
338 break;
339 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:
351 getHexagonTargetFeatures(Args, Features);
352 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:
364 getAMDGPUTargetFeatures(D, Args, Features);
365 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) {
415 const Driver &D = TC.getDriver();
416 const llvm::Triple &Triple = TC.getTriple();
417
418 if (KernelOrKext) {
419 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
420 // arguments now to avoid warnings about unused arguments.
421 Args.ClaimAllArgs(options::OPT_fexceptions);
422 Args.ClaimAllArgs(options::OPT_fno_exceptions);
423 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
424 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
425 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
426 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
427 return;
428 }
429
430 // See if the user explicitly enabled exceptions.
431 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
432 false);
433
434 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
435 // is not necessarily sensible, but follows GCC.
436 if (types::isObjC(InputType) &&
437 Args.hasFlag(options::OPT_fobjc_exceptions,
438 options::OPT_fno_objc_exceptions, true)) {
439 CmdArgs.push_back("-fobjc-exceptions");
440
441 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
442 }
443
444 if (types::isCXX(InputType)) {
445 // Disable C++ EH by default on XCore and PS4.
446 bool CXXExceptionsEnabled =
447 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
448 Arg *ExceptionArg = Args.getLastArg(
449 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
450 options::OPT_fexceptions, options::OPT_fno_exceptions);
451 if (ExceptionArg)
452 CXXExceptionsEnabled =
453 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
454 ExceptionArg->getOption().matches(options::OPT_fexceptions);
455
456 if (CXXExceptionsEnabled) {
457 if (Triple.isPS4CPU()) {
458 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
459 assert(ExceptionArg &&
460 "On the PS4 exceptions should only be enabled if passing "
461 "an argument");
462 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
463 const Arg *RTTIArg = TC.getRTTIArg();
464 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
465 D.Diag(diag::err_drv_argument_not_allowed_with)
466 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
467 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
468 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
469 } else
470 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
471
472 CmdArgs.push_back("-fcxx-exceptions");
473
474 EH = true;
475 }
476 }
477
478 if (EH)
479 CmdArgs.push_back("-fexceptions");
480}
481
482static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
483 bool Default = true;
484 if (TC.getTriple().isOSDarwin()) {
485 // The native darwin assembler doesn't support the linker_option directives,
486 // so we disable them if we think the .s file will be passed to it.
487 Default = TC.useIntegratedAs();
488 }
489 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
490 Default);
491}
492
493static bool ShouldDisableDwarfDirectory(const ArgList &Args,
494 const ToolChain &TC) {
495 bool UseDwarfDirectory =
496 Args.hasFlag(options::OPT_fdwarf_directory_asm,
497 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
498 return !UseDwarfDirectory;
499}
500
501// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
502// to the corresponding DebugInfoKind.
503static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
504 assert(A.getOption().matches(options::OPT_gN_Group) &&
505 "Not a -g option that specifies a debug-info level");
506 if (A.getOption().matches(options::OPT_g0) ||
507 A.getOption().matches(options::OPT_ggdb0))
508 return codegenoptions::NoDebugInfo;
509 if (A.getOption().matches(options::OPT_gline_tables_only) ||
510 A.getOption().matches(options::OPT_ggdb1))
511 return codegenoptions::DebugLineTablesOnly;
512 return codegenoptions::LimitedDebugInfo;
513}
514
515static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
516 switch (Triple.getArch()){
517 default:
518 return false;
519 case llvm::Triple::arm:
520 case llvm::Triple::thumb:
521 // ARM Darwin targets require a frame pointer to be always present to aid
522 // offline debugging via backtraces.
523 return Triple.isOSDarwin();
524 }
525}
526
527static bool useFramePointerForTargetByDefault(const ArgList &Args,
528 const llvm::Triple &Triple) {
529 switch (Triple.getArch()) {
530 case llvm::Triple::xcore:
531 case llvm::Triple::wasm32:
532 case llvm::Triple::wasm64:
533 // XCore never wants frame pointers, regardless of OS.
534 // WebAssembly never wants frame pointers.
535 return false;
536 default:
537 break;
538 }
539
540 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
541 switch (Triple.getArch()) {
542 // Don't use a frame pointer on linux if optimizing for certain targets.
543 case llvm::Triple::mips64:
544 case llvm::Triple::mips64el:
545 case llvm::Triple::mips:
546 case llvm::Triple::mipsel:
547 case llvm::Triple::ppc:
548 case llvm::Triple::ppc64:
549 case llvm::Triple::ppc64le:
550 case llvm::Triple::systemz:
551 case llvm::Triple::x86:
552 case llvm::Triple::x86_64:
553 return !areOptimizationsEnabled(Args);
554 default:
555 return true;
556 }
557 }
558
559 if (Triple.isOSWindows()) {
560 switch (Triple.getArch()) {
561 case llvm::Triple::x86:
562 return !areOptimizationsEnabled(Args);
563 case llvm::Triple::x86_64:
564 return Triple.isOSBinFormatMachO();
565 case llvm::Triple::arm:
566 case llvm::Triple::thumb:
567 // Windows on ARM builds with FPO disabled to aid fast stack walking
568 return true;
569 default:
570 // All other supported Windows ISAs use xdata unwind information, so frame
571 // pointers are not generally useful.
572 return false;
573 }
574 }
575
576 return true;
577}
578
579static bool shouldUseFramePointer(const ArgList &Args,
580 const llvm::Triple &Triple) {
581 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
582 options::OPT_fomit_frame_pointer))
583 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
584 mustUseNonLeafFramePointerForTarget(Triple);
585
586 if (Args.hasArg(options::OPT_pg))
587 return true;
588
589 return useFramePointerForTargetByDefault(Args, Triple);
590}
591
592static bool shouldUseLeafFramePointer(const ArgList &Args,
593 const llvm::Triple &Triple) {
594 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
595 options::OPT_momit_leaf_frame_pointer))
596 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
597
598 if (Args.hasArg(options::OPT_pg))
599 return true;
600
601 if (Triple.isPS4CPU())
602 return false;
603
604 return useFramePointerForTargetByDefault(Args, Triple);
605}
606
607/// Add a CC1 option to specify the debug compilation directory.
608static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
609 SmallString<128> cwd;
610 if (!llvm::sys::fs::current_path(cwd)) {
611 CmdArgs.push_back("-fdebug-compilation-dir");
612 CmdArgs.push_back(Args.MakeArgString(cwd));
613 }
614}
615
616/// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
617/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
618static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
619 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
620 if (A->getOption().matches(options::OPT_O4) ||
621 A->getOption().matches(options::OPT_Ofast))
622 return true;
623
624 if (A->getOption().matches(options::OPT_O0))
625 return false;
626
627 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
628
629 // Vectorize -Os.
630 StringRef S(A->getValue());
631 if (S == "s")
632 return true;
633
634 // Don't vectorize -Oz, unless it's the slp vectorizer.
635 if (S == "z")
636 return isSlpVec;
637
638 unsigned OptLevel = 0;
639 if (S.getAsInteger(10, OptLevel))
640 return false;
641
642 return OptLevel > 1;
643 }
644
645 return false;
646}
647
648/// Add -x lang to \p CmdArgs for \p Input.
649static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
650 ArgStringList &CmdArgs) {
651 // When using -verify-pch, we don't want to provide the type
652 // 'precompiled-header' if it was inferred from the file extension
653 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
654 return;
655
656 CmdArgs.push_back("-x");
657 if (Args.hasArg(options::OPT_rewrite_objc))
658 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000659 else {
660 // Map the driver type to the frontend type. This is mostly an identity
661 // mapping, except that the distinction between module interface units
662 // and other source files does not exist at the frontend layer.
663 const char *ClangType;
664 switch (Input.getType()) {
665 case types::TY_CXXModule:
666 ClangType = "c++";
667 break;
668 case types::TY_PP_CXXModule:
669 ClangType = "c++-cpp-output";
670 break;
671 default:
672 ClangType = types::getTypeName(Input.getType());
673 break;
674 }
675 CmdArgs.push_back(ClangType);
676 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000677}
678
679static void appendUserToPath(SmallVectorImpl<char> &Result) {
680#ifdef LLVM_ON_UNIX
681 const char *Username = getenv("LOGNAME");
682#else
683 const char *Username = getenv("USERNAME");
684#endif
685 if (Username) {
686 // Validate that LoginName can be used in a path, and get its length.
687 size_t Len = 0;
688 for (const char *P = Username; *P; ++P, ++Len) {
689 if (!clang::isAlphanumeric(*P) && *P != '_') {
690 Username = nullptr;
691 break;
692 }
693 }
694
695 if (Username && Len > 0) {
696 Result.append(Username, Username + Len);
697 return;
698 }
699 }
700
701// Fallback to user id.
702#ifdef LLVM_ON_UNIX
703 std::string UID = llvm::utostr(getuid());
704#else
705 // FIXME: Windows seems to have an 'SID' that might work.
706 std::string UID = "9999";
707#endif
708 Result.append(UID.begin(), UID.end());
709}
710
711static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
712 const InputInfo &Output, const ArgList &Args,
713 ArgStringList &CmdArgs) {
714
715 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
716 options::OPT_fprofile_generate_EQ,
717 options::OPT_fno_profile_generate);
718 if (PGOGenerateArg &&
719 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
720 PGOGenerateArg = nullptr;
721
722 auto *ProfileGenerateArg = Args.getLastArg(
723 options::OPT_fprofile_instr_generate,
724 options::OPT_fprofile_instr_generate_EQ,
725 options::OPT_fno_profile_instr_generate);
726 if (ProfileGenerateArg &&
727 ProfileGenerateArg->getOption().matches(
728 options::OPT_fno_profile_instr_generate))
729 ProfileGenerateArg = nullptr;
730
731 if (PGOGenerateArg && ProfileGenerateArg)
732 D.Diag(diag::err_drv_argument_not_allowed_with)
733 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
734
735 auto *ProfileUseArg = getLastProfileUseArg(Args);
736
737 if (PGOGenerateArg && ProfileUseArg)
738 D.Diag(diag::err_drv_argument_not_allowed_with)
739 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
740
741 if (ProfileGenerateArg && ProfileUseArg)
742 D.Diag(diag::err_drv_argument_not_allowed_with)
743 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
744
745 if (ProfileGenerateArg) {
746 if (ProfileGenerateArg->getOption().matches(
747 options::OPT_fprofile_instr_generate_EQ))
748 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
749 ProfileGenerateArg->getValue()));
750 // The default is to use Clang Instrumentation.
751 CmdArgs.push_back("-fprofile-instrument=clang");
752 }
753
754 if (PGOGenerateArg) {
755 CmdArgs.push_back("-fprofile-instrument=llvm");
756 if (PGOGenerateArg->getOption().matches(
757 options::OPT_fprofile_generate_EQ)) {
758 SmallString<128> Path(PGOGenerateArg->getValue());
759 llvm::sys::path::append(Path, "default_%m.profraw");
760 CmdArgs.push_back(
761 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
762 }
763 }
764
765 if (ProfileUseArg) {
766 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
767 CmdArgs.push_back(Args.MakeArgString(
768 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
769 else if ((ProfileUseArg->getOption().matches(
770 options::OPT_fprofile_use_EQ) ||
771 ProfileUseArg->getOption().matches(
772 options::OPT_fprofile_instr_use))) {
773 SmallString<128> Path(
774 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
775 if (Path.empty() || llvm::sys::fs::is_directory(Path))
776 llvm::sys::path::append(Path, "default.profdata");
777 CmdArgs.push_back(
778 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
779 }
780 }
781
782 if (Args.hasArg(options::OPT_ftest_coverage) ||
783 Args.hasArg(options::OPT_coverage))
784 CmdArgs.push_back("-femit-coverage-notes");
785 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
786 false) ||
787 Args.hasArg(options::OPT_coverage))
788 CmdArgs.push_back("-femit-coverage-data");
789
790 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000791 options::OPT_fno_coverage_mapping, false)) {
792 if (!ProfileGenerateArg)
793 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
794 << "-fcoverage-mapping"
795 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000796
David L. Jonesf561aba2017-03-08 01:02:16 +0000797 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000798 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000799
800 if (C.getArgs().hasArg(options::OPT_c) ||
801 C.getArgs().hasArg(options::OPT_S)) {
802 if (Output.isFilename()) {
803 CmdArgs.push_back("-coverage-notes-file");
804 SmallString<128> OutputFilename;
805 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
806 OutputFilename = FinalOutput->getValue();
807 else
808 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
809 SmallString<128> CoverageFilename = OutputFilename;
810 if (llvm::sys::path::is_relative(CoverageFilename)) {
811 SmallString<128> Pwd;
812 if (!llvm::sys::fs::current_path(Pwd)) {
813 llvm::sys::path::append(Pwd, CoverageFilename);
814 CoverageFilename.swap(Pwd);
815 }
816 }
817 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
818 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
819
820 // Leave -fprofile-dir= an unused argument unless .gcda emission is
821 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
822 // the flag used. There is no -fno-profile-dir, so the user has no
823 // targeted way to suppress the warning.
824 if (Args.hasArg(options::OPT_fprofile_arcs) ||
825 Args.hasArg(options::OPT_coverage)) {
826 CmdArgs.push_back("-coverage-data-file");
827 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
828 CoverageFilename = FProfileDir->getValue();
829 llvm::sys::path::append(CoverageFilename, OutputFilename);
830 }
831 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
832 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
833 }
834 }
835 }
836}
837
838/// \brief Check whether the given input tree contains any compilation actions.
839static bool ContainsCompileAction(const Action *A) {
840 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
841 return true;
842
843 for (const auto &AI : A->inputs())
844 if (ContainsCompileAction(AI))
845 return true;
846
847 return false;
848}
849
850/// \brief Check if -relax-all should be passed to the internal assembler.
851/// This is done by default when compiling non-assembler source with -O0.
852static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
853 bool RelaxDefault = true;
854
855 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
856 RelaxDefault = A->getOption().matches(options::OPT_O0);
857
858 if (RelaxDefault) {
859 RelaxDefault = false;
860 for (const auto &Act : C.getActions()) {
861 if (ContainsCompileAction(Act)) {
862 RelaxDefault = true;
863 break;
864 }
865 }
866 }
867
868 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
869 RelaxDefault);
870}
871
872// Extract the integer N from a string spelled "-dwarf-N", returning 0
873// on mismatch. The StringRef input (rather than an Arg) allows
874// for use by the "-Xassembler" option parser.
875static unsigned DwarfVersionNum(StringRef ArgValue) {
876 return llvm::StringSwitch<unsigned>(ArgValue)
877 .Case("-gdwarf-2", 2)
878 .Case("-gdwarf-3", 3)
879 .Case("-gdwarf-4", 4)
880 .Case("-gdwarf-5", 5)
881 .Default(0);
882}
883
884static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
885 codegenoptions::DebugInfoKind DebugInfoKind,
886 unsigned DwarfVersion,
887 llvm::DebuggerKind DebuggerTuning) {
888 switch (DebugInfoKind) {
889 case codegenoptions::DebugLineTablesOnly:
890 CmdArgs.push_back("-debug-info-kind=line-tables-only");
891 break;
892 case codegenoptions::LimitedDebugInfo:
893 CmdArgs.push_back("-debug-info-kind=limited");
894 break;
895 case codegenoptions::FullDebugInfo:
896 CmdArgs.push_back("-debug-info-kind=standalone");
897 break;
898 default:
899 break;
900 }
901 if (DwarfVersion > 0)
902 CmdArgs.push_back(
903 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
904 switch (DebuggerTuning) {
905 case llvm::DebuggerKind::GDB:
906 CmdArgs.push_back("-debugger-tuning=gdb");
907 break;
908 case llvm::DebuggerKind::LLDB:
909 CmdArgs.push_back("-debugger-tuning=lldb");
910 break;
911 case llvm::DebuggerKind::SCE:
912 CmdArgs.push_back("-debugger-tuning=sce");
913 break;
914 default:
915 break;
916 }
917}
918
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000919static void RenderDebugInfoCompressionArgs(const ArgList &Args,
920 ArgStringList &CmdArgs,
921 const Driver &D) {
922 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
923 if (!A)
924 return;
925
926 if (A->getOption().getID() == options::OPT_gz) {
927 if (llvm::zlib::isAvailable())
928 CmdArgs.push_back("-compress-debug-sections");
929 else
930 D.Diag(diag::warn_debug_compression_unavailable);
931 return;
932 }
933
934 StringRef Value = A->getValue();
935 if (Value == "none") {
936 CmdArgs.push_back("-compress-debug-sections=none");
937 } else if (Value == "zlib" || Value == "zlib-gnu") {
938 if (llvm::zlib::isAvailable()) {
939 CmdArgs.push_back(
940 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
941 } else {
942 D.Diag(diag::warn_debug_compression_unavailable);
943 }
944 } else {
945 D.Diag(diag::err_drv_unsupported_option_argument)
946 << A->getOption().getName() << Value;
947 }
948}
949
David L. Jonesf561aba2017-03-08 01:02:16 +0000950static const char *RelocationModelName(llvm::Reloc::Model Model) {
951 switch (Model) {
952 case llvm::Reloc::Static:
953 return "static";
954 case llvm::Reloc::PIC_:
955 return "pic";
956 case llvm::Reloc::DynamicNoPIC:
957 return "dynamic-no-pic";
958 case llvm::Reloc::ROPI:
959 return "ropi";
960 case llvm::Reloc::RWPI:
961 return "rwpi";
962 case llvm::Reloc::ROPI_RWPI:
963 return "ropi-rwpi";
964 }
965 llvm_unreachable("Unknown Reloc::Model kind");
966}
967
968void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
969 const Driver &D, const ArgList &Args,
970 ArgStringList &CmdArgs,
971 const InputInfo &Output,
972 const InputInfoList &Inputs) const {
973 Arg *A;
974 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
975
976 CheckPreprocessingOptions(D, Args);
977
978 Args.AddLastArg(CmdArgs, options::OPT_C);
979 Args.AddLastArg(CmdArgs, options::OPT_CC);
980
981 // Handle dependency file generation.
982 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
983 (A = Args.getLastArg(options::OPT_MD)) ||
984 (A = Args.getLastArg(options::OPT_MMD))) {
985 // Determine the output location.
986 const char *DepFile;
987 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
988 DepFile = MF->getValue();
989 C.addFailureResultFile(DepFile, &JA);
990 } else if (Output.getType() == types::TY_Dependencies) {
991 DepFile = Output.getFilename();
992 } else if (A->getOption().matches(options::OPT_M) ||
993 A->getOption().matches(options::OPT_MM)) {
994 DepFile = "-";
995 } else {
996 DepFile = getDependencyFileName(Args, Inputs);
997 C.addFailureResultFile(DepFile, &JA);
998 }
999 CmdArgs.push_back("-dependency-file");
1000 CmdArgs.push_back(DepFile);
1001
1002 // Add a default target if one wasn't specified.
1003 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1004 const char *DepTarget;
1005
1006 // If user provided -o, that is the dependency target, except
1007 // when we are only generating a dependency file.
1008 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1009 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1010 DepTarget = OutputOpt->getValue();
1011 } else {
1012 // Otherwise derive from the base input.
1013 //
1014 // FIXME: This should use the computed output file location.
1015 SmallString<128> P(Inputs[0].getBaseInput());
1016 llvm::sys::path::replace_extension(P, "o");
1017 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1018 }
1019
Yuka Takahashicdb53482017-06-16 16:01:13 +00001020 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1021 CmdArgs.push_back("-w");
1022 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001023 CmdArgs.push_back("-MT");
1024 SmallString<128> Quoted;
1025 QuoteTarget(DepTarget, Quoted);
1026 CmdArgs.push_back(Args.MakeArgString(Quoted));
1027 }
1028
1029 if (A->getOption().matches(options::OPT_M) ||
1030 A->getOption().matches(options::OPT_MD))
1031 CmdArgs.push_back("-sys-header-deps");
1032 if ((isa<PrecompileJobAction>(JA) &&
1033 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1034 Args.hasArg(options::OPT_fmodule_file_deps))
1035 CmdArgs.push_back("-module-file-deps");
1036 }
1037
1038 if (Args.hasArg(options::OPT_MG)) {
1039 if (!A || A->getOption().matches(options::OPT_MD) ||
1040 A->getOption().matches(options::OPT_MMD))
1041 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1042 CmdArgs.push_back("-MG");
1043 }
1044
1045 Args.AddLastArg(CmdArgs, options::OPT_MP);
1046 Args.AddLastArg(CmdArgs, options::OPT_MV);
1047
1048 // Convert all -MQ <target> args to -MT <quoted target>
1049 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1050 A->claim();
1051
1052 if (A->getOption().matches(options::OPT_MQ)) {
1053 CmdArgs.push_back("-MT");
1054 SmallString<128> Quoted;
1055 QuoteTarget(A->getValue(), Quoted);
1056 CmdArgs.push_back(Args.MakeArgString(Quoted));
1057
1058 // -MT flag - no change
1059 } else {
1060 A->render(Args, CmdArgs);
1061 }
1062 }
1063
1064 // Add offload include arguments specific for CUDA. This must happen before
1065 // we -I or -include anything else, because we must pick up the CUDA headers
1066 // from the particular CUDA installation, rather than from e.g.
1067 // /usr/local/include.
1068 if (JA.isOffloading(Action::OFK_Cuda))
1069 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1070
1071 // Add -i* options, and automatically translate to
1072 // -include-pch/-include-pth for transparent PCH support. It's
1073 // wonky, but we include looking for .gch so we can support seamless
1074 // replacement into a build system already set up to be generating
1075 // .gch files.
1076 int YcIndex = -1, YuIndex = -1;
1077 {
1078 int AI = -1;
1079 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1080 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1081 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1082 // Walk the whole i_Group and skip non "-include" flags so that the index
1083 // here matches the index in the next loop below.
1084 ++AI;
1085 if (!A->getOption().matches(options::OPT_include))
1086 continue;
1087 if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
1088 YcIndex = AI;
1089 if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
1090 YuIndex = AI;
1091 }
1092 }
1093 if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
1094 Driver::InputList Inputs;
1095 D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
1096 assert(Inputs.size() == 1 && "Need one input when building pch");
1097 CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
1098 Inputs[0].second->getValue()));
1099 }
1100
1101 bool RenderedImplicitInclude = false;
1102 int AI = -1;
1103 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1104 ++AI;
1105
1106 if (getToolChain().getDriver().IsCLMode() &&
1107 A->getOption().matches(options::OPT_include)) {
1108 // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
1109 // include is compiled into foo.h, and everything after goes into
1110 // the .obj file. /Yufoo.h means that all includes prior to and including
1111 // foo.h are completely skipped and replaced with a use of the pch file
1112 // for foo.h. (Each flag can have at most one value, multiple /Yc flags
1113 // just mean that the last one wins.) If /Yc and /Yu are both present
1114 // and refer to the same file, /Yc wins.
1115 // Note that OPT__SLASH_FI gets mapped to OPT_include.
1116 // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
1117 // cl.exe seems to support both flags with different values, but that
1118 // seems strange (which flag does /Fp now refer to?), so don't implement
1119 // that until someone needs it.
1120 int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
1121 if (PchIndex != -1) {
1122 if (isa<PrecompileJobAction>(JA)) {
1123 // When building the pch, skip all includes after the pch.
1124 assert(YcIndex != -1 && PchIndex == YcIndex);
1125 if (AI >= YcIndex)
1126 continue;
1127 } else {
1128 // When using the pch, skip all includes prior to the pch.
1129 if (AI < PchIndex) {
1130 A->claim();
1131 continue;
1132 }
1133 if (AI == PchIndex) {
1134 A->claim();
1135 CmdArgs.push_back("-include-pch");
1136 CmdArgs.push_back(
1137 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
1138 continue;
1139 }
1140 }
1141 }
1142 } else if (A->getOption().matches(options::OPT_include)) {
1143 // Handling of gcc-style gch precompiled headers.
1144 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1145 RenderedImplicitInclude = true;
1146
1147 // Use PCH if the user requested it.
1148 bool UsePCH = D.CCCUsePCH;
1149
1150 bool FoundPTH = false;
1151 bool FoundPCH = false;
1152 SmallString<128> P(A->getValue());
1153 // We want the files to have a name like foo.h.pch. Add a dummy extension
1154 // so that replace_extension does the right thing.
1155 P += ".dummy";
1156 if (UsePCH) {
1157 llvm::sys::path::replace_extension(P, "pch");
1158 if (llvm::sys::fs::exists(P))
1159 FoundPCH = true;
1160 }
1161
1162 if (!FoundPCH) {
1163 llvm::sys::path::replace_extension(P, "pth");
1164 if (llvm::sys::fs::exists(P))
1165 FoundPTH = true;
1166 }
1167
1168 if (!FoundPCH && !FoundPTH) {
1169 llvm::sys::path::replace_extension(P, "gch");
1170 if (llvm::sys::fs::exists(P)) {
1171 FoundPCH = UsePCH;
1172 FoundPTH = !UsePCH;
1173 }
1174 }
1175
1176 if (FoundPCH || FoundPTH) {
1177 if (IsFirstImplicitInclude) {
1178 A->claim();
1179 if (UsePCH)
1180 CmdArgs.push_back("-include-pch");
1181 else
1182 CmdArgs.push_back("-include-pth");
1183 CmdArgs.push_back(Args.MakeArgString(P));
1184 continue;
1185 } else {
1186 // Ignore the PCH if not first on command line and emit warning.
1187 D.Diag(diag::warn_drv_pch_not_first_include) << P
1188 << A->getAsString(Args);
1189 }
1190 }
1191 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1192 // Handling of paths which must come late. These entries are handled by
1193 // the toolchain itself after the resource dir is inserted in the right
1194 // search order.
1195 // Do not claim the argument so that the use of the argument does not
1196 // silently go unnoticed on toolchains which do not honour the option.
1197 continue;
1198 }
1199
1200 // Not translated, render as usual.
1201 A->claim();
1202 A->render(Args, CmdArgs);
1203 }
1204
1205 Args.AddAllArgs(CmdArgs,
1206 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1207 options::OPT_F, options::OPT_index_header_map});
1208
1209 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1210
1211 // FIXME: There is a very unfortunate problem here, some troubled
1212 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1213 // really support that we would have to parse and then translate
1214 // those options. :(
1215 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1216 options::OPT_Xpreprocessor);
1217
1218 // -I- is a deprecated GCC feature, reject it.
1219 if (Arg *A = Args.getLastArg(options::OPT_I_))
1220 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1221
1222 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1223 // -isysroot to the CC1 invocation.
1224 StringRef sysroot = C.getSysRoot();
1225 if (sysroot != "") {
1226 if (!Args.hasArg(options::OPT_isysroot)) {
1227 CmdArgs.push_back("-isysroot");
1228 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1229 }
1230 }
1231
1232 // Parse additional include paths from environment variables.
1233 // FIXME: We should probably sink the logic for handling these from the
1234 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1235 // CPATH - included following the user specified includes (but prior to
1236 // builtin and standard includes).
1237 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1238 // C_INCLUDE_PATH - system includes enabled when compiling C.
1239 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1240 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1241 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1242 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1243 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1244 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1245 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1246
1247 // While adding the include arguments, we also attempt to retrieve the
1248 // arguments of related offloading toolchains or arguments that are specific
1249 // of an offloading programming model.
1250
1251 // Add C++ include arguments, if needed.
1252 if (types::isCXX(Inputs[0].getType()))
1253 forAllAssociatedToolChains(C, JA, getToolChain(),
1254 [&Args, &CmdArgs](const ToolChain &TC) {
1255 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1256 });
1257
1258 // Add system include arguments for all targets but IAMCU.
1259 if (!IsIAMCU)
1260 forAllAssociatedToolChains(C, JA, getToolChain(),
1261 [&Args, &CmdArgs](const ToolChain &TC) {
1262 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1263 });
1264 else {
1265 // For IAMCU add special include arguments.
1266 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1267 }
1268}
1269
1270// FIXME: Move to target hook.
1271static bool isSignedCharDefault(const llvm::Triple &Triple) {
1272 switch (Triple.getArch()) {
1273 default:
1274 return true;
1275
1276 case llvm::Triple::aarch64:
1277 case llvm::Triple::aarch64_be:
1278 case llvm::Triple::arm:
1279 case llvm::Triple::armeb:
1280 case llvm::Triple::thumb:
1281 case llvm::Triple::thumbeb:
1282 if (Triple.isOSDarwin() || Triple.isOSWindows())
1283 return true;
1284 return false;
1285
1286 case llvm::Triple::ppc:
1287 case llvm::Triple::ppc64:
1288 if (Triple.isOSDarwin())
1289 return true;
1290 return false;
1291
1292 case llvm::Triple::hexagon:
1293 case llvm::Triple::ppc64le:
1294 case llvm::Triple::systemz:
1295 case llvm::Triple::xcore:
1296 return false;
1297 }
1298}
1299
1300static bool isNoCommonDefault(const llvm::Triple &Triple) {
1301 switch (Triple.getArch()) {
1302 default:
1303 return false;
1304
1305 case llvm::Triple::xcore:
1306 case llvm::Triple::wasm32:
1307 case llvm::Triple::wasm64:
1308 return true;
1309 }
1310}
1311
1312void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1313 ArgStringList &CmdArgs, bool KernelOrKext) const {
1314 // Select the ABI to use.
1315 // FIXME: Support -meabi.
1316 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1317 const char *ABIName = nullptr;
1318 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1319 ABIName = A->getValue();
1320 } else if (Triple.isOSBinFormatMachO()) {
1321 if (arm::useAAPCSForMachO(Triple)) {
1322 ABIName = "aapcs";
1323 } else if (Triple.isWatchABI()) {
1324 ABIName = "aapcs16";
1325 } else {
1326 ABIName = "apcs-gnu";
1327 }
1328 } else if (Triple.isOSWindows()) {
1329 // FIXME: this is invalid for WindowsCE
1330 ABIName = "aapcs";
1331 } else {
1332 // Select the default based on the platform.
1333 switch (Triple.getEnvironment()) {
1334 case llvm::Triple::Android:
1335 case llvm::Triple::GNUEABI:
1336 case llvm::Triple::GNUEABIHF:
1337 case llvm::Triple::MuslEABI:
1338 case llvm::Triple::MuslEABIHF:
1339 ABIName = "aapcs-linux";
1340 break;
1341 case llvm::Triple::EABIHF:
1342 case llvm::Triple::EABI:
1343 ABIName = "aapcs";
1344 break;
1345 default:
1346 if (Triple.getOS() == llvm::Triple::NetBSD)
1347 ABIName = "apcs-gnu";
1348 else if (Triple.getOS() == llvm::Triple::OpenBSD)
1349 ABIName = "aapcs-linux";
1350 else
1351 ABIName = "aapcs";
1352 break;
1353 }
1354 }
1355 CmdArgs.push_back("-target-abi");
1356 CmdArgs.push_back(ABIName);
1357
1358 // Determine floating point ABI from the options & target defaults.
1359 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1360 if (ABI == arm::FloatABI::Soft) {
1361 // Floating point operations and argument passing are soft.
1362 // FIXME: This changes CPP defines, we need -target-soft-float.
1363 CmdArgs.push_back("-msoft-float");
1364 CmdArgs.push_back("-mfloat-abi");
1365 CmdArgs.push_back("soft");
1366 } else if (ABI == arm::FloatABI::SoftFP) {
1367 // Floating point operations are hard, but argument passing is soft.
1368 CmdArgs.push_back("-mfloat-abi");
1369 CmdArgs.push_back("soft");
1370 } else {
1371 // Floating point operations and argument passing are hard.
1372 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1373 CmdArgs.push_back("-mfloat-abi");
1374 CmdArgs.push_back("hard");
1375 }
1376
1377 // Forward the -mglobal-merge option for explicit control over the pass.
1378 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1379 options::OPT_mno_global_merge)) {
1380 CmdArgs.push_back("-backend-option");
1381 if (A->getOption().matches(options::OPT_mno_global_merge))
1382 CmdArgs.push_back("-arm-global-merge=false");
1383 else
1384 CmdArgs.push_back("-arm-global-merge=true");
1385 }
1386
1387 if (!Args.hasFlag(options::OPT_mimplicit_float,
1388 options::OPT_mno_implicit_float, true))
1389 CmdArgs.push_back("-no-implicit-float");
1390}
1391
1392void Clang::AddAArch64TargetArgs(const ArgList &Args,
1393 ArgStringList &CmdArgs) const {
1394 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1395
1396 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1397 Args.hasArg(options::OPT_mkernel) ||
1398 Args.hasArg(options::OPT_fapple_kext))
1399 CmdArgs.push_back("-disable-red-zone");
1400
1401 if (!Args.hasFlag(options::OPT_mimplicit_float,
1402 options::OPT_mno_implicit_float, true))
1403 CmdArgs.push_back("-no-implicit-float");
1404
1405 const char *ABIName = nullptr;
1406 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1407 ABIName = A->getValue();
1408 else if (Triple.isOSDarwin())
1409 ABIName = "darwinpcs";
1410 else
1411 ABIName = "aapcs";
1412
1413 CmdArgs.push_back("-target-abi");
1414 CmdArgs.push_back(ABIName);
1415
1416 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1417 options::OPT_mno_fix_cortex_a53_835769)) {
1418 CmdArgs.push_back("-backend-option");
1419 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1420 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1421 else
1422 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1423 } else if (Triple.isAndroid()) {
1424 // Enabled A53 errata (835769) workaround by default on android
1425 CmdArgs.push_back("-backend-option");
1426 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1427 }
1428
1429 // Forward the -mglobal-merge option for explicit control over the pass.
1430 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1431 options::OPT_mno_global_merge)) {
1432 CmdArgs.push_back("-backend-option");
1433 if (A->getOption().matches(options::OPT_mno_global_merge))
1434 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1435 else
1436 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1437 }
1438}
1439
1440void Clang::AddMIPSTargetArgs(const ArgList &Args,
1441 ArgStringList &CmdArgs) const {
1442 const Driver &D = getToolChain().getDriver();
1443 StringRef CPUName;
1444 StringRef ABIName;
1445 const llvm::Triple &Triple = getToolChain().getTriple();
1446 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1447
1448 CmdArgs.push_back("-target-abi");
1449 CmdArgs.push_back(ABIName.data());
1450
1451 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1452 if (ABI == mips::FloatABI::Soft) {
1453 // Floating point operations and argument passing are soft.
1454 CmdArgs.push_back("-msoft-float");
1455 CmdArgs.push_back("-mfloat-abi");
1456 CmdArgs.push_back("soft");
1457 } else {
1458 // Floating point operations and argument passing are hard.
1459 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1460 CmdArgs.push_back("-mfloat-abi");
1461 CmdArgs.push_back("hard");
1462 }
1463
1464 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1465 if (A->getOption().matches(options::OPT_mxgot)) {
1466 CmdArgs.push_back("-mllvm");
1467 CmdArgs.push_back("-mxgot");
1468 }
1469 }
1470
1471 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1472 options::OPT_mno_ldc1_sdc1)) {
1473 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1474 CmdArgs.push_back("-mllvm");
1475 CmdArgs.push_back("-mno-ldc1-sdc1");
1476 }
1477 }
1478
1479 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1480 options::OPT_mno_check_zero_division)) {
1481 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1482 CmdArgs.push_back("-mllvm");
1483 CmdArgs.push_back("-mno-check-zero-division");
1484 }
1485 }
1486
1487 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1488 StringRef v = A->getValue();
1489 CmdArgs.push_back("-mllvm");
1490 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1491 A->claim();
1492 }
1493
1494 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1495 StringRef Val = StringRef(A->getValue());
1496 if (mips::hasCompactBranches(CPUName)) {
1497 if (Val == "never" || Val == "always" || Val == "optimal") {
1498 CmdArgs.push_back("-mllvm");
1499 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1500 } else
1501 D.Diag(diag::err_drv_unsupported_option_argument)
1502 << A->getOption().getName() << Val;
1503 } else
1504 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1505 }
1506}
1507
1508void Clang::AddPPCTargetArgs(const ArgList &Args,
1509 ArgStringList &CmdArgs) const {
1510 // Select the ABI to use.
1511 const char *ABIName = nullptr;
1512 if (getToolChain().getTriple().isOSLinux())
1513 switch (getToolChain().getArch()) {
1514 case llvm::Triple::ppc64: {
1515 // When targeting a processor that supports QPX, or if QPX is
1516 // specifically enabled, default to using the ABI that supports QPX (so
1517 // long as it is not specifically disabled).
1518 bool HasQPX = false;
1519 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1520 HasQPX = A->getValue() == StringRef("a2q");
1521 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1522 if (HasQPX) {
1523 ABIName = "elfv1-qpx";
1524 break;
1525 }
1526
1527 ABIName = "elfv1";
1528 break;
1529 }
1530 case llvm::Triple::ppc64le:
1531 ABIName = "elfv2";
1532 break;
1533 default:
1534 break;
1535 }
1536
1537 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1538 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1539 // the option if given as we don't have backend support for any targets
1540 // that don't use the altivec abi.
1541 if (StringRef(A->getValue()) != "altivec")
1542 ABIName = A->getValue();
1543
1544 ppc::FloatABI FloatABI =
1545 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1546
1547 if (FloatABI == ppc::FloatABI::Soft) {
1548 // Floating point operations and argument passing are soft.
1549 CmdArgs.push_back("-msoft-float");
1550 CmdArgs.push_back("-mfloat-abi");
1551 CmdArgs.push_back("soft");
1552 } else {
1553 // Floating point operations and argument passing are hard.
1554 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1555 CmdArgs.push_back("-mfloat-abi");
1556 CmdArgs.push_back("hard");
1557 }
1558
1559 if (ABIName) {
1560 CmdArgs.push_back("-target-abi");
1561 CmdArgs.push_back(ABIName);
1562 }
1563}
1564
1565void Clang::AddSparcTargetArgs(const ArgList &Args,
1566 ArgStringList &CmdArgs) const {
1567 sparc::FloatABI FloatABI =
1568 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1569
1570 if (FloatABI == sparc::FloatABI::Soft) {
1571 // Floating point operations and argument passing are soft.
1572 CmdArgs.push_back("-msoft-float");
1573 CmdArgs.push_back("-mfloat-abi");
1574 CmdArgs.push_back("soft");
1575 } else {
1576 // Floating point operations and argument passing are hard.
1577 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1578 CmdArgs.push_back("-mfloat-abi");
1579 CmdArgs.push_back("hard");
1580 }
1581}
1582
1583void Clang::AddSystemZTargetArgs(const ArgList &Args,
1584 ArgStringList &CmdArgs) const {
1585 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1586 CmdArgs.push_back("-mbackchain");
1587}
1588
1589void Clang::AddX86TargetArgs(const ArgList &Args,
1590 ArgStringList &CmdArgs) const {
1591 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1592 Args.hasArg(options::OPT_mkernel) ||
1593 Args.hasArg(options::OPT_fapple_kext))
1594 CmdArgs.push_back("-disable-red-zone");
1595
1596 // Default to avoid implicit floating-point for kernel/kext code, but allow
1597 // that to be overridden with -mno-soft-float.
1598 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1599 Args.hasArg(options::OPT_fapple_kext));
1600 if (Arg *A = Args.getLastArg(
1601 options::OPT_msoft_float, options::OPT_mno_soft_float,
1602 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1603 const Option &O = A->getOption();
1604 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1605 O.matches(options::OPT_msoft_float));
1606 }
1607 if (NoImplicitFloat)
1608 CmdArgs.push_back("-no-implicit-float");
1609
1610 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1611 StringRef Value = A->getValue();
1612 if (Value == "intel" || Value == "att") {
1613 CmdArgs.push_back("-mllvm");
1614 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1615 } else {
1616 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1617 << A->getOption().getName() << Value;
1618 }
1619 }
1620
1621 // Set flags to support MCU ABI.
1622 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1623 CmdArgs.push_back("-mfloat-abi");
1624 CmdArgs.push_back("soft");
1625 CmdArgs.push_back("-mstack-alignment=4");
1626 }
1627}
1628
1629void Clang::AddHexagonTargetArgs(const ArgList &Args,
1630 ArgStringList &CmdArgs) const {
1631 CmdArgs.push_back("-mqdsp6-compat");
1632 CmdArgs.push_back("-Wreturn-type");
1633
1634 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1635 std::string N = llvm::utostr(G.getValue());
1636 std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
1637 CmdArgs.push_back("-mllvm");
1638 CmdArgs.push_back(Args.MakeArgString(Opt));
1639 }
1640
1641 if (!Args.hasArg(options::OPT_fno_short_enums))
1642 CmdArgs.push_back("-fshort-enums");
1643 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1644 CmdArgs.push_back("-mllvm");
1645 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1646 }
1647 CmdArgs.push_back("-mllvm");
1648 CmdArgs.push_back("-machine-sink-split=0");
1649}
1650
1651void Clang::AddLanaiTargetArgs(const ArgList &Args,
1652 ArgStringList &CmdArgs) const {
1653 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1654 StringRef CPUName = A->getValue();
1655
1656 CmdArgs.push_back("-target-cpu");
1657 CmdArgs.push_back(Args.MakeArgString(CPUName));
1658 }
1659 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1660 StringRef Value = A->getValue();
1661 // Only support mregparm=4 to support old usage. Report error for all other
1662 // cases.
1663 int Mregparm;
1664 if (Value.getAsInteger(10, Mregparm)) {
1665 if (Mregparm != 4) {
1666 getToolChain().getDriver().Diag(
1667 diag::err_drv_unsupported_option_argument)
1668 << A->getOption().getName() << Value;
1669 }
1670 }
1671 }
1672}
1673
1674void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1675 ArgStringList &CmdArgs) const {
1676 // Default to "hidden" visibility.
1677 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1678 options::OPT_fvisibility_ms_compat)) {
1679 CmdArgs.push_back("-fvisibility");
1680 CmdArgs.push_back("hidden");
1681 }
1682}
1683
1684void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1685 StringRef Target, const InputInfo &Output,
1686 const InputInfo &Input, const ArgList &Args) const {
1687 // If this is a dry run, do not create the compilation database file.
1688 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1689 return;
1690
1691 using llvm::yaml::escape;
1692 const Driver &D = getToolChain().getDriver();
1693
1694 if (!CompilationDatabase) {
1695 std::error_code EC;
1696 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1697 if (EC) {
1698 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1699 << EC.message();
1700 return;
1701 }
1702 CompilationDatabase = std::move(File);
1703 }
1704 auto &CDB = *CompilationDatabase;
1705 SmallString<128> Buf;
1706 if (llvm::sys::fs::current_path(Buf))
1707 Buf = ".";
1708 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1709 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1710 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1711 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1712 Buf = "-x";
1713 Buf += types::getTypeName(Input.getType());
1714 CDB << ", \"" << escape(Buf) << "\"";
1715 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1716 Buf = "--sysroot=";
1717 Buf += D.SysRoot;
1718 CDB << ", \"" << escape(Buf) << "\"";
1719 }
1720 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1721 for (auto &A: Args) {
1722 auto &O = A->getOption();
1723 // Skip language selection, which is positional.
1724 if (O.getID() == options::OPT_x)
1725 continue;
1726 // Skip writing dependency output and the compilation database itself.
1727 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1728 continue;
1729 // Skip inputs.
1730 if (O.getKind() == Option::InputClass)
1731 continue;
1732 // All other arguments are quoted and appended.
1733 ArgStringList ASL;
1734 A->render(Args, ASL);
1735 for (auto &it: ASL)
1736 CDB << ", \"" << escape(it) << "\"";
1737 }
1738 Buf = "--target=";
1739 Buf += Target;
1740 CDB << ", \"" << escape(Buf) << "\"]},\n";
1741}
1742
1743static void CollectArgsForIntegratedAssembler(Compilation &C,
1744 const ArgList &Args,
1745 ArgStringList &CmdArgs,
1746 const Driver &D) {
1747 if (UseRelaxAll(C, Args))
1748 CmdArgs.push_back("-mrelax-all");
1749
1750 // Only default to -mincremental-linker-compatible if we think we are
1751 // targeting the MSVC linker.
1752 bool DefaultIncrementalLinkerCompatible =
1753 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1754 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1755 options::OPT_mno_incremental_linker_compatible,
1756 DefaultIncrementalLinkerCompatible))
1757 CmdArgs.push_back("-mincremental-linker-compatible");
1758
1759 switch (C.getDefaultToolChain().getArch()) {
1760 case llvm::Triple::arm:
1761 case llvm::Triple::armeb:
1762 case llvm::Triple::thumb:
1763 case llvm::Triple::thumbeb:
1764 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1765 StringRef Value = A->getValue();
1766 if (Value == "always" || Value == "never" || Value == "arm" ||
1767 Value == "thumb") {
1768 CmdArgs.push_back("-mllvm");
1769 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1770 } else {
1771 D.Diag(diag::err_drv_unsupported_option_argument)
1772 << A->getOption().getName() << Value;
1773 }
1774 }
1775 break;
1776 default:
1777 break;
1778 }
1779
1780 // When passing -I arguments to the assembler we sometimes need to
1781 // unconditionally take the next argument. For example, when parsing
1782 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1783 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1784 // arg after parsing the '-I' arg.
1785 bool TakeNextArg = false;
1786
David L. Jonesf561aba2017-03-08 01:02:16 +00001787 bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
1788 const char *MipsTargetFeature = nullptr;
1789 for (const Arg *A :
1790 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1791 A->claim();
1792
1793 for (StringRef Value : A->getValues()) {
1794 if (TakeNextArg) {
1795 CmdArgs.push_back(Value.data());
1796 TakeNextArg = false;
1797 continue;
1798 }
1799
1800 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1801 Value == "-mbig-obj")
1802 continue; // LLVM handles bigobj automatically
1803
1804 switch (C.getDefaultToolChain().getArch()) {
1805 default:
1806 break;
1807 case llvm::Triple::mips:
1808 case llvm::Triple::mipsel:
1809 case llvm::Triple::mips64:
1810 case llvm::Triple::mips64el:
1811 if (Value == "--trap") {
1812 CmdArgs.push_back("-target-feature");
1813 CmdArgs.push_back("+use-tcc-in-div");
1814 continue;
1815 }
1816 if (Value == "--break") {
1817 CmdArgs.push_back("-target-feature");
1818 CmdArgs.push_back("-use-tcc-in-div");
1819 continue;
1820 }
1821 if (Value.startswith("-msoft-float")) {
1822 CmdArgs.push_back("-target-feature");
1823 CmdArgs.push_back("+soft-float");
1824 continue;
1825 }
1826 if (Value.startswith("-mhard-float")) {
1827 CmdArgs.push_back("-target-feature");
1828 CmdArgs.push_back("-soft-float");
1829 continue;
1830 }
1831
1832 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1833 .Case("-mips1", "+mips1")
1834 .Case("-mips2", "+mips2")
1835 .Case("-mips3", "+mips3")
1836 .Case("-mips4", "+mips4")
1837 .Case("-mips5", "+mips5")
1838 .Case("-mips32", "+mips32")
1839 .Case("-mips32r2", "+mips32r2")
1840 .Case("-mips32r3", "+mips32r3")
1841 .Case("-mips32r5", "+mips32r5")
1842 .Case("-mips32r6", "+mips32r6")
1843 .Case("-mips64", "+mips64")
1844 .Case("-mips64r2", "+mips64r2")
1845 .Case("-mips64r3", "+mips64r3")
1846 .Case("-mips64r5", "+mips64r5")
1847 .Case("-mips64r6", "+mips64r6")
1848 .Default(nullptr);
1849 if (MipsTargetFeature)
1850 continue;
1851 }
1852
1853 if (Value == "-force_cpusubtype_ALL") {
1854 // Do nothing, this is the default and we don't support anything else.
1855 } else if (Value == "-L") {
1856 CmdArgs.push_back("-msave-temp-labels");
1857 } else if (Value == "--fatal-warnings") {
1858 CmdArgs.push_back("-massembler-fatal-warnings");
1859 } else if (Value == "--noexecstack") {
1860 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001861 } else if (Value.startswith("-compress-debug-sections") ||
1862 Value.startswith("--compress-debug-sections") ||
1863 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00001864 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001865 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00001866 } else if (Value == "-mrelax-relocations=yes" ||
1867 Value == "--mrelax-relocations=yes") {
1868 UseRelaxRelocations = true;
1869 } else if (Value == "-mrelax-relocations=no" ||
1870 Value == "--mrelax-relocations=no") {
1871 UseRelaxRelocations = false;
1872 } else if (Value.startswith("-I")) {
1873 CmdArgs.push_back(Value.data());
1874 // We need to consume the next argument if the current arg is a plain
1875 // -I. The next arg will be the include directory.
1876 if (Value == "-I")
1877 TakeNextArg = true;
1878 } else if (Value.startswith("-gdwarf-")) {
1879 // "-gdwarf-N" options are not cc1as options.
1880 unsigned DwarfVersion = DwarfVersionNum(Value);
1881 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
1882 CmdArgs.push_back(Value.data());
1883 } else {
1884 RenderDebugEnablingArgs(Args, CmdArgs,
1885 codegenoptions::LimitedDebugInfo,
1886 DwarfVersion, llvm::DebuggerKind::Default);
1887 }
1888 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
1889 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
1890 // Do nothing, we'll validate it later.
1891 } else if (Value == "-defsym") {
1892 if (A->getNumValues() != 2) {
1893 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
1894 break;
1895 }
1896 const char *S = A->getValue(1);
1897 auto Pair = StringRef(S).split('=');
1898 auto Sym = Pair.first;
1899 auto SVal = Pair.second;
1900
1901 if (Sym.empty() || SVal.empty()) {
1902 D.Diag(diag::err_drv_defsym_invalid_format) << S;
1903 break;
1904 }
1905 int64_t IVal;
1906 if (SVal.getAsInteger(0, IVal)) {
1907 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
1908 break;
1909 }
1910 CmdArgs.push_back(Value.data());
1911 TakeNextArg = true;
1912 } else {
1913 D.Diag(diag::err_drv_unsupported_option_argument)
1914 << A->getOption().getName() << Value;
1915 }
1916 }
1917 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001918 if (UseRelaxRelocations)
1919 CmdArgs.push_back("--mrelax-relocations");
1920 if (MipsTargetFeature != nullptr) {
1921 CmdArgs.push_back("-target-feature");
1922 CmdArgs.push_back(MipsTargetFeature);
1923 }
1924}
1925
1926void Clang::ConstructJob(Compilation &C, const JobAction &JA,
1927 const InputInfo &Output, const InputInfoList &Inputs,
1928 const ArgList &Args, const char *LinkingOutput) const {
1929 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1930 const std::string &TripleStr = Triple.getTriple();
1931
1932 bool KernelOrKext =
1933 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1934 const Driver &D = getToolChain().getDriver();
1935 ArgStringList CmdArgs;
1936
1937 // Check number of inputs for sanity. We need at least one input.
1938 assert(Inputs.size() >= 1 && "Must have at least one input.");
1939 const InputInfo &Input = Inputs[0];
1940 // CUDA compilation may have multiple inputs (source file + results of
1941 // device-side compilations). OpenMP device jobs also take the host IR as a
1942 // second input. All other jobs are expected to have exactly one
1943 // input.
1944 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
1945 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
1946 assert((IsCuda || (IsOpenMPDevice && Inputs.size() == 2) ||
1947 Inputs.size() == 1) &&
1948 "Unable to handle multiple inputs.");
1949
1950 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
1951 bool IsWindowsCygnus =
1952 getToolChain().getTriple().isWindowsCygwinEnvironment();
1953 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
1954 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
1955 bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1956
1957 // Adjust IsWindowsXYZ for CUDA compilations. Even when compiling in device
1958 // mode (i.e., getToolchain().getTriple() is NVPTX, not Windows), we need to
1959 // pass Windows-specific flags to cc1.
1960 if (IsCuda) {
1961 const llvm::Triple *AuxTriple = getToolChain().getAuxTriple();
1962 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
1963 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
1964 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
1965 }
1966
1967 // C++ is not supported for IAMCU.
1968 if (IsIAMCU && types::isCXX(Input.getType()))
1969 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
1970
1971 // Invoke ourselves in -cc1 mode.
1972 //
1973 // FIXME: Implement custom jobs for internal actions.
1974 CmdArgs.push_back("-cc1");
1975
1976 // Add the "effective" target triple.
1977 CmdArgs.push_back("-triple");
1978 CmdArgs.push_back(Args.MakeArgString(TripleStr));
1979
1980 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
1981 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
1982 Args.ClaimAllArgs(options::OPT_MJ);
1983 }
1984
1985 if (IsCuda) {
1986 // We have to pass the triple of the host if compiling for a CUDA device and
1987 // vice-versa.
1988 std::string NormalizedTriple;
1989 if (JA.isDeviceOffloading(Action::OFK_Cuda))
1990 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
1991 ->getTriple()
1992 .normalize();
1993 else
1994 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
1995 ->getTriple()
1996 .normalize();
1997
1998 CmdArgs.push_back("-aux-triple");
1999 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
2000 }
2001
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00002002 if (IsOpenMPDevice) {
2003 // We have to pass the triple of the host if compiling for an OpenMP device.
2004 std::string NormalizedTriple =
2005 C.getSingleOffloadToolChain<Action::OFK_Host>()
2006 ->getTriple()
2007 .normalize();
2008 CmdArgs.push_back("-aux-triple");
2009 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
2010 }
2011
David L. Jonesf561aba2017-03-08 01:02:16 +00002012 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
2013 Triple.getArch() == llvm::Triple::thumb)) {
2014 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
2015 unsigned Version;
2016 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
2017 if (Version < 7)
2018 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
2019 << TripleStr;
2020 }
2021
2022 // Push all default warning arguments that are specific to
2023 // the given target. These come before user provided warning options
2024 // are provided.
2025 getToolChain().addClangWarningOptions(CmdArgs);
2026
2027 // Select the appropriate action.
2028 RewriteKind rewriteKind = RK_None;
2029
2030 if (isa<AnalyzeJobAction>(JA)) {
2031 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2032 CmdArgs.push_back("-analyze");
2033 } else if (isa<MigrateJobAction>(JA)) {
2034 CmdArgs.push_back("-migrate");
2035 } else if (isa<PreprocessJobAction>(JA)) {
2036 if (Output.getType() == types::TY_Dependencies)
2037 CmdArgs.push_back("-Eonly");
2038 else {
2039 CmdArgs.push_back("-E");
2040 if (Args.hasArg(options::OPT_rewrite_objc) &&
2041 !Args.hasArg(options::OPT_g_Group))
2042 CmdArgs.push_back("-P");
2043 }
2044 } else if (isa<AssembleJobAction>(JA)) {
2045 CmdArgs.push_back("-emit-obj");
2046
2047 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2048
2049 // Also ignore explicit -force_cpusubtype_ALL option.
2050 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
2051 } else if (isa<PrecompileJobAction>(JA)) {
2052 // Use PCH if the user requested it.
2053 bool UsePCH = D.CCCUsePCH;
2054
2055 if (JA.getType() == types::TY_Nothing)
2056 CmdArgs.push_back("-fsyntax-only");
2057 else if (JA.getType() == types::TY_ModuleFile)
2058 CmdArgs.push_back("-emit-module-interface");
2059 else if (UsePCH)
2060 CmdArgs.push_back("-emit-pch");
2061 else
2062 CmdArgs.push_back("-emit-pth");
2063 } else if (isa<VerifyPCHJobAction>(JA)) {
2064 CmdArgs.push_back("-verify-pch");
2065 } else {
2066 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
2067 "Invalid action for clang tool.");
2068 if (JA.getType() == types::TY_Nothing) {
2069 CmdArgs.push_back("-fsyntax-only");
2070 } else if (JA.getType() == types::TY_LLVM_IR ||
2071 JA.getType() == types::TY_LTO_IR) {
2072 CmdArgs.push_back("-emit-llvm");
2073 } else if (JA.getType() == types::TY_LLVM_BC ||
2074 JA.getType() == types::TY_LTO_BC) {
2075 CmdArgs.push_back("-emit-llvm-bc");
2076 } else if (JA.getType() == types::TY_PP_Asm) {
2077 CmdArgs.push_back("-S");
2078 } else if (JA.getType() == types::TY_AST) {
2079 CmdArgs.push_back("-emit-pch");
2080 } else if (JA.getType() == types::TY_ModuleFile) {
2081 CmdArgs.push_back("-module-file-info");
2082 } else if (JA.getType() == types::TY_RewrittenObjC) {
2083 CmdArgs.push_back("-rewrite-objc");
2084 rewriteKind = RK_NonFragile;
2085 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2086 CmdArgs.push_back("-rewrite-objc");
2087 rewriteKind = RK_Fragile;
2088 } else {
2089 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
2090 }
2091
2092 // Preserve use-list order by default when emitting bitcode, so that
2093 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
2094 // same result as running passes here. For LTO, we don't need to preserve
2095 // the use-list order, since serialization to bitcode is part of the flow.
2096 if (JA.getType() == types::TY_LLVM_BC)
2097 CmdArgs.push_back("-emit-llvm-uselists");
2098
2099 if (D.isUsingLTO()) {
2100 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
2101
2102 // The Darwin linker currently uses the legacy LTO API, which does not
2103 // support LTO unit features (CFI, whole program vtable opt) under
2104 // ThinLTO.
2105 if (!getToolChain().getTriple().isOSDarwin() ||
2106 D.getLTOMode() == LTOK_Full)
2107 CmdArgs.push_back("-flto-unit");
2108 }
2109 }
2110
2111 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
2112 if (!types::isLLVMIR(Input.getType()))
2113 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
2114 << "-x ir";
2115 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
2116 }
2117
2118 // Embed-bitcode option.
2119 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
2120 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
2121 // Add flags implied by -fembed-bitcode.
2122 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2123 // Disable all llvm IR level optimizations.
2124 CmdArgs.push_back("-disable-llvm-passes");
2125 }
2126 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
2127 CmdArgs.push_back("-fembed-bitcode=marker");
2128
2129 // We normally speed up the clang process a bit by skipping destructors at
2130 // exit, but when we're generating diagnostics we can rely on some of the
2131 // cleanup.
2132 if (!C.isForDiagnostics())
2133 CmdArgs.push_back("-disable-free");
2134
2135// Disable the verification pass in -asserts builds.
2136#ifdef NDEBUG
2137 CmdArgs.push_back("-disable-llvm-verifier");
2138 // Discard LLVM value names in -asserts builds.
2139 CmdArgs.push_back("-discard-value-names");
2140#endif
2141
2142 // Set the main file name, so that debug info works even with
2143 // -save-temps.
2144 CmdArgs.push_back("-main-file-name");
2145 CmdArgs.push_back(getBaseInputName(Args, Input));
2146
2147 // Some flags which affect the language (via preprocessor
2148 // defines).
2149 if (Args.hasArg(options::OPT_static))
2150 CmdArgs.push_back("-static-define");
2151
2152 if (isa<AnalyzeJobAction>(JA)) {
2153 // Enable region store model by default.
2154 CmdArgs.push_back("-analyzer-store=region");
2155
2156 // Treat blocks as analysis entry points.
2157 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2158
2159 CmdArgs.push_back("-analyzer-eagerly-assume");
2160
2161 // Add default argument set.
2162 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2163 CmdArgs.push_back("-analyzer-checker=core");
2164 CmdArgs.push_back("-analyzer-checker=apiModeling");
2165
2166 if (!IsWindowsMSVC) {
2167 CmdArgs.push_back("-analyzer-checker=unix");
2168 } else {
2169 // Enable "unix" checkers that also work on Windows.
2170 CmdArgs.push_back("-analyzer-checker=unix.API");
2171 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2172 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2173 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2174 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2175 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2176 }
2177
2178 // Disable some unix checkers for PS4.
2179 if (IsPS4CPU) {
2180 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2181 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2182 }
2183
2184 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2185 CmdArgs.push_back("-analyzer-checker=osx");
2186
2187 CmdArgs.push_back("-analyzer-checker=deadcode");
2188
2189 if (types::isCXX(Input.getType()))
2190 CmdArgs.push_back("-analyzer-checker=cplusplus");
2191
2192 if (!IsPS4CPU) {
2193 CmdArgs.push_back(
2194 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
2195 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2196 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2197 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2198 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2199 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2200 }
2201
2202 // Default nullability checks.
2203 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2204 CmdArgs.push_back(
2205 "-analyzer-checker=nullability.NullReturnedFromNonnull");
2206 }
2207
2208 // Set the output format. The default is plist, for (lame) historical
2209 // reasons.
2210 CmdArgs.push_back("-analyzer-output");
2211 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2212 CmdArgs.push_back(A->getValue());
2213 else
2214 CmdArgs.push_back("plist");
2215
2216 // Disable the presentation of standard compiler warnings when
2217 // using --analyze. We only want to show static analyzer diagnostics
2218 // or frontend errors.
2219 CmdArgs.push_back("-w");
2220
2221 // Add -Xanalyzer arguments when running as analyzer.
2222 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2223 }
2224
2225 CheckCodeGenerationOptions(D, Args);
2226
2227 llvm::Reloc::Model RelocationModel;
2228 unsigned PICLevel;
2229 bool IsPIE;
2230 std::tie(RelocationModel, PICLevel, IsPIE) =
2231 ParsePICArgs(getToolChain(), Args);
2232
2233 const char *RMName = RelocationModelName(RelocationModel);
2234
2235 if ((RelocationModel == llvm::Reloc::ROPI ||
2236 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
2237 types::isCXX(Input.getType()) &&
2238 !Args.hasArg(options::OPT_fallow_unsupported))
2239 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
2240
2241 if (RMName) {
2242 CmdArgs.push_back("-mrelocation-model");
2243 CmdArgs.push_back(RMName);
2244 }
2245 if (PICLevel > 0) {
2246 CmdArgs.push_back("-pic-level");
2247 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
2248 if (IsPIE)
2249 CmdArgs.push_back("-pic-is-pie");
2250 }
2251
2252 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
2253 CmdArgs.push_back("-meabi");
2254 CmdArgs.push_back(A->getValue());
2255 }
2256
2257 CmdArgs.push_back("-mthread-model");
2258 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
2259 CmdArgs.push_back(A->getValue());
2260 else
2261 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
2262
2263 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
2264
2265 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
2266 options::OPT_fno_merge_all_constants))
2267 CmdArgs.push_back("-fno-merge-all-constants");
2268
2269 // LLVM Code Generator Options.
2270
2271 if (Args.hasArg(options::OPT_frewrite_map_file) ||
2272 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
2273 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
2274 options::OPT_frewrite_map_file_EQ)) {
2275 StringRef Map = A->getValue();
2276 if (!llvm::sys::fs::exists(Map)) {
2277 D.Diag(diag::err_drv_no_such_file) << Map;
2278 } else {
2279 CmdArgs.push_back("-frewrite-map-file");
2280 CmdArgs.push_back(A->getValue());
2281 A->claim();
2282 }
2283 }
2284 }
2285
2286 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
2287 StringRef v = A->getValue();
2288 CmdArgs.push_back("-mllvm");
2289 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
2290 A->claim();
2291 }
2292
2293 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
2294 true))
2295 CmdArgs.push_back("-fno-jump-tables");
2296
2297 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
2298 options::OPT_fno_preserve_as_comments, true))
2299 CmdArgs.push_back("-fno-preserve-as-comments");
2300
2301 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2302 CmdArgs.push_back("-mregparm");
2303 CmdArgs.push_back(A->getValue());
2304 }
2305
2306 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
2307 options::OPT_freg_struct_return)) {
2308 if (getToolChain().getArch() != llvm::Triple::x86) {
2309 D.Diag(diag::err_drv_unsupported_opt_for_target)
2310 << A->getSpelling() << getToolChain().getTriple().str();
2311 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
2312 CmdArgs.push_back("-fpcc-struct-return");
2313 } else {
2314 assert(A->getOption().matches(options::OPT_freg_struct_return));
2315 CmdArgs.push_back("-freg-struct-return");
2316 }
2317 }
2318
2319 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
2320 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
2321
2322 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
2323 CmdArgs.push_back("-mdisable-fp-elim");
2324 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
2325 options::OPT_fno_zero_initialized_in_bss))
2326 CmdArgs.push_back("-mno-zero-initialized-in-bss");
2327
2328 bool OFastEnabled = isOptimizationLevelFast(Args);
2329 // If -Ofast is the optimization level, then -fstrict-aliasing should be
2330 // enabled. This alias option is being used to simplify the hasFlag logic.
2331 OptSpecifier StrictAliasingAliasOption =
2332 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
2333 // We turn strict aliasing off by default if we're in CL mode, since MSVC
2334 // doesn't do any TBAA.
2335 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
2336 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
2337 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
2338 CmdArgs.push_back("-relaxed-aliasing");
2339 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
2340 options::OPT_fno_struct_path_tbaa))
2341 CmdArgs.push_back("-no-struct-path-tbaa");
2342 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
2343 false))
2344 CmdArgs.push_back("-fstrict-enums");
2345 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
2346 true))
2347 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00002348 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
2349 options::OPT_fno_allow_editor_placeholders, false))
2350 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00002351 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
2352 options::OPT_fno_strict_vtable_pointers,
2353 false))
2354 CmdArgs.push_back("-fstrict-vtable-pointers");
2355 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
2356 options::OPT_fno_optimize_sibling_calls))
2357 CmdArgs.push_back("-mdisable-tail-calls");
2358
2359 // Handle segmented stacks.
2360 if (Args.hasArg(options::OPT_fsplit_stack))
2361 CmdArgs.push_back("-split-stacks");
2362
David L. Jonesf561aba2017-03-08 01:02:16 +00002363 // Handle various floating point optimization flags, mapping them to the
John Brawn5c4c6112017-03-15 14:03:32 +00002364 // appropriate LLVM code generation flags. This is complicated by several
2365 // "umbrella" flags, so we do this by stepping through the flags incrementally
2366 // adjusting what we think is enabled/disabled, then at the end settting the
2367 // LLVM flags based on the final state.
2368 bool HonorInfs = true;
2369 bool HonorNans = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002370 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2371 bool MathErrno = getToolChain().IsMathErrnoDefault();
John Brawn5c4c6112017-03-15 14:03:32 +00002372 bool AssociativeMath = false;
2373 bool ReciprocalMath = false;
2374 bool SignedZeros = true;
2375 bool TrappingMath = true;
2376 StringRef DenormalFpMath = "";
2377 StringRef FpContract = "";
2378
2379 for (Arg *A : Args) {
2380 switch (A->getOption().getID()) {
2381 // If this isn't an FP option skip the claim below
2382 default:
2383 continue;
2384
2385 // Options controlling individual features
2386 case options::OPT_fhonor_infinities: HonorInfs = true; break;
2387 case options::OPT_fno_honor_infinities: HonorInfs = false; break;
2388 case options::OPT_fhonor_nans: HonorNans = true; break;
2389 case options::OPT_fno_honor_nans: HonorNans = false; break;
2390 case options::OPT_fmath_errno: MathErrno = true; break;
2391 case options::OPT_fno_math_errno: MathErrno = false; break;
2392 case options::OPT_fassociative_math: AssociativeMath = true; break;
2393 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2394 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2395 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2396 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2397 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2398 case options::OPT_ftrapping_math: TrappingMath = true; break;
2399 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2400
2401 case options::OPT_fdenormal_fp_math_EQ:
2402 DenormalFpMath = A->getValue();
2403 break;
2404
2405 // Validate and pass through -fp-contract option.
2406 case options::OPT_ffp_contract: {
2407 StringRef Val = A->getValue();
2408 if (Val == "fast" || Val == "on" || Val == "off") {
2409 FpContract = Val;
2410 } else {
2411 D.Diag(diag::err_drv_unsupported_option_argument)
2412 << A->getOption().getName() << Val;
2413 }
2414 break;
2415 }
2416
2417 case options::OPT_ffinite_math_only:
2418 HonorInfs = false;
2419 HonorNans = false;
2420 break;
2421 case options::OPT_fno_finite_math_only:
2422 HonorInfs = true;
2423 HonorNans = true;
2424 break;
2425
2426 case options::OPT_funsafe_math_optimizations:
2427 AssociativeMath = true;
2428 ReciprocalMath = true;
2429 SignedZeros = false;
2430 TrappingMath = false;
2431 break;
2432 case options::OPT_fno_unsafe_math_optimizations:
2433 AssociativeMath = false;
2434 ReciprocalMath = false;
2435 SignedZeros = true;
2436 TrappingMath = true;
2437 // -fno_unsafe_math_optimizations restores default denormal handling
2438 DenormalFpMath = "";
2439 break;
2440
2441 case options::OPT_Ofast:
2442 // If -Ofast is the optimization level, then -ffast-math should be enabled
2443 if (!OFastEnabled)
2444 continue;
2445 LLVM_FALLTHROUGH;
2446 case options::OPT_ffast_math:
2447 HonorInfs = false;
2448 HonorNans = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00002449 MathErrno = false;
John Brawn5c4c6112017-03-15 14:03:32 +00002450 AssociativeMath = true;
2451 ReciprocalMath = true;
2452 SignedZeros = false;
2453 TrappingMath = false;
2454 // If fast-math is set then set the fp-contract mode to fast.
2455 FpContract = "fast";
2456 break;
2457 case options::OPT_fno_fast_math:
2458 HonorInfs = true;
2459 HonorNans = true;
2460 // Turning on -ffast-math (with either flag) removes the need for
2461 // MathErrno. However, turning *off* -ffast-math merely restores the
2462 // toolchain default (which may be false).
2463 MathErrno = getToolChain().IsMathErrnoDefault();
2464 AssociativeMath = false;
2465 ReciprocalMath = false;
2466 SignedZeros = true;
2467 TrappingMath = true;
2468 // -fno_fast_math restores default denormal and fpcontract handling
2469 DenormalFpMath = "";
2470 FpContract = "";
2471 break;
2472 }
2473 // If we handled this option claim it
2474 A->claim();
David L. Jonesf561aba2017-03-08 01:02:16 +00002475 }
John Brawn5c4c6112017-03-15 14:03:32 +00002476
2477 if (!HonorInfs)
2478 CmdArgs.push_back("-menable-no-infs");
2479
2480 if (!HonorNans)
2481 CmdArgs.push_back("-menable-no-nans");
2482
David L. Jonesf561aba2017-03-08 01:02:16 +00002483 if (MathErrno)
2484 CmdArgs.push_back("-fmath-errno");
2485
David L. Jonesf561aba2017-03-08 01:02:16 +00002486 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2487 !TrappingMath)
2488 CmdArgs.push_back("-menable-unsafe-fp-math");
2489
2490 if (!SignedZeros)
2491 CmdArgs.push_back("-fno-signed-zeros");
2492
2493 if (ReciprocalMath)
2494 CmdArgs.push_back("-freciprocal-math");
2495
2496 if (!TrappingMath)
2497 CmdArgs.push_back("-fno-trapping-math");
2498
John Brawn5c4c6112017-03-15 14:03:32 +00002499 if (!DenormalFpMath.empty())
2500 CmdArgs.push_back(Args.MakeArgString("-fdenormal-fp-math="+DenormalFpMath));
David L. Jonesf561aba2017-03-08 01:02:16 +00002501
John Brawn5c4c6112017-03-15 14:03:32 +00002502 if (!FpContract.empty())
2503 CmdArgs.push_back(Args.MakeArgString("-ffp-contract="+FpContract));
David L. Jonesf561aba2017-03-08 01:02:16 +00002504
2505 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
2506
John Brawn5c4c6112017-03-15 14:03:32 +00002507 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2508 // individual features enabled by -ffast-math instead of the option itself as
2509 // that's consistent with gcc's behaviour.
2510 if (!HonorInfs && !HonorNans && !MathErrno && AssociativeMath &&
2511 ReciprocalMath && !SignedZeros && !TrappingMath)
2512 CmdArgs.push_back("-ffast-math");
2513
2514 // Handle __FINITE_MATH_ONLY__ similarly.
2515 if (!HonorInfs && !HonorNans)
2516 CmdArgs.push_back("-ffinite-math-only");
David L. Jonesf561aba2017-03-08 01:02:16 +00002517
2518 // Decide whether to use verbose asm. Verbose assembly is the default on
2519 // toolchains which have the integrated assembler on by default.
2520 bool IsIntegratedAssemblerDefault =
2521 getToolChain().IsIntegratedAssemblerDefault();
2522 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2523 IsIntegratedAssemblerDefault) ||
2524 Args.hasArg(options::OPT_dA))
2525 CmdArgs.push_back("-masm-verbose");
2526
2527 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
2528 IsIntegratedAssemblerDefault))
2529 CmdArgs.push_back("-no-integrated-as");
2530
2531 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2532 CmdArgs.push_back("-mdebug-pass");
2533 CmdArgs.push_back("Structure");
2534 }
2535 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2536 CmdArgs.push_back("-mdebug-pass");
2537 CmdArgs.push_back("Arguments");
2538 }
2539
2540 // Enable -mconstructor-aliases except on darwin, where we have to work around
2541 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
2542 // aliases aren't supported.
2543 if (!getToolChain().getTriple().isOSDarwin() &&
2544 !getToolChain().getTriple().isNVPTX())
2545 CmdArgs.push_back("-mconstructor-aliases");
2546
2547 // Darwin's kernel doesn't support guard variables; just die if we
2548 // try to use them.
2549 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2550 CmdArgs.push_back("-fforbid-guard-variables");
2551
2552 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
2553 false)) {
2554 CmdArgs.push_back("-mms-bitfields");
2555 }
2556
2557 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
2558 options::OPT_mno_pie_copy_relocations,
2559 false)) {
2560 CmdArgs.push_back("-mpie-copy-relocations");
2561 }
2562
2563 // This is a coarse approximation of what llvm-gcc actually does, both
2564 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2565 // complicated ways.
2566 bool AsynchronousUnwindTables =
2567 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2568 options::OPT_fno_asynchronous_unwind_tables,
2569 (getToolChain().IsUnwindTablesDefault() ||
2570 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
2571 !KernelOrKext);
2572 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2573 AsynchronousUnwindTables))
2574 CmdArgs.push_back("-munwind-tables");
2575
2576 getToolChain().addClangTargetOptions(Args, CmdArgs);
2577
2578 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2579 CmdArgs.push_back("-mlimit-float-precision");
2580 CmdArgs.push_back(A->getValue());
2581 }
2582
2583 // FIXME: Handle -mtune=.
2584 (void)Args.hasArg(options::OPT_mtune_EQ);
2585
2586 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2587 CmdArgs.push_back("-mcode-model");
2588 CmdArgs.push_back(A->getValue());
2589 }
2590
2591 // Add the target cpu
2592 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
2593 if (!CPU.empty()) {
2594 CmdArgs.push_back("-target-cpu");
2595 CmdArgs.push_back(Args.MakeArgString(CPU));
2596 }
2597
2598 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2599 CmdArgs.push_back("-mfpmath");
2600 CmdArgs.push_back(A->getValue());
2601 }
2602
2603 // Add the target features
2604 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
2605
2606 // Add target specific flags.
2607 switch (getToolChain().getArch()) {
2608 default:
2609 break;
2610
2611 case llvm::Triple::arm:
2612 case llvm::Triple::armeb:
2613 case llvm::Triple::thumb:
2614 case llvm::Triple::thumbeb:
2615 // Use the effective triple, which takes into account the deployment target.
2616 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
2617 break;
2618
2619 case llvm::Triple::aarch64:
2620 case llvm::Triple::aarch64_be:
2621 AddAArch64TargetArgs(Args, CmdArgs);
2622 break;
2623
2624 case llvm::Triple::mips:
2625 case llvm::Triple::mipsel:
2626 case llvm::Triple::mips64:
2627 case llvm::Triple::mips64el:
2628 AddMIPSTargetArgs(Args, CmdArgs);
2629 break;
2630
2631 case llvm::Triple::ppc:
2632 case llvm::Triple::ppc64:
2633 case llvm::Triple::ppc64le:
2634 AddPPCTargetArgs(Args, CmdArgs);
2635 break;
2636
2637 case llvm::Triple::sparc:
2638 case llvm::Triple::sparcel:
2639 case llvm::Triple::sparcv9:
2640 AddSparcTargetArgs(Args, CmdArgs);
2641 break;
2642
2643 case llvm::Triple::systemz:
2644 AddSystemZTargetArgs(Args, CmdArgs);
2645 break;
2646
2647 case llvm::Triple::x86:
2648 case llvm::Triple::x86_64:
2649 AddX86TargetArgs(Args, CmdArgs);
2650 break;
2651
2652 case llvm::Triple::lanai:
2653 AddLanaiTargetArgs(Args, CmdArgs);
2654 break;
2655
2656 case llvm::Triple::hexagon:
2657 AddHexagonTargetArgs(Args, CmdArgs);
2658 break;
2659
2660 case llvm::Triple::wasm32:
2661 case llvm::Triple::wasm64:
2662 AddWebAssemblyTargetArgs(Args, CmdArgs);
2663 break;
2664 }
2665
2666 // The 'g' groups options involve a somewhat intricate sequence of decisions
2667 // about what to pass from the driver to the frontend, but by the time they
2668 // reach cc1 they've been factored into three well-defined orthogonal choices:
2669 // * what level of debug info to generate
2670 // * what dwarf version to write
2671 // * what debugger tuning to use
2672 // This avoids having to monkey around further in cc1 other than to disable
2673 // codeview if not running in a Windows environment. Perhaps even that
2674 // decision should be made in the driver as well though.
2675 unsigned DwarfVersion = 0;
2676 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
2677 // These two are potentially updated by AddClangCLArgs.
2678 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
2679 bool EmitCodeView = false;
2680
2681 // Add clang-cl arguments.
2682 types::ID InputType = Input.getType();
2683 if (getToolChain().getDriver().IsCLMode())
2684 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
2685
2686 // Pass the linker version in use.
2687 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2688 CmdArgs.push_back("-target-linker-version");
2689 CmdArgs.push_back(A->getValue());
2690 }
2691
2692 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
2693 CmdArgs.push_back("-momit-leaf-frame-pointer");
2694
2695 // Explicitly error on some things we know we don't support and can't just
2696 // ignore.
2697 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
2698 Arg *Unsupported;
2699 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
2700 getToolChain().getArch() == llvm::Triple::x86) {
2701 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
2702 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
2703 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
2704 << Unsupported->getOption().getName();
2705 }
Eric Christopher758aad72017-03-21 22:06:18 +00002706 // The faltivec option has been superseded by the maltivec option.
2707 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
2708 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
2709 << Unsupported->getOption().getName()
2710 << "please use -maltivec and include altivec.h explicitly";
2711 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
2712 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
2713 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00002714 }
2715
2716 Args.AddAllArgs(CmdArgs, options::OPT_v);
2717 Args.AddLastArg(CmdArgs, options::OPT_H);
2718 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
2719 CmdArgs.push_back("-header-include-file");
2720 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
2721 : "-");
2722 }
2723 Args.AddLastArg(CmdArgs, options::OPT_P);
2724 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
2725
2726 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
2727 CmdArgs.push_back("-diagnostic-log-file");
2728 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
2729 : "-");
2730 }
2731
2732 bool splitDwarfInlining =
2733 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2734 options::OPT_fno_split_dwarf_inlining, true);
2735
2736 Args.ClaimAllArgs(options::OPT_g_Group);
2737 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2738 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2739 // If the last option explicitly specified a debug-info level, use it.
2740 if (A->getOption().matches(options::OPT_gN_Group)) {
2741 DebugInfoKind = DebugLevelToInfoKind(*A);
2742 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2743 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2744 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
2745 // This gets a bit more complicated if you've disabled inline info in the
2746 // skeleton CUs (splitDwarfInlining) - then there's value in composing
2747 // split-dwarf and line-tables-only, so let those compose naturally in
2748 // that case.
2749 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2750 if (SplitDwarfArg) {
2751 if (A->getIndex() > SplitDwarfArg->getIndex()) {
2752 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2753 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2754 splitDwarfInlining))
2755 SplitDwarfArg = nullptr;
2756 } else if (splitDwarfInlining)
2757 DebugInfoKind = codegenoptions::NoDebugInfo;
2758 }
2759 } else
2760 // For any other 'g' option, use Limited.
2761 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2762 }
2763
2764 // If a debugger tuning argument appeared, remember it.
2765 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2766 options::OPT_ggdbN_Group)) {
2767 if (A->getOption().matches(options::OPT_glldb))
2768 DebuggerTuning = llvm::DebuggerKind::LLDB;
2769 else if (A->getOption().matches(options::OPT_gsce))
2770 DebuggerTuning = llvm::DebuggerKind::SCE;
2771 else
2772 DebuggerTuning = llvm::DebuggerKind::GDB;
2773 }
2774
2775 // If a -gdwarf argument appeared, remember it.
2776 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2777 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2778 DwarfVersion = DwarfVersionNum(A->getSpelling());
2779
2780 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2781 // argument parsing.
2782 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
2783 // DwarfVersion remains at 0 if no explicit choice was made.
2784 CmdArgs.push_back("-gcodeview");
2785 } else if (DwarfVersion == 0 &&
2786 DebugInfoKind != codegenoptions::NoDebugInfo) {
2787 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
2788 }
2789
Eric Christopherca325172017-03-29 23:34:20 +00002790 // We ignore flag -gstrict-dwarf for now.
2791 // And we handle flag -grecord-gcc-switches later with DwarfDebugFlags.
David L. Jonesf561aba2017-03-08 01:02:16 +00002792 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2793
2794 // Column info is included by default for everything except PS4 and CodeView.
2795 // Clang doesn't track end columns, just starting columns, which, in theory,
2796 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2797 // debuggers don't handle missing end columns well, so it's better not to
2798 // include any column info.
2799 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
2800 /*Default=*/ !IsPS4CPU && !(IsWindowsMSVC && EmitCodeView)))
2801 CmdArgs.push_back("-dwarf-column-info");
2802
2803 // FIXME: Move backend command line options to the module.
2804 // If -gline-tables-only is the last option it wins.
2805 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2806 Args.hasArg(options::OPT_gmodules)) {
2807 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2808 CmdArgs.push_back("-dwarf-ext-refs");
2809 CmdArgs.push_back("-fmodule-format=obj");
2810 }
2811
2812 // -gsplit-dwarf should turn on -g and enable the backend dwarf
2813 // splitting and extraction.
2814 // FIXME: Currently only works on Linux.
David Blaikie9bb296c2017-04-28 20:50:25 +00002815 if (getToolChain().getTriple().isOSLinux()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00002816 if (!splitDwarfInlining)
2817 CmdArgs.push_back("-fno-split-dwarf-inlining");
David Blaikie9bb296c2017-04-28 20:50:25 +00002818 if (SplitDwarfArg) {
2819 if (DebugInfoKind == codegenoptions::NoDebugInfo)
2820 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2821 CmdArgs.push_back("-enable-split-dwarf");
2822 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002823 }
2824
2825 // After we've dealt with all combinations of things that could
2826 // make DebugInfoKind be other than None or DebugLineTablesOnly,
2827 // figure out if we need to "upgrade" it to standalone debug info.
2828 // We parse these two '-f' options whether or not they will be used,
2829 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
2830 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
2831 options::OPT_fno_standalone_debug,
2832 getToolChain().GetDefaultStandaloneDebug());
2833 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
2834 DebugInfoKind = codegenoptions::FullDebugInfo;
2835 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
2836 DebuggerTuning);
2837
2838 // -fdebug-macro turns on macro debug info generation.
2839 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
2840 false))
2841 CmdArgs.push_back("-debug-info-macro");
2842
2843 // -ggnu-pubnames turns on gnu style pubnames in the backend.
2844 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
2845 CmdArgs.push_back("-backend-option");
2846 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
2847 }
2848
2849 // -gdwarf-aranges turns on the emission of the aranges section in the
2850 // backend.
2851 // Always enabled on the PS4.
2852 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
2853 CmdArgs.push_back("-backend-option");
2854 CmdArgs.push_back("-generate-arange-section");
2855 }
2856
2857 if (Args.hasFlag(options::OPT_fdebug_types_section,
2858 options::OPT_fno_debug_types_section, false)) {
2859 CmdArgs.push_back("-backend-option");
2860 CmdArgs.push_back("-generate-type-units");
2861 }
2862
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002863 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
2864
David L. Jonesf561aba2017-03-08 01:02:16 +00002865 bool UseSeparateSections = isUseSeparateSections(Triple);
2866
2867 if (Args.hasFlag(options::OPT_ffunction_sections,
2868 options::OPT_fno_function_sections, UseSeparateSections)) {
2869 CmdArgs.push_back("-ffunction-sections");
2870 }
2871
2872 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
2873 UseSeparateSections)) {
2874 CmdArgs.push_back("-fdata-sections");
2875 }
2876
2877 if (!Args.hasFlag(options::OPT_funique_section_names,
2878 options::OPT_fno_unique_section_names, true))
2879 CmdArgs.push_back("-fno-unique-section-names");
2880
2881 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2882
David L. Jonesf561aba2017-03-08 01:02:16 +00002883 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
2884
2885 // Add runtime flag for PS4 when PGO or Coverage are enabled.
2886 if (getToolChain().getTriple().isPS4CPU())
2887 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
2888
2889 // Pass options for controlling the default header search paths.
2890 if (Args.hasArg(options::OPT_nostdinc)) {
2891 CmdArgs.push_back("-nostdsysteminc");
2892 CmdArgs.push_back("-nobuiltininc");
2893 } else {
2894 if (Args.hasArg(options::OPT_nostdlibinc))
2895 CmdArgs.push_back("-nostdsysteminc");
2896 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2897 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2898 }
2899
2900 // Pass the path to compiler resource files.
2901 CmdArgs.push_back("-resource-dir");
2902 CmdArgs.push_back(D.ResourceDir.c_str());
2903
2904 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2905
2906 bool ARCMTEnabled = false;
2907 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2908 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2909 options::OPT_ccc_arcmt_modify,
2910 options::OPT_ccc_arcmt_migrate)) {
2911 ARCMTEnabled = true;
2912 switch (A->getOption().getID()) {
2913 default:
2914 llvm_unreachable("missed a case");
2915 case options::OPT_ccc_arcmt_check:
2916 CmdArgs.push_back("-arcmt-check");
2917 break;
2918 case options::OPT_ccc_arcmt_modify:
2919 CmdArgs.push_back("-arcmt-modify");
2920 break;
2921 case options::OPT_ccc_arcmt_migrate:
2922 CmdArgs.push_back("-arcmt-migrate");
2923 CmdArgs.push_back("-mt-migrate-directory");
2924 CmdArgs.push_back(A->getValue());
2925
2926 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2927 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2928 break;
2929 }
2930 }
2931 } else {
2932 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2933 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2934 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2935 }
2936
2937 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2938 if (ARCMTEnabled) {
2939 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
2940 << "-ccc-arcmt-migrate";
2941 }
2942 CmdArgs.push_back("-mt-migrate-directory");
2943 CmdArgs.push_back(A->getValue());
2944
2945 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2946 options::OPT_objcmt_migrate_subscripting,
2947 options::OPT_objcmt_migrate_property)) {
2948 // None specified, means enable them all.
2949 CmdArgs.push_back("-objcmt-migrate-literals");
2950 CmdArgs.push_back("-objcmt-migrate-subscripting");
2951 CmdArgs.push_back("-objcmt-migrate-property");
2952 } else {
2953 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2954 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2955 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2956 }
2957 } else {
2958 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2959 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2960 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2961 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2962 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2963 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2964 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2965 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2966 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2967 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2968 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2969 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2970 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2971 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2972 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2973 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2974 }
2975
2976 // Add preprocessing options like -I, -D, etc. if we are using the
2977 // preprocessor.
2978 //
2979 // FIXME: Support -fpreprocessed
2980 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2981 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
2982
2983 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2984 // that "The compiler can only warn and ignore the option if not recognized".
2985 // When building with ccache, it will pass -D options to clang even on
2986 // preprocessed inputs and configure concludes that -fPIC is not supported.
2987 Args.ClaimAllArgs(options::OPT_D);
2988
2989 // Manually translate -O4 to -O3; let clang reject others.
2990 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2991 if (A->getOption().matches(options::OPT_O4)) {
2992 CmdArgs.push_back("-O3");
2993 D.Diag(diag::warn_O4_is_O3);
2994 } else {
2995 A->render(Args, CmdArgs);
2996 }
2997 }
2998
2999 // Warn about ignored options to clang.
3000 for (const Arg *A :
3001 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3002 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3003 A->claim();
3004 }
3005
3006 claimNoWarnArgs(Args);
3007
3008 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3009
3010 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3011 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3012 CmdArgs.push_back("-pedantic");
3013 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3014 Args.AddLastArg(CmdArgs, options::OPT_w);
3015
3016 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3017 // (-ansi is equivalent to -std=c89 or -std=c++98).
3018 //
3019 // If a std is supplied, only add -trigraphs if it follows the
3020 // option.
3021 bool ImplyVCPPCXXVer = false;
3022 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3023 if (Std->getOption().matches(options::OPT_ansi))
3024 if (types::isCXX(InputType))
3025 CmdArgs.push_back("-std=c++98");
3026 else
3027 CmdArgs.push_back("-std=c89");
3028 else
3029 Std->render(Args, CmdArgs);
3030
3031 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3032 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3033 options::OPT_ftrigraphs,
3034 options::OPT_fno_trigraphs))
3035 if (A != Std)
3036 A->render(Args, CmdArgs);
3037 } else {
3038 // Honor -std-default.
3039 //
3040 // FIXME: Clang doesn't correctly handle -std= when the input language
3041 // doesn't match. For the time being just ignore this for C++ inputs;
3042 // eventually we want to do all the standard defaulting here instead of
3043 // splitting it between the driver and clang -cc1.
3044 if (!types::isCXX(InputType))
3045 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3046 /*Joined=*/true);
3047 else if (IsWindowsMSVC)
3048 ImplyVCPPCXXVer = true;
3049
3050 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3051 options::OPT_fno_trigraphs);
3052 }
3053
3054 // GCC's behavior for -Wwrite-strings is a bit strange:
3055 // * In C, this "warning flag" changes the types of string literals from
3056 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3057 // for the discarded qualifier.
3058 // * In C++, this is just a normal warning flag.
3059 //
3060 // Implementing this warning correctly in C is hard, so we follow GCC's
3061 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3062 // a non-const char* in C, rather than using this crude hack.
3063 if (!types::isCXX(InputType)) {
3064 // FIXME: This should behave just like a warning flag, and thus should also
3065 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3066 Arg *WriteStrings =
3067 Args.getLastArg(options::OPT_Wwrite_strings,
3068 options::OPT_Wno_write_strings, options::OPT_w);
3069 if (WriteStrings &&
3070 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3071 CmdArgs.push_back("-fconst-strings");
3072 }
3073
3074 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3075 // during C++ compilation, which it is by default. GCC keeps this define even
3076 // in the presence of '-w', match this behavior bug-for-bug.
3077 if (types::isCXX(InputType) &&
3078 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3079 true)) {
3080 CmdArgs.push_back("-fdeprecated-macro");
3081 }
3082
3083 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3084 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3085 if (Asm->getOption().matches(options::OPT_fasm))
3086 CmdArgs.push_back("-fgnu-keywords");
3087 else
3088 CmdArgs.push_back("-fno-gnu-keywords");
3089 }
3090
3091 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3092 CmdArgs.push_back("-fno-dwarf-directory-asm");
3093
3094 if (ShouldDisableAutolink(Args, getToolChain()))
3095 CmdArgs.push_back("-fno-autolink");
3096
3097 // Add in -fdebug-compilation-dir if necessary.
3098 addDebugCompDirArg(Args, CmdArgs);
3099
3100 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3101 StringRef Map = A->getValue();
3102 if (Map.find('=') == StringRef::npos)
3103 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3104 else
3105 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3106 A->claim();
3107 }
3108
3109 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3110 options::OPT_ftemplate_depth_EQ)) {
3111 CmdArgs.push_back("-ftemplate-depth");
3112 CmdArgs.push_back(A->getValue());
3113 }
3114
3115 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3116 CmdArgs.push_back("-foperator-arrow-depth");
3117 CmdArgs.push_back(A->getValue());
3118 }
3119
3120 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3121 CmdArgs.push_back("-fconstexpr-depth");
3122 CmdArgs.push_back(A->getValue());
3123 }
3124
3125 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3126 CmdArgs.push_back("-fconstexpr-steps");
3127 CmdArgs.push_back(A->getValue());
3128 }
3129
3130 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3131 CmdArgs.push_back("-fbracket-depth");
3132 CmdArgs.push_back(A->getValue());
3133 }
3134
3135 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3136 options::OPT_Wlarge_by_value_copy_def)) {
3137 if (A->getNumValues()) {
3138 StringRef bytes = A->getValue();
3139 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3140 } else
3141 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3142 }
3143
3144 if (Args.hasArg(options::OPT_relocatable_pch))
3145 CmdArgs.push_back("-relocatable-pch");
3146
3147 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3148 CmdArgs.push_back("-fconstant-string-class");
3149 CmdArgs.push_back(A->getValue());
3150 }
3151
3152 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3153 CmdArgs.push_back("-ftabstop");
3154 CmdArgs.push_back(A->getValue());
3155 }
3156
3157 CmdArgs.push_back("-ferror-limit");
3158 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3159 CmdArgs.push_back(A->getValue());
3160 else
3161 CmdArgs.push_back("19");
3162
3163 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3164 CmdArgs.push_back("-fmacro-backtrace-limit");
3165 CmdArgs.push_back(A->getValue());
3166 }
3167
3168 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3169 CmdArgs.push_back("-ftemplate-backtrace-limit");
3170 CmdArgs.push_back(A->getValue());
3171 }
3172
3173 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3174 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3175 CmdArgs.push_back(A->getValue());
3176 }
3177
3178 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3179 CmdArgs.push_back("-fspell-checking-limit");
3180 CmdArgs.push_back(A->getValue());
3181 }
3182
3183 // Pass -fmessage-length=.
3184 CmdArgs.push_back("-fmessage-length");
3185 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3186 CmdArgs.push_back(A->getValue());
3187 } else {
3188 // If -fmessage-length=N was not specified, determine whether this is a
3189 // terminal and, if so, implicitly define -fmessage-length appropriately.
3190 unsigned N = llvm::sys::Process::StandardErrColumns();
3191 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3192 }
3193
3194 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3195 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3196 options::OPT_fvisibility_ms_compat)) {
3197 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3198 CmdArgs.push_back("-fvisibility");
3199 CmdArgs.push_back(A->getValue());
3200 } else {
3201 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3202 CmdArgs.push_back("-fvisibility");
3203 CmdArgs.push_back("hidden");
3204 CmdArgs.push_back("-ftype-visibility");
3205 CmdArgs.push_back("default");
3206 }
3207 }
3208
3209 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3210
3211 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3212
3213 // -fhosted is default.
3214 bool IsHosted = true;
3215 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3216 KernelOrKext) {
3217 CmdArgs.push_back("-ffreestanding");
3218 IsHosted = false;
3219 }
3220
3221 // Forward -f (flag) options which we can pass directly.
3222 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3223 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3224 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3225 // Emulated TLS is enabled by default on Android, and can be enabled manually
3226 // with -femulated-tls.
3227 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
3228 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
3229 EmulatedTLSDefault))
3230 CmdArgs.push_back("-femulated-tls");
3231 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003232 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003233 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003234
David L. Jonesf561aba2017-03-08 01:02:16 +00003235 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3236 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3237
3238 // Forward flags for OpenMP. We don't do this if the current action is an
3239 // device offloading action other than OpenMP.
3240 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3241 options::OPT_fno_openmp, false) &&
3242 (JA.isDeviceOffloading(Action::OFK_None) ||
3243 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
3244 switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
3245 case Driver::OMPRT_OMP:
3246 case Driver::OMPRT_IOMP5:
3247 // Clang can generate useful OpenMP code for these two runtime libraries.
3248 CmdArgs.push_back("-fopenmp");
3249
3250 // If no option regarding the use of TLS in OpenMP codegeneration is
3251 // given, decide a default based on the target. Otherwise rely on the
3252 // options and pass the right information to the frontend.
3253 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3254 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3255 CmdArgs.push_back("-fnoopenmp-use-tls");
3256 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
3257 break;
3258 default:
3259 // By default, if Clang doesn't know how to generate useful OpenMP code
3260 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3261 // down to the actual compilation.
3262 // FIXME: It would be better to have a mode which *only* omits IR
3263 // generation based on the OpenMP support so that we get consistent
3264 // semantic analysis, etc.
3265 break;
3266 }
3267 }
3268
3269 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3270 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3271
Dean Michael Berris835832d2017-03-30 00:29:36 +00003272 const XRayArgs &XRay = getToolChain().getXRayArgs();
3273 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
3274
David L. Jonesf561aba2017-03-08 01:02:16 +00003275 if (getToolChain().SupportsProfiling())
3276 Args.AddLastArg(CmdArgs, options::OPT_pg);
3277
3278 if (getToolChain().SupportsProfiling())
3279 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
3280
3281 // -flax-vector-conversions is default.
3282 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3283 options::OPT_fno_lax_vector_conversions))
3284 CmdArgs.push_back("-fno-lax-vector-conversions");
3285
3286 if (Args.getLastArg(options::OPT_fapple_kext) ||
3287 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
3288 CmdArgs.push_back("-fapple-kext");
3289
3290 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3291 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3292 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3293 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3294 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3295
3296 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3297 CmdArgs.push_back("-ftrapv-handler");
3298 CmdArgs.push_back(A->getValue());
3299 }
3300
3301 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3302
3303 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3304 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3305 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3306 if (A->getOption().matches(options::OPT_fwrapv))
3307 CmdArgs.push_back("-fwrapv");
3308 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3309 options::OPT_fno_strict_overflow)) {
3310 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3311 CmdArgs.push_back("-fwrapv");
3312 }
3313
3314 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3315 options::OPT_fno_reroll_loops))
3316 if (A->getOption().matches(options::OPT_freroll_loops))
3317 CmdArgs.push_back("-freroll-loops");
3318
3319 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3320 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3321 options::OPT_fno_unroll_loops);
3322
3323 Args.AddLastArg(CmdArgs, options::OPT_pthread);
3324
3325 // -stack-protector=0 is default.
3326 unsigned StackProtectorLevel = 0;
3327 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3328 // doesn't even have a stack!
3329 if (!Triple.isNVPTX()) {
3330 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3331 options::OPT_fstack_protector_all,
3332 options::OPT_fstack_protector_strong,
3333 options::OPT_fstack_protector)) {
3334 if (A->getOption().matches(options::OPT_fstack_protector)) {
3335 StackProtectorLevel = std::max<unsigned>(
3336 LangOptions::SSPOn,
3337 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
3338 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3339 StackProtectorLevel = LangOptions::SSPStrong;
3340 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3341 StackProtectorLevel = LangOptions::SSPReq;
3342 } else {
3343 StackProtectorLevel =
3344 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3345 // Only use a default stack protector on Darwin in case -ffreestanding
3346 // is not specified.
3347 if (Triple.isOSDarwin() && !IsHosted)
3348 StackProtectorLevel = 0;
3349 }
3350 }
3351 if (StackProtectorLevel) {
3352 CmdArgs.push_back("-stack-protector");
3353 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3354 }
3355
3356 // --param ssp-buffer-size=
3357 for (const Arg *A : Args.filtered(options::OPT__param)) {
3358 StringRef Str(A->getValue());
3359 if (Str.startswith("ssp-buffer-size=")) {
3360 if (StackProtectorLevel) {
3361 CmdArgs.push_back("-stack-protector-buffer-size");
3362 // FIXME: Verify the argument is a valid integer.
3363 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3364 }
3365 A->claim();
3366 }
3367 }
3368
3369 // Translate -mstackrealign
3370 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3371 false))
3372 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3373
3374 if (Args.hasArg(options::OPT_mstack_alignment)) {
3375 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3376 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3377 }
3378
3379 if (Args.hasArg(options::OPT_mstack_probe_size)) {
3380 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
3381
3382 if (!Size.empty())
3383 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
3384 else
3385 CmdArgs.push_back("-mstack-probe-size=0");
3386 }
3387
3388 switch (getToolChain().getArch()) {
3389 case llvm::Triple::aarch64:
3390 case llvm::Triple::aarch64_be:
3391 case llvm::Triple::arm:
3392 case llvm::Triple::armeb:
3393 case llvm::Triple::thumb:
3394 case llvm::Triple::thumbeb:
3395 CmdArgs.push_back("-fallow-half-arguments-and-returns");
3396 break;
3397
3398 default:
3399 break;
3400 }
3401
3402 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3403 options::OPT_mno_restrict_it)) {
3404 if (A->getOption().matches(options::OPT_mrestrict_it)) {
3405 CmdArgs.push_back("-backend-option");
3406 CmdArgs.push_back("-arm-restrict-it");
3407 } else {
3408 CmdArgs.push_back("-backend-option");
3409 CmdArgs.push_back("-arm-no-restrict-it");
3410 }
3411 } else if (Triple.isOSWindows() &&
3412 (Triple.getArch() == llvm::Triple::arm ||
3413 Triple.getArch() == llvm::Triple::thumb)) {
3414 // Windows on ARM expects restricted IT blocks
3415 CmdArgs.push_back("-backend-option");
3416 CmdArgs.push_back("-arm-restrict-it");
3417 }
3418
3419 // Forward -cl options to -cc1
3420 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
3421 CmdArgs.push_back("-cl-opt-disable");
3422 }
3423 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
3424 CmdArgs.push_back("-cl-strict-aliasing");
3425 }
3426 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
3427 CmdArgs.push_back("-cl-single-precision-constant");
3428 }
3429 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
3430 CmdArgs.push_back("-cl-finite-math-only");
3431 }
3432 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
3433 CmdArgs.push_back("-cl-kernel-arg-info");
3434 }
3435 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
3436 CmdArgs.push_back("-cl-unsafe-math-optimizations");
3437 }
3438 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
3439 CmdArgs.push_back("-cl-fast-relaxed-math");
3440 }
3441 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
3442 CmdArgs.push_back("-cl-mad-enable");
3443 }
3444 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
3445 CmdArgs.push_back("-cl-no-signed-zeros");
3446 }
3447 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3448 std::string CLStdStr = "-cl-std=";
3449 CLStdStr += A->getValue();
3450 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3451 }
3452 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
3453 CmdArgs.push_back("-cl-denorms-are-zero");
3454 }
3455 if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
3456 CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
3457 }
3458
3459 // Forward -f options with positive and negative forms; we translate
3460 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00003461 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003462 StringRef fname = A->getValue();
3463 if (!llvm::sys::fs::exists(fname))
3464 D.Diag(diag::err_drv_no_such_file) << fname;
3465 else
3466 A->render(Args, CmdArgs);
3467 }
3468
3469 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3470 options::OPT_fno_debug_info_for_profiling, false))
3471 CmdArgs.push_back("-fdebug-info-for-profiling");
3472
3473 // -fbuiltin is default unless -mkernel is used.
3474 bool UseBuiltins =
3475 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3476 !Args.hasArg(options::OPT_mkernel));
3477 if (!UseBuiltins)
3478 CmdArgs.push_back("-fno-builtin");
3479
3480 // -ffreestanding implies -fno-builtin.
3481 if (Args.hasArg(options::OPT_ffreestanding))
3482 UseBuiltins = false;
3483
3484 // Process the -fno-builtin-* options.
3485 for (const auto &Arg : Args) {
3486 const Option &O = Arg->getOption();
3487 if (!O.matches(options::OPT_fno_builtin_))
3488 continue;
3489
3490 Arg->claim();
3491 // If -fno-builtin is specified, then there's no need to pass the option to
3492 // the frontend.
3493 if (!UseBuiltins)
3494 continue;
3495
3496 StringRef FuncName = Arg->getValue();
3497 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3498 }
3499
3500 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3501 options::OPT_fno_assume_sane_operator_new))
3502 CmdArgs.push_back("-fno-assume-sane-operator-new");
3503
3504 // -fblocks=0 is default.
3505 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3506 getToolChain().IsBlocksDefault()) ||
3507 (Args.hasArg(options::OPT_fgnu_runtime) &&
3508 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3509 !Args.hasArg(options::OPT_fno_blocks))) {
3510 CmdArgs.push_back("-fblocks");
3511
3512 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
3513 !getToolChain().hasBlocksRuntime())
3514 CmdArgs.push_back("-fblocks-runtime-optional");
3515 }
3516
3517 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
3518 false) &&
3519 types::isCXX(InputType)) {
3520 CmdArgs.push_back("-fcoroutines-ts");
3521 }
3522
3523 // -fmodules enables the use of precompiled modules (off by default).
3524 // Users can pass -fno-cxx-modules to turn off modules support for
3525 // C++/Objective-C++ programs.
3526 bool HaveClangModules = false;
3527 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3528 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3529 options::OPT_fno_cxx_modules, true);
3530 if (AllowedInCXX || !types::isCXX(InputType)) {
3531 CmdArgs.push_back("-fmodules");
3532 HaveClangModules = true;
3533 }
3534 }
3535
3536 bool HaveAnyModules = HaveClangModules;
3537 if (Args.hasArg(options::OPT_fmodules_ts)) {
3538 CmdArgs.push_back("-fmodules-ts");
3539 HaveAnyModules = true;
3540 }
3541
3542 // -fmodule-maps enables implicit reading of module map files. By default,
3543 // this is enabled if we are using Clang's flavor of precompiled modules.
3544 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3545 options::OPT_fno_implicit_module_maps, HaveClangModules)) {
3546 CmdArgs.push_back("-fimplicit-module-maps");
3547 }
3548
3549 // -fmodules-decluse checks that modules used are declared so (off by
3550 // default).
3551 if (Args.hasFlag(options::OPT_fmodules_decluse,
3552 options::OPT_fno_modules_decluse, false)) {
3553 CmdArgs.push_back("-fmodules-decluse");
3554 }
3555
3556 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3557 // all #included headers are part of modules.
3558 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3559 options::OPT_fno_modules_strict_decluse, false)) {
3560 CmdArgs.push_back("-fmodules-strict-decluse");
3561 }
3562
3563 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3564 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3565 options::OPT_fno_implicit_modules, HaveClangModules)) {
3566 if (HaveAnyModules)
3567 CmdArgs.push_back("-fno-implicit-modules");
3568 } else if (HaveAnyModules) {
3569 // -fmodule-cache-path specifies where our implicitly-built module files
3570 // should be written.
3571 SmallString<128> Path;
3572 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3573 Path = A->getValue();
3574 if (C.isForDiagnostics()) {
3575 // When generating crash reports, we want to emit the modules along with
3576 // the reproduction sources, so we ignore any provided module path.
3577 Path = Output.getFilename();
3578 llvm::sys::path::replace_extension(Path, ".cache");
3579 llvm::sys::path::append(Path, "modules");
3580 } else if (Path.empty()) {
3581 // No module path was provided: use the default.
3582 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
3583 llvm::sys::path::append(Path, "org.llvm.clang.");
3584 appendUserToPath(Path);
3585 llvm::sys::path::append(Path, "ModuleCache");
3586 }
3587 const char Arg[] = "-fmodules-cache-path=";
3588 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3589 CmdArgs.push_back(Args.MakeArgString(Path));
3590 }
3591
3592 if (HaveAnyModules) {
3593 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3594 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path))
3595 CmdArgs.push_back(Args.MakeArgString(
3596 std::string("-fprebuilt-module-path=") + A->getValue()));
3597 }
3598
3599 // -fmodule-name specifies the module that is currently being built (or
3600 // used for header checking by -fmodule-maps).
3601 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3602
3603 // -fmodule-map-file can be used to specify files containing module
3604 // definitions.
3605 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3606
3607 // -fbuiltin-module-map can be used to load the clang
3608 // builtin headers modulemap file.
3609 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3610 SmallString<128> BuiltinModuleMap(getToolChain().getDriver().ResourceDir);
3611 llvm::sys::path::append(BuiltinModuleMap, "include");
3612 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3613 if (llvm::sys::fs::exists(BuiltinModuleMap)) {
3614 CmdArgs.push_back(Args.MakeArgString("-fmodule-map-file=" +
3615 BuiltinModuleMap));
3616 }
3617 }
3618
3619 // -fmodule-file can be used to specify files containing precompiled modules.
3620 if (HaveAnyModules)
3621 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3622 else
3623 Args.ClaimAllArgs(options::OPT_fmodule_file);
3624
3625 // When building modules and generating crashdumps, we need to dump a module
3626 // dependency VFS alongside the output.
3627 if (HaveClangModules && C.isForDiagnostics()) {
3628 SmallString<128> VFSDir(Output.getFilename());
3629 llvm::sys::path::replace_extension(VFSDir, ".cache");
3630 // Add the cache directory as a temp so the crash diagnostics pick it up.
3631 C.addTempFile(Args.MakeArgString(VFSDir));
3632
3633 llvm::sys::path::append(VFSDir, "vfs");
3634 CmdArgs.push_back("-module-dependency-dir");
3635 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3636 }
3637
3638 if (HaveClangModules)
3639 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3640
3641 // Pass through all -fmodules-ignore-macro arguments.
3642 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3643 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3644 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3645
3646 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3647
3648 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3649 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3650 D.Diag(diag::err_drv_argument_not_allowed_with)
3651 << A->getAsString(Args) << "-fbuild-session-timestamp";
3652
3653 llvm::sys::fs::file_status Status;
3654 if (llvm::sys::fs::status(A->getValue(), Status))
3655 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3656 CmdArgs.push_back(
3657 Args.MakeArgString("-fbuild-session-timestamp=" +
3658 Twine((uint64_t)Status.getLastModificationTime()
3659 .time_since_epoch()
3660 .count())));
3661 }
3662
3663 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3664 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3665 options::OPT_fbuild_session_file))
3666 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3667
3668 Args.AddLastArg(CmdArgs,
3669 options::OPT_fmodules_validate_once_per_build_session);
3670 }
3671
3672 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
3673 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3674
3675 // -faccess-control is default.
3676 if (Args.hasFlag(options::OPT_fno_access_control,
3677 options::OPT_faccess_control, false))
3678 CmdArgs.push_back("-fno-access-control");
3679
3680 // -felide-constructors is the default.
3681 if (Args.hasFlag(options::OPT_fno_elide_constructors,
3682 options::OPT_felide_constructors, false))
3683 CmdArgs.push_back("-fno-elide-constructors");
3684
3685 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
3686
3687 if (KernelOrKext || (types::isCXX(InputType) &&
3688 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
3689 RTTIMode == ToolChain::RM_DisabledImplicitly)))
3690 CmdArgs.push_back("-fno-rtti");
3691
3692 // -fshort-enums=0 is default for all architectures except Hexagon.
3693 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
3694 getToolChain().getArch() == llvm::Triple::hexagon))
3695 CmdArgs.push_back("-fshort-enums");
3696
3697 // -fsigned-char is default.
3698 if (Arg *A = Args.getLastArg(
3699 options::OPT_fsigned_char, options::OPT_fno_signed_char,
3700 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
3701 if (A->getOption().matches(options::OPT_funsigned_char) ||
3702 A->getOption().matches(options::OPT_fno_signed_char)) {
3703 CmdArgs.push_back("-fno-signed-char");
3704 }
3705 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
3706 CmdArgs.push_back("-fno-signed-char");
3707 }
3708
3709 // -fuse-cxa-atexit is default.
3710 if (!Args.hasFlag(
3711 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
3712 !IsWindowsCygnus && !IsWindowsGNU &&
3713 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
3714 getToolChain().getArch() != llvm::Triple::hexagon &&
3715 getToolChain().getArch() != llvm::Triple::xcore &&
3716 ((getToolChain().getTriple().getVendor() !=
3717 llvm::Triple::MipsTechnologies) ||
3718 getToolChain().getTriple().hasEnvironment())) ||
3719 KernelOrKext)
3720 CmdArgs.push_back("-fno-use-cxa-atexit");
3721
3722 // -fms-extensions=0 is default.
3723 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3724 IsWindowsMSVC))
3725 CmdArgs.push_back("-fms-extensions");
3726
3727 // -fno-use-line-directives is default.
3728 if (Args.hasFlag(options::OPT_fuse_line_directives,
3729 options::OPT_fno_use_line_directives, false))
3730 CmdArgs.push_back("-fuse-line-directives");
3731
3732 // -fms-compatibility=0 is default.
3733 if (Args.hasFlag(options::OPT_fms_compatibility,
3734 options::OPT_fno_ms_compatibility,
3735 (IsWindowsMSVC &&
3736 Args.hasFlag(options::OPT_fms_extensions,
3737 options::OPT_fno_ms_extensions, true))))
3738 CmdArgs.push_back("-fms-compatibility");
3739
3740 VersionTuple MSVT =
3741 getToolChain().computeMSVCVersion(&getToolChain().getDriver(), Args);
3742 if (!MSVT.empty())
3743 CmdArgs.push_back(
3744 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
3745
3746 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
3747 if (ImplyVCPPCXXVer) {
3748 StringRef LanguageStandard;
3749 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
3750 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
3751 .Case("c++14", "-std=c++14")
3752 .Case("c++latest", "-std=c++1z")
3753 .Default("");
3754 if (LanguageStandard.empty())
3755 D.Diag(clang::diag::warn_drv_unused_argument)
3756 << StdArg->getAsString(Args);
3757 }
3758
3759 if (LanguageStandard.empty()) {
3760 if (IsMSVC2015Compatible)
3761 LanguageStandard = "-std=c++14";
3762 else
3763 LanguageStandard = "-std=c++11";
3764 }
3765
3766 CmdArgs.push_back(LanguageStandard.data());
3767 }
3768
3769 // -fno-borland-extensions is default.
3770 if (Args.hasFlag(options::OPT_fborland_extensions,
3771 options::OPT_fno_borland_extensions, false))
3772 CmdArgs.push_back("-fborland-extensions");
3773
3774 // -fno-declspec is default, except for PS4.
3775 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
3776 getToolChain().getTriple().isPS4()))
3777 CmdArgs.push_back("-fdeclspec");
3778 else if (Args.hasArg(options::OPT_fno_declspec))
3779 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
3780
3781 // -fthreadsafe-static is default, except for MSVC compatibility versions less
3782 // than 19.
3783 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3784 options::OPT_fno_threadsafe_statics,
3785 !IsWindowsMSVC || IsMSVC2015Compatible))
3786 CmdArgs.push_back("-fno-threadsafe-statics");
3787
3788 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
3789 // needs it.
3790 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
3791 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
3792 CmdArgs.push_back("-fdelayed-template-parsing");
3793
3794 // -fgnu-keywords default varies depending on language; only pass if
3795 // specified.
3796 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3797 options::OPT_fno_gnu_keywords))
3798 A->render(Args, CmdArgs);
3799
3800 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
3801 false))
3802 CmdArgs.push_back("-fgnu89-inline");
3803
3804 if (Args.hasArg(options::OPT_fno_inline))
3805 CmdArgs.push_back("-fno-inline");
3806
3807 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
3808 options::OPT_finline_hint_functions,
3809 options::OPT_fno_inline_functions))
3810 InlineArg->render(Args, CmdArgs);
3811
3812 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
3813 options::OPT_fno_experimental_new_pass_manager);
3814
3815 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3816
3817 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3818 // legacy is the default. Except for deployment target of 10.5,
3819 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
3820 // gets ignored silently.
3821 if (objcRuntime.isNonFragile()) {
3822 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3823 options::OPT_fno_objc_legacy_dispatch,
3824 objcRuntime.isLegacyDispatchDefaultForArch(
3825 getToolChain().getArch()))) {
3826 if (getToolChain().UseObjCMixedDispatch())
3827 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3828 else
3829 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3830 }
3831 }
3832
3833 // When ObjectiveC legacy runtime is in effect on MacOSX,
3834 // turn on the option to do Array/Dictionary subscripting
3835 // by default.
3836 if (getToolChain().getArch() == llvm::Triple::x86 &&
3837 getToolChain().getTriple().isMacOSX() &&
3838 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
3839 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
3840 objcRuntime.isNeXTFamily())
3841 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3842
3843 // -fencode-extended-block-signature=1 is default.
3844 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3845 CmdArgs.push_back("-fencode-extended-block-signature");
3846 }
3847
3848 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3849 // NOTE: This logic is duplicated in ToolChains.cpp.
3850 bool ARC = isObjCAutoRefCount(Args);
3851 if (ARC) {
3852 getToolChain().CheckObjCARC();
3853
3854 CmdArgs.push_back("-fobjc-arc");
3855
3856 // FIXME: It seems like this entire block, and several around it should be
3857 // wrapped in isObjC, but for now we just use it here as this is where it
3858 // was being used previously.
3859 if (types::isCXX(InputType) && types::isObjC(InputType)) {
3860 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3861 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3862 else
3863 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3864 }
3865
3866 // Allow the user to enable full exceptions code emission.
3867 // We define off for Objective-CC, on for Objective-C++.
3868 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3869 options::OPT_fno_objc_arc_exceptions,
3870 /*default*/ types::isCXX(InputType)))
3871 CmdArgs.push_back("-fobjc-arc-exceptions");
3872 }
3873
3874 // Silence warning for full exception code emission options when explicitly
3875 // set to use no ARC.
3876 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3877 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3878 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3879 }
3880
3881 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3882 // rewriter.
3883 if (rewriteKind != RK_None)
3884 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3885
3886 // Pass down -fobjc-weak or -fno-objc-weak if present.
3887 if (types::isObjC(InputType)) {
3888 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
3889 options::OPT_fno_objc_weak);
3890 if (!WeakArg) {
3891 // nothing to do
3892 } else if (!objcRuntime.allowsWeak()) {
3893 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3894 D.Diag(diag::err_objc_weak_unsupported);
3895 } else {
3896 WeakArg->render(Args, CmdArgs);
3897 }
3898 }
3899
3900 if (Args.hasFlag(options::OPT_fapplication_extension,
3901 options::OPT_fno_application_extension, false))
3902 CmdArgs.push_back("-fapplication-extension");
3903
3904 // Handle GCC-style exception args.
3905 if (!C.getDriver().IsCLMode())
3906 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
3907 CmdArgs);
3908
3909 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
3910 getToolChain().UseSjLjExceptions(Args))
3911 CmdArgs.push_back("-fsjlj-exceptions");
3912
3913 // C++ "sane" operator new.
3914 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3915 options::OPT_fno_assume_sane_operator_new))
3916 CmdArgs.push_back("-fno-assume-sane-operator-new");
3917
3918 // -frelaxed-template-template-args is off by default, as it is a severe
3919 // breaking change until a corresponding change to template partial ordering
3920 // is provided.
3921 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
3922 options::OPT_fno_relaxed_template_template_args, false))
3923 CmdArgs.push_back("-frelaxed-template-template-args");
3924
3925 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
3926 // most platforms.
3927 if (Args.hasFlag(options::OPT_fsized_deallocation,
3928 options::OPT_fno_sized_deallocation, false))
3929 CmdArgs.push_back("-fsized-deallocation");
3930
3931 // -faligned-allocation is on by default in C++17 onwards and otherwise off
3932 // by default.
3933 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
3934 options::OPT_fno_aligned_allocation,
3935 options::OPT_faligned_new_EQ)) {
3936 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
3937 CmdArgs.push_back("-fno-aligned-allocation");
3938 else
3939 CmdArgs.push_back("-faligned-allocation");
3940 }
3941
3942 // The default new alignment can be specified using a dedicated option or via
3943 // a GCC-compatible option that also turns on aligned allocation.
3944 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
3945 options::OPT_faligned_new_EQ))
3946 CmdArgs.push_back(
3947 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
3948
3949 // -fconstant-cfstrings is default, and may be subject to argument translation
3950 // on Darwin.
3951 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
3952 options::OPT_fno_constant_cfstrings) ||
3953 !Args.hasFlag(options::OPT_mconstant_cfstrings,
3954 options::OPT_mno_constant_cfstrings))
3955 CmdArgs.push_back("-fno-constant-cfstrings");
3956
3957 // -fshort-wchar default varies depending on platform; only
3958 // pass if specified.
3959 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3960 options::OPT_fno_short_wchar))
3961 A->render(Args, CmdArgs);
3962
3963 // -fno-pascal-strings is default, only pass non-default.
3964 if (Args.hasFlag(options::OPT_fpascal_strings,
3965 options::OPT_fno_pascal_strings, false))
3966 CmdArgs.push_back("-fpascal-strings");
3967
3968 // Honor -fpack-struct= and -fpack-struct, if given. Note that
3969 // -fno-pack-struct doesn't apply to -fpack-struct=.
3970 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
3971 std::string PackStructStr = "-fpack-struct=";
3972 PackStructStr += A->getValue();
3973 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
3974 } else if (Args.hasFlag(options::OPT_fpack_struct,
3975 options::OPT_fno_pack_struct, false)) {
3976 CmdArgs.push_back("-fpack-struct=1");
3977 }
3978
3979 // Handle -fmax-type-align=N and -fno-type-align
3980 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
3981 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
3982 if (!SkipMaxTypeAlign) {
3983 std::string MaxTypeAlignStr = "-fmax-type-align=";
3984 MaxTypeAlignStr += A->getValue();
3985 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
3986 }
3987 } else if (getToolChain().getTriple().isOSDarwin()) {
3988 if (!SkipMaxTypeAlign) {
3989 std::string MaxTypeAlignStr = "-fmax-type-align=16";
3990 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
3991 }
3992 }
3993
3994 // -fcommon is the default unless compiling kernel code or the target says so
3995 bool NoCommonDefault =
3996 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
3997 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
3998 !NoCommonDefault))
3999 CmdArgs.push_back("-fno-common");
4000
4001 // -fsigned-bitfields is default, and clang doesn't yet support
4002 // -funsigned-bitfields.
4003 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4004 options::OPT_funsigned_bitfields))
4005 D.Diag(diag::warn_drv_clang_unsupported)
4006 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4007
4008 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4009 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4010 D.Diag(diag::err_drv_clang_unsupported)
4011 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4012
4013 // -finput_charset=UTF-8 is default. Reject others
4014 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4015 StringRef value = inputCharset->getValue();
4016 if (!value.equals_lower("utf-8"))
4017 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4018 << value;
4019 }
4020
4021 // -fexec_charset=UTF-8 is default. Reject others
4022 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4023 StringRef value = execCharset->getValue();
4024 if (!value.equals_lower("utf-8"))
4025 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4026 << value;
4027 }
4028
Reid Klecknerca77dd52017-05-31 17:37:49 +00004029 bool CaretDefault = true;
4030 bool ColumnDefault = true;
4031 if (Arg *DiagArg = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4032 options::OPT__SLASH_diagnostics_column,
4033 options::OPT__SLASH_diagnostics_caret)) {
4034 switch (DiagArg->getOption().getID()) {
4035 case options::OPT__SLASH_diagnostics_caret:
4036 CaretDefault = true;
4037 ColumnDefault = true;
4038 break;
4039 case options::OPT__SLASH_diagnostics_column:
4040 CaretDefault = false;
4041 ColumnDefault = true;
4042 break;
4043 case options::OPT__SLASH_diagnostics_classic:
4044 CaretDefault = false;
4045 ColumnDefault = false;
4046 break;
4047 }
4048 }
4049
David L. Jonesf561aba2017-03-08 01:02:16 +00004050 // -fcaret-diagnostics is default.
4051 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
Reid Klecknerca77dd52017-05-31 17:37:49 +00004052 options::OPT_fno_caret_diagnostics, CaretDefault))
David L. Jonesf561aba2017-03-08 01:02:16 +00004053 CmdArgs.push_back("-fno-caret-diagnostics");
4054
4055 // -fdiagnostics-fixit-info is default, only pass non-default.
4056 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4057 options::OPT_fno_diagnostics_fixit_info))
4058 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4059
4060 // Enable -fdiagnostics-show-option by default.
4061 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4062 options::OPT_fno_diagnostics_show_option))
4063 CmdArgs.push_back("-fdiagnostics-show-option");
4064
4065 if (const Arg *A =
4066 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4067 CmdArgs.push_back("-fdiagnostics-show-category");
4068 CmdArgs.push_back(A->getValue());
4069 }
4070
4071 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
4072 options::OPT_fno_diagnostics_show_hotness, false))
4073 CmdArgs.push_back("-fdiagnostics-show-hotness");
4074
4075 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4076 CmdArgs.push_back("-fdiagnostics-format");
4077 CmdArgs.push_back(A->getValue());
4078 }
4079
4080 if (Arg *A = Args.getLastArg(
4081 options::OPT_fdiagnostics_show_note_include_stack,
4082 options::OPT_fno_diagnostics_show_note_include_stack)) {
4083 if (A->getOption().matches(
4084 options::OPT_fdiagnostics_show_note_include_stack))
4085 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4086 else
4087 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4088 }
4089
4090 // Color diagnostics are parsed by the driver directly from argv
4091 // and later re-parsed to construct this job; claim any possible
4092 // color diagnostic here to avoid warn_drv_unused_argument and
4093 // diagnose bad OPT_fdiagnostics_color_EQ values.
4094 for (Arg *A : Args) {
4095 const Option &O = A->getOption();
4096 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4097 !O.matches(options::OPT_fdiagnostics_color) &&
4098 !O.matches(options::OPT_fno_color_diagnostics) &&
4099 !O.matches(options::OPT_fno_diagnostics_color) &&
4100 !O.matches(options::OPT_fdiagnostics_color_EQ))
4101 continue;
4102 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
4103 StringRef Value(A->getValue());
4104 if (Value != "always" && Value != "never" && Value != "auto")
4105 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4106 << ("-fdiagnostics-color=" + Value).str();
4107 }
4108 A->claim();
4109 }
4110 if (D.getDiags().getDiagnosticOptions().ShowColors)
4111 CmdArgs.push_back("-fcolor-diagnostics");
4112
4113 if (Args.hasArg(options::OPT_fansi_escape_codes))
4114 CmdArgs.push_back("-fansi-escape-codes");
4115
4116 if (!Args.hasFlag(options::OPT_fshow_source_location,
4117 options::OPT_fno_show_source_location))
4118 CmdArgs.push_back("-fno-show-source-location");
4119
4120 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4121 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4122
4123 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
Reid Klecknerca77dd52017-05-31 17:37:49 +00004124 ColumnDefault))
David L. Jonesf561aba2017-03-08 01:02:16 +00004125 CmdArgs.push_back("-fno-show-column");
4126
4127 if (!Args.hasFlag(options::OPT_fspell_checking,
4128 options::OPT_fno_spell_checking))
4129 CmdArgs.push_back("-fno-spell-checking");
4130
4131 // -fno-asm-blocks is default.
4132 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4133 false))
4134 CmdArgs.push_back("-fasm-blocks");
4135
4136 // -fgnu-inline-asm is default.
4137 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4138 options::OPT_fno_gnu_inline_asm, true))
4139 CmdArgs.push_back("-fno-gnu-inline-asm");
4140
4141 // Enable vectorization per default according to the optimization level
4142 // selected. For optimization levels that want vectorization we use the alias
4143 // option to simplify the hasFlag logic.
4144 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4145 OptSpecifier VectorizeAliasOption =
4146 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4147 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4148 options::OPT_fno_vectorize, EnableVec))
4149 CmdArgs.push_back("-vectorize-loops");
4150
4151 // -fslp-vectorize is enabled based on the optimization level selected.
4152 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4153 OptSpecifier SLPVectAliasOption =
4154 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4155 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4156 options::OPT_fno_slp_vectorize, EnableSLPVec))
4157 CmdArgs.push_back("-vectorize-slp");
4158
4159 // -fno-slp-vectorize-aggressive is default.
4160 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4161 options::OPT_fno_slp_vectorize_aggressive, false))
4162 CmdArgs.push_back("-vectorize-slp-aggressive");
4163
4164 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4165 A->render(Args, CmdArgs);
4166
4167 if (Arg *A = Args.getLastArg(
4168 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4169 A->render(Args, CmdArgs);
4170
4171 // -fdollars-in-identifiers default varies depending on platform and
4172 // language; only pass if specified.
4173 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4174 options::OPT_fno_dollars_in_identifiers)) {
4175 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4176 CmdArgs.push_back("-fdollars-in-identifiers");
4177 else
4178 CmdArgs.push_back("-fno-dollars-in-identifiers");
4179 }
4180
4181 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4182 // practical purposes.
4183 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4184 options::OPT_fno_unit_at_a_time)) {
4185 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4186 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4187 }
4188
4189 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4190 options::OPT_fno_apple_pragma_pack, false))
4191 CmdArgs.push_back("-fapple-pragma-pack");
4192
4193 // le32-specific flags:
4194 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4195 // by default.
4196 if (getToolChain().getArch() == llvm::Triple::le32) {
4197 CmdArgs.push_back("-fno-math-builtin");
4198 }
4199
4200 if (Args.hasFlag(options::OPT_fsave_optimization_record,
4201 options::OPT_fno_save_optimization_record, false)) {
4202 CmdArgs.push_back("-opt-record-file");
4203
4204 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4205 if (A) {
4206 CmdArgs.push_back(A->getValue());
4207 } else {
4208 SmallString<128> F;
4209 if (Output.isFilename() && (Args.hasArg(options::OPT_c) ||
4210 Args.hasArg(options::OPT_S))) {
4211 F = Output.getFilename();
4212 } else {
4213 // Use the input filename.
4214 F = llvm::sys::path::stem(Input.getBaseInput());
4215
4216 // If we're compiling for an offload architecture (i.e. a CUDA device),
4217 // we need to make the file name for the device compilation different
4218 // from the host compilation.
4219 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4220 !JA.isDeviceOffloading(Action::OFK_Host)) {
4221 llvm::sys::path::replace_extension(F, "");
4222 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4223 Triple.normalize());
4224 F += "-";
4225 F += JA.getOffloadingArch();
4226 }
4227 }
4228
4229 llvm::sys::path::replace_extension(F, "opt.yaml");
4230 CmdArgs.push_back(Args.MakeArgString(F));
4231 }
4232 }
4233
4234// Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4235//
4236// FIXME: Now that PR4941 has been fixed this can be enabled.
4237#if 0
4238 if (getToolChain().getTriple().isOSDarwin() &&
4239 (getToolChain().getArch() == llvm::Triple::arm ||
4240 getToolChain().getArch() == llvm::Triple::thumb)) {
4241 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4242 CmdArgs.push_back("-fno-builtin-strcat");
4243 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4244 CmdArgs.push_back("-fno-builtin-strcpy");
4245 }
4246#endif
4247
Richard Smith86a3ef52017-06-09 21:24:02 +00004248 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4249 options::OPT_fno_rewrite_imports, false);
4250 if (RewriteImports)
4251 CmdArgs.push_back("-frewrite-imports");
4252
David L. Jonesf561aba2017-03-08 01:02:16 +00004253 // Enable rewrite includes if the user's asked for it or if we're generating
4254 // diagnostics.
4255 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4256 // nice to enable this when doing a crashdump for modules as well.
4257 if (Args.hasFlag(options::OPT_frewrite_includes,
4258 options::OPT_fno_rewrite_includes, false) ||
Richard Smith86a3ef52017-06-09 21:24:02 +00004259 (C.isForDiagnostics() && (RewriteImports || !HaveAnyModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004260 CmdArgs.push_back("-frewrite-includes");
4261
4262 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4263 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4264 options::OPT_traditional_cpp)) {
4265 if (isa<PreprocessJobAction>(JA))
4266 CmdArgs.push_back("-traditional-cpp");
4267 else
4268 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4269 }
4270
4271 Args.AddLastArg(CmdArgs, options::OPT_dM);
4272 Args.AddLastArg(CmdArgs, options::OPT_dD);
4273
4274 // Handle serialized diagnostics.
4275 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4276 CmdArgs.push_back("-serialize-diagnostic-file");
4277 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4278 }
4279
4280 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4281 CmdArgs.push_back("-fretain-comments-from-system-headers");
4282
4283 // Forward -fcomment-block-commands to -cc1.
4284 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4285 // Forward -fparse-all-comments to -cc1.
4286 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4287
4288 // Turn -fplugin=name.so into -load name.so
4289 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4290 CmdArgs.push_back("-load");
4291 CmdArgs.push_back(A->getValue());
4292 A->claim();
4293 }
4294
4295 // Setup statistics file output.
4296 if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
4297 StringRef SaveStats = A->getValue();
4298
4299 SmallString<128> StatsFile;
4300 bool DoSaveStats = false;
4301 if (SaveStats == "obj") {
4302 if (Output.isFilename()) {
4303 StatsFile.assign(Output.getFilename());
4304 llvm::sys::path::remove_filename(StatsFile);
4305 }
4306 DoSaveStats = true;
4307 } else if (SaveStats == "cwd") {
4308 DoSaveStats = true;
4309 } else {
4310 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
4311 }
4312
4313 if (DoSaveStats) {
4314 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
4315 llvm::sys::path::append(StatsFile, BaseName);
4316 llvm::sys::path::replace_extension(StatsFile, "stats");
4317 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
4318 StatsFile));
4319 }
4320 }
4321
4322 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4323 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004324 // -finclude-default-header flag is for preprocessor,
4325 // do not pass it to other cc1 commands when save-temps is enabled
4326 if (C.getDriver().isSaveTempsEnabled() &&
4327 !isa<PreprocessJobAction>(JA)) {
4328 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4329 Arg->claim();
4330 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4331 CmdArgs.push_back(Arg->getValue());
4332 }
4333 }
4334 else {
4335 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4336 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004337 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4338 A->claim();
4339
4340 // We translate this by hand to the -cc1 argument, since nightly test uses
4341 // it and developers have been trained to spell it with -mllvm. Both
4342 // spellings are now deprecated and should be removed.
4343 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4344 CmdArgs.push_back("-disable-llvm-optzns");
4345 } else {
4346 A->render(Args, CmdArgs);
4347 }
4348 }
4349
4350 // With -save-temps, we want to save the unoptimized bitcode output from the
4351 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4352 // by the frontend.
4353 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4354 // has slightly different breakdown between stages.
4355 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4356 // pristine IR generated by the frontend. Ideally, a new compile action should
4357 // be added so both IR can be captured.
4358 if (C.getDriver().isSaveTempsEnabled() &&
4359 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4360 isa<CompileJobAction>(JA))
4361 CmdArgs.push_back("-disable-llvm-passes");
4362
4363 if (Output.getType() == types::TY_Dependencies) {
4364 // Handled with other dependency code.
4365 } else if (Output.isFilename()) {
4366 CmdArgs.push_back("-o");
4367 CmdArgs.push_back(Output.getFilename());
4368 } else {
4369 assert(Output.isNothing() && "Invalid output.");
4370 }
4371
4372 addDashXForInput(Args, Input, CmdArgs);
4373
4374 if (Input.isFilename())
4375 CmdArgs.push_back(Input.getFilename());
4376 else
4377 Input.getInputArg().renderAsInput(Args, CmdArgs);
4378
4379 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4380
4381 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4382
4383 // Optionally embed the -cc1 level arguments into the debug info, for build
4384 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004385 // Also record command line arguments into the debug info if
4386 // -grecord-gcc-switches options is set on.
4387 // By default, -gno-record-gcc-switches is set on and no recording.
4388 if (getToolChain().UseDwarfDebugFlags() ||
4389 Args.hasFlag(options::OPT_grecord_gcc_switches,
4390 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004391 ArgStringList OriginalArgs;
4392 for (const auto &Arg : Args)
4393 Arg->render(Args, OriginalArgs);
4394
4395 SmallString<256> Flags;
4396 Flags += Exec;
4397 for (const char *OriginalArg : OriginalArgs) {
4398 SmallString<128> EscapedArg;
4399 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4400 Flags += " ";
4401 Flags += EscapedArg;
4402 }
4403 CmdArgs.push_back("-dwarf-debug-flags");
4404 CmdArgs.push_back(Args.MakeArgString(Flags));
4405 }
4406
4407 // Add the split debug info name to the command lines here so we
4408 // can propagate it to the backend.
4409 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
4410 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4411 isa<BackendJobAction>(JA));
4412 const char *SplitDwarfOut;
4413 if (SplitDwarf) {
4414 CmdArgs.push_back("-split-dwarf-file");
4415 SplitDwarfOut = SplitDebugName(Args, Input);
4416 CmdArgs.push_back(SplitDwarfOut);
4417 }
4418
4419 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4420 // Include them with -fcuda-include-gpubinary.
4421 if (IsCuda && Inputs.size() > 1)
4422 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
4423 CmdArgs.push_back("-fcuda-include-gpubinary");
4424 CmdArgs.push_back(I->getFilename());
4425 }
4426
4427 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4428 // to specify the result of the compile phase on the host, so the meaningful
4429 // device declarations can be identified. Also, -fopenmp-is-device is passed
4430 // along to tell the frontend that it is generating code for a device, so that
4431 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004432 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004433 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004434 if (Inputs.size() == 2) {
4435 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4436 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4437 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004438 }
4439
4440 // For all the host OpenMP offloading compile jobs we need to pass the targets
4441 // information using -fopenmp-targets= option.
4442 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4443 SmallString<128> TargetInfo("-fopenmp-targets=");
4444
4445 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4446 assert(Tgts && Tgts->getNumValues() &&
4447 "OpenMP offloading has to have targets specified.");
4448 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4449 if (i)
4450 TargetInfo += ',';
4451 // We need to get the string from the triple because it may be not exactly
4452 // the same as the one we get directly from the arguments.
4453 llvm::Triple T(Tgts->getValue(i));
4454 TargetInfo += T.getTriple();
4455 }
4456 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4457 }
4458
4459 bool WholeProgramVTables =
4460 Args.hasFlag(options::OPT_fwhole_program_vtables,
4461 options::OPT_fno_whole_program_vtables, false);
4462 if (WholeProgramVTables) {
4463 if (!D.isUsingLTO())
4464 D.Diag(diag::err_drv_argument_only_allowed_with)
4465 << "-fwhole-program-vtables"
4466 << "-flto";
4467 CmdArgs.push_back("-fwhole-program-vtables");
4468 }
4469
4470 // Finally add the compile command to the compilation.
4471 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4472 Output.getType() == types::TY_Object &&
4473 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4474 auto CLCommand =
4475 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4476 C.addCommand(llvm::make_unique<FallbackCommand>(
4477 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4478 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4479 isa<PrecompileJobAction>(JA)) {
4480 // In /fallback builds, run the main compilation even if the pch generation
4481 // fails, so that the main compilation's fallback to cl.exe runs.
4482 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4483 CmdArgs, Inputs));
4484 } else {
4485 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4486 }
4487
4488 // Handle the debug info splitting at object creation time if we're
4489 // creating an object.
4490 // TODO: Currently only works on linux with newer objcopy.
4491 if (SplitDwarf && Output.getType() == types::TY_Object)
4492 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4493
4494 if (Arg *A = Args.getLastArg(options::OPT_pg))
4495 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4496 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4497 << A->getAsString(Args);
4498
4499 // Claim some arguments which clang supports automatically.
4500
4501 // -fpch-preprocess is used with gcc to add a special marker in the output to
4502 // include the PCH file. Clang's PTH solution is completely transparent, so we
4503 // do not need to deal with it at all.
4504 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4505
4506 // Claim some arguments which clang doesn't support, but we don't
4507 // care to warn the user about.
4508 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4509 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4510
4511 // Disable warnings for clang -E -emit-llvm foo.c
4512 Args.ClaimAllArgs(options::OPT_emit_llvm);
4513}
4514
4515Clang::Clang(const ToolChain &TC)
4516 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4517 // as it is for other tools. Some operations on a Tool actually test
4518 // whether that tool is Clang based on the Tool's Name as a string.
4519 : Tool("clang", "clang frontend", TC, RF_Full) {}
4520
4521Clang::~Clang() {}
4522
4523/// Add options related to the Objective-C runtime/ABI.
4524///
4525/// Returns true if the runtime is non-fragile.
4526ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4527 ArgStringList &cmdArgs,
4528 RewriteKind rewriteKind) const {
4529 // Look for the controlling runtime option.
4530 Arg *runtimeArg =
4531 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4532 options::OPT_fobjc_runtime_EQ);
4533
4534 // Just forward -fobjc-runtime= to the frontend. This supercedes
4535 // options about fragility.
4536 if (runtimeArg &&
4537 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4538 ObjCRuntime runtime;
4539 StringRef value = runtimeArg->getValue();
4540 if (runtime.tryParse(value)) {
4541 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4542 << value;
4543 }
4544
4545 runtimeArg->render(args, cmdArgs);
4546 return runtime;
4547 }
4548
4549 // Otherwise, we'll need the ABI "version". Version numbers are
4550 // slightly confusing for historical reasons:
4551 // 1 - Traditional "fragile" ABI
4552 // 2 - Non-fragile ABI, version 1
4553 // 3 - Non-fragile ABI, version 2
4554 unsigned objcABIVersion = 1;
4555 // If -fobjc-abi-version= is present, use that to set the version.
4556 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4557 StringRef value = abiArg->getValue();
4558 if (value == "1")
4559 objcABIVersion = 1;
4560 else if (value == "2")
4561 objcABIVersion = 2;
4562 else if (value == "3")
4563 objcABIVersion = 3;
4564 else
4565 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4566 } else {
4567 // Otherwise, determine if we are using the non-fragile ABI.
4568 bool nonFragileABIIsDefault =
4569 (rewriteKind == RK_NonFragile ||
4570 (rewriteKind == RK_None &&
4571 getToolChain().IsObjCNonFragileABIDefault()));
4572 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4573 options::OPT_fno_objc_nonfragile_abi,
4574 nonFragileABIIsDefault)) {
4575// Determine the non-fragile ABI version to use.
4576#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4577 unsigned nonFragileABIVersion = 1;
4578#else
4579 unsigned nonFragileABIVersion = 2;
4580#endif
4581
4582 if (Arg *abiArg =
4583 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4584 StringRef value = abiArg->getValue();
4585 if (value == "1")
4586 nonFragileABIVersion = 1;
4587 else if (value == "2")
4588 nonFragileABIVersion = 2;
4589 else
4590 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4591 << value;
4592 }
4593
4594 objcABIVersion = 1 + nonFragileABIVersion;
4595 } else {
4596 objcABIVersion = 1;
4597 }
4598 }
4599
4600 // We don't actually care about the ABI version other than whether
4601 // it's non-fragile.
4602 bool isNonFragile = objcABIVersion != 1;
4603
4604 // If we have no runtime argument, ask the toolchain for its default runtime.
4605 // However, the rewriter only really supports the Mac runtime, so assume that.
4606 ObjCRuntime runtime;
4607 if (!runtimeArg) {
4608 switch (rewriteKind) {
4609 case RK_None:
4610 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4611 break;
4612 case RK_Fragile:
4613 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4614 break;
4615 case RK_NonFragile:
4616 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4617 break;
4618 }
4619
4620 // -fnext-runtime
4621 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4622 // On Darwin, make this use the default behavior for the toolchain.
4623 if (getToolChain().getTriple().isOSDarwin()) {
4624 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4625
4626 // Otherwise, build for a generic macosx port.
4627 } else {
4628 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4629 }
4630
4631 // -fgnu-runtime
4632 } else {
4633 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4634 // Legacy behaviour is to target the gnustep runtime if we are in
4635 // non-fragile mode or the GCC runtime in fragile mode.
4636 if (isNonFragile)
4637 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4638 else
4639 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4640 }
4641
4642 cmdArgs.push_back(
4643 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4644 return runtime;
4645}
4646
4647static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4648 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4649 I += HaveDash;
4650 return !HaveDash;
4651}
4652
4653namespace {
4654struct EHFlags {
4655 bool Synch = false;
4656 bool Asynch = false;
4657 bool NoUnwindC = false;
4658};
4659} // end anonymous namespace
4660
4661/// /EH controls whether to run destructor cleanups when exceptions are
4662/// thrown. There are three modifiers:
4663/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4664/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4665/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4666/// - c: Assume that extern "C" functions are implicitly nounwind.
4667/// The default is /EHs-c-, meaning cleanups are disabled.
4668static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4669 EHFlags EH;
4670
4671 std::vector<std::string> EHArgs =
4672 Args.getAllArgValues(options::OPT__SLASH_EH);
4673 for (auto EHVal : EHArgs) {
4674 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4675 switch (EHVal[I]) {
4676 case 'a':
4677 EH.Asynch = maybeConsumeDash(EHVal, I);
4678 if (EH.Asynch)
4679 EH.Synch = false;
4680 continue;
4681 case 'c':
4682 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
4683 continue;
4684 case 's':
4685 EH.Synch = maybeConsumeDash(EHVal, I);
4686 if (EH.Synch)
4687 EH.Asynch = false;
4688 continue;
4689 default:
4690 break;
4691 }
4692 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4693 break;
4694 }
4695 }
4696 // The /GX, /GX- flags are only processed if there are not /EH flags.
4697 // The default is that /GX is not specified.
4698 if (EHArgs.empty() &&
4699 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
4700 /*default=*/false)) {
4701 EH.Synch = true;
4702 EH.NoUnwindC = true;
4703 }
4704
4705 return EH;
4706}
4707
4708void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
4709 ArgStringList &CmdArgs,
4710 codegenoptions::DebugInfoKind *DebugInfoKind,
4711 bool *EmitCodeView) const {
4712 unsigned RTOptionID = options::OPT__SLASH_MT;
4713
4714 if (Args.hasArg(options::OPT__SLASH_LDd))
4715 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4716 // but defining _DEBUG is sticky.
4717 RTOptionID = options::OPT__SLASH_MTd;
4718
4719 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4720 RTOptionID = A->getOption().getID();
4721
4722 StringRef FlagForCRT;
4723 switch (RTOptionID) {
4724 case options::OPT__SLASH_MD:
4725 if (Args.hasArg(options::OPT__SLASH_LDd))
4726 CmdArgs.push_back("-D_DEBUG");
4727 CmdArgs.push_back("-D_MT");
4728 CmdArgs.push_back("-D_DLL");
4729 FlagForCRT = "--dependent-lib=msvcrt";
4730 break;
4731 case options::OPT__SLASH_MDd:
4732 CmdArgs.push_back("-D_DEBUG");
4733 CmdArgs.push_back("-D_MT");
4734 CmdArgs.push_back("-D_DLL");
4735 FlagForCRT = "--dependent-lib=msvcrtd";
4736 break;
4737 case options::OPT__SLASH_MT:
4738 if (Args.hasArg(options::OPT__SLASH_LDd))
4739 CmdArgs.push_back("-D_DEBUG");
4740 CmdArgs.push_back("-D_MT");
4741 CmdArgs.push_back("-flto-visibility-public-std");
4742 FlagForCRT = "--dependent-lib=libcmt";
4743 break;
4744 case options::OPT__SLASH_MTd:
4745 CmdArgs.push_back("-D_DEBUG");
4746 CmdArgs.push_back("-D_MT");
4747 CmdArgs.push_back("-flto-visibility-public-std");
4748 FlagForCRT = "--dependent-lib=libcmtd";
4749 break;
4750 default:
4751 llvm_unreachable("Unexpected option ID.");
4752 }
4753
4754 if (Args.hasArg(options::OPT__SLASH_Zl)) {
4755 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4756 } else {
4757 CmdArgs.push_back(FlagForCRT.data());
4758
4759 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4760 // users want. The /Za flag to cl.exe turns this off, but it's not
4761 // implemented in clang.
4762 CmdArgs.push_back("--dependent-lib=oldnames");
4763 }
4764
4765 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4766 // would produce interleaved output, so ignore /showIncludes in such cases.
4767 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
4768 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4769 A->render(Args, CmdArgs);
4770
4771 // This controls whether or not we emit RTTI data for polymorphic types.
4772 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4773 /*default=*/false))
4774 CmdArgs.push_back("-fno-rtti-data");
4775
4776 // This controls whether or not we emit stack-protector instrumentation.
4777 // In MSVC, Buffer Security Check (/GS) is on by default.
4778 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
4779 /*default=*/true)) {
4780 CmdArgs.push_back("-stack-protector");
4781 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
4782 }
4783
4784 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
4785 if (Arg *DebugInfoArg =
4786 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
4787 options::OPT_gline_tables_only)) {
4788 *EmitCodeView = true;
4789 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
4790 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
4791 else
4792 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4793 CmdArgs.push_back("-gcodeview");
4794 } else {
4795 *EmitCodeView = false;
4796 }
4797
4798 const Driver &D = getToolChain().getDriver();
4799 EHFlags EH = parseClangCLEHFlags(D, Args);
4800 if (EH.Synch || EH.Asynch) {
4801 if (types::isCXX(InputType))
4802 CmdArgs.push_back("-fcxx-exceptions");
4803 CmdArgs.push_back("-fexceptions");
4804 }
4805 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
4806 CmdArgs.push_back("-fexternc-nounwind");
4807
4808 // /EP should expand to -E -P.
4809 if (Args.hasArg(options::OPT__SLASH_EP)) {
4810 CmdArgs.push_back("-E");
4811 CmdArgs.push_back("-P");
4812 }
4813
4814 unsigned VolatileOptionID;
4815 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
4816 getToolChain().getArch() == llvm::Triple::x86)
4817 VolatileOptionID = options::OPT__SLASH_volatile_ms;
4818 else
4819 VolatileOptionID = options::OPT__SLASH_volatile_iso;
4820
4821 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
4822 VolatileOptionID = A->getOption().getID();
4823
4824 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
4825 CmdArgs.push_back("-fms-volatile");
4826
4827 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
4828 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
4829 if (MostGeneralArg && BestCaseArg)
4830 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4831 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
4832
4833 if (MostGeneralArg) {
4834 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
4835 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
4836 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
4837
4838 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
4839 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
4840 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
4841 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4842 << FirstConflict->getAsString(Args)
4843 << SecondConflict->getAsString(Args);
4844
4845 if (SingleArg)
4846 CmdArgs.push_back("-fms-memptr-rep=single");
4847 else if (MultipleArg)
4848 CmdArgs.push_back("-fms-memptr-rep=multiple");
4849 else
4850 CmdArgs.push_back("-fms-memptr-rep=virtual");
4851 }
4852
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004853 // Parse the default calling convention options.
4854 if (Arg *CCArg =
4855 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
4856 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv)) {
4857 unsigned DCCOptId = CCArg->getOption().getID();
4858 const char *DCCFlag = nullptr;
4859 bool ArchSupported = true;
4860 llvm::Triple::ArchType Arch = getToolChain().getArch();
4861 switch (DCCOptId) {
4862 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00004863 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004864 break;
4865 case options::OPT__SLASH_Gr:
4866 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00004867 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004868 break;
4869 case options::OPT__SLASH_Gz:
4870 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00004871 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004872 break;
4873 case options::OPT__SLASH_Gv:
4874 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00004875 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004876 break;
4877 }
4878
4879 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
4880 if (ArchSupported && DCCFlag)
4881 CmdArgs.push_back(DCCFlag);
4882 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004883
4884 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
4885 A->render(Args, CmdArgs);
4886
4887 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
4888 CmdArgs.push_back("-fdiagnostics-format");
4889 if (Args.hasArg(options::OPT__SLASH_fallback))
4890 CmdArgs.push_back("msvc-fallback");
4891 else
4892 CmdArgs.push_back("msvc");
4893 }
4894}
4895
4896visualstudio::Compiler *Clang::getCLFallback() const {
4897 if (!CLFallback)
4898 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
4899 return CLFallback.get();
4900}
4901
4902
4903const char *Clang::getBaseInputName(const ArgList &Args,
4904 const InputInfo &Input) {
4905 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
4906}
4907
4908const char *Clang::getBaseInputStem(const ArgList &Args,
4909 const InputInfoList &Inputs) {
4910 const char *Str = getBaseInputName(Args, Inputs[0]);
4911
4912 if (const char *End = strrchr(Str, '.'))
4913 return Args.MakeArgString(std::string(Str, End));
4914
4915 return Str;
4916}
4917
4918const char *Clang::getDependencyFileName(const ArgList &Args,
4919 const InputInfoList &Inputs) {
4920 // FIXME: Think about this more.
4921 std::string Res;
4922
4923 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4924 std::string Str(OutputOpt->getValue());
4925 Res = Str.substr(0, Str.rfind('.'));
4926 } else {
4927 Res = getBaseInputStem(Args, Inputs);
4928 }
4929 return Args.MakeArgString(Res + ".d");
4930}
4931
4932// Begin ClangAs
4933
4934void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
4935 ArgStringList &CmdArgs) const {
4936 StringRef CPUName;
4937 StringRef ABIName;
4938 const llvm::Triple &Triple = getToolChain().getTriple();
4939 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
4940
4941 CmdArgs.push_back("-target-abi");
4942 CmdArgs.push_back(ABIName.data());
4943}
4944
4945void ClangAs::AddX86TargetArgs(const ArgList &Args,
4946 ArgStringList &CmdArgs) const {
4947 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
4948 StringRef Value = A->getValue();
4949 if (Value == "intel" || Value == "att") {
4950 CmdArgs.push_back("-mllvm");
4951 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
4952 } else {
4953 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
4954 << A->getOption().getName() << Value;
4955 }
4956 }
4957}
4958
4959void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
4960 const InputInfo &Output, const InputInfoList &Inputs,
4961 const ArgList &Args,
4962 const char *LinkingOutput) const {
4963 ArgStringList CmdArgs;
4964
4965 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4966 const InputInfo &Input = Inputs[0];
4967
4968 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
4969 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00004970 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00004971
4972 // Don't warn about "clang -w -c foo.s"
4973 Args.ClaimAllArgs(options::OPT_w);
4974 // and "clang -emit-llvm -c foo.s"
4975 Args.ClaimAllArgs(options::OPT_emit_llvm);
4976
4977 claimNoWarnArgs(Args);
4978
4979 // Invoke ourselves in -cc1as mode.
4980 //
4981 // FIXME: Implement custom jobs for internal actions.
4982 CmdArgs.push_back("-cc1as");
4983
4984 // Add the "effective" target triple.
4985 CmdArgs.push_back("-triple");
4986 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4987
4988 // Set the output mode, we currently only expect to be used as a real
4989 // assembler.
4990 CmdArgs.push_back("-filetype");
4991 CmdArgs.push_back("obj");
4992
4993 // Set the main file name, so that debug info works even with
4994 // -save-temps or preprocessed assembly.
4995 CmdArgs.push_back("-main-file-name");
4996 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
4997
4998 // Add the target cpu
4999 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5000 if (!CPU.empty()) {
5001 CmdArgs.push_back("-target-cpu");
5002 CmdArgs.push_back(Args.MakeArgString(CPU));
5003 }
5004
5005 // Add the target features
5006 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5007
5008 // Ignore explicit -force_cpusubtype_ALL option.
5009 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5010
5011 // Pass along any -I options so we get proper .include search paths.
5012 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5013
5014 // Determine the original source input.
5015 const Action *SourceAction = &JA;
5016 while (SourceAction->getKind() != Action::InputClass) {
5017 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5018 SourceAction = SourceAction->getInputs()[0];
5019 }
5020
5021 // Forward -g and handle debug info related flags, assuming we are dealing
5022 // with an actual assembly file.
5023 bool WantDebug = false;
5024 unsigned DwarfVersion = 0;
5025 Args.ClaimAllArgs(options::OPT_g_Group);
5026 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5027 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5028 !A->getOption().matches(options::OPT_ggdb0);
5029 if (WantDebug)
5030 DwarfVersion = DwarfVersionNum(A->getSpelling());
5031 }
5032 if (DwarfVersion == 0)
5033 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5034
5035 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5036
5037 if (SourceAction->getType() == types::TY_Asm ||
5038 SourceAction->getType() == types::TY_PP_Asm) {
5039 // You might think that it would be ok to set DebugInfoKind outside of
5040 // the guard for source type, however there is a test which asserts
5041 // that some assembler invocation receives no -debug-info-kind,
5042 // and it's not clear whether that test is just overly restrictive.
5043 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5044 : codegenoptions::NoDebugInfo);
5045 // Add the -fdebug-compilation-dir flag if needed.
5046 addDebugCompDirArg(Args, CmdArgs);
5047
5048 // Set the AT_producer to the clang version when using the integrated
5049 // assembler on assembly source files.
5050 CmdArgs.push_back("-dwarf-debug-producer");
5051 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5052
5053 // And pass along -I options
5054 Args.AddAllArgs(CmdArgs, options::OPT_I);
5055 }
5056 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5057 llvm::DebuggerKind::Default);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005058 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5059
David L. Jonesf561aba2017-03-08 01:02:16 +00005060
5061 // Handle -fPIC et al -- the relocation-model affects the assembler
5062 // for some targets.
5063 llvm::Reloc::Model RelocationModel;
5064 unsigned PICLevel;
5065 bool IsPIE;
5066 std::tie(RelocationModel, PICLevel, IsPIE) =
5067 ParsePICArgs(getToolChain(), Args);
5068
5069 const char *RMName = RelocationModelName(RelocationModel);
5070 if (RMName) {
5071 CmdArgs.push_back("-mrelocation-model");
5072 CmdArgs.push_back(RMName);
5073 }
5074
5075 // Optionally embed the -cc1as level arguments into the debug info, for build
5076 // analysis.
5077 if (getToolChain().UseDwarfDebugFlags()) {
5078 ArgStringList OriginalArgs;
5079 for (const auto &Arg : Args)
5080 Arg->render(Args, OriginalArgs);
5081
5082 SmallString<256> Flags;
5083 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5084 Flags += Exec;
5085 for (const char *OriginalArg : OriginalArgs) {
5086 SmallString<128> EscapedArg;
5087 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5088 Flags += " ";
5089 Flags += EscapedArg;
5090 }
5091 CmdArgs.push_back("-dwarf-debug-flags");
5092 CmdArgs.push_back(Args.MakeArgString(Flags));
5093 }
5094
5095 // FIXME: Add -static support, once we have it.
5096
5097 // Add target specific flags.
5098 switch (getToolChain().getArch()) {
5099 default:
5100 break;
5101
5102 case llvm::Triple::mips:
5103 case llvm::Triple::mipsel:
5104 case llvm::Triple::mips64:
5105 case llvm::Triple::mips64el:
5106 AddMIPSTargetArgs(Args, CmdArgs);
5107 break;
5108
5109 case llvm::Triple::x86:
5110 case llvm::Triple::x86_64:
5111 AddX86TargetArgs(Args, CmdArgs);
5112 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005113
5114 case llvm::Triple::arm:
5115 case llvm::Triple::armeb:
5116 case llvm::Triple::thumb:
5117 case llvm::Triple::thumbeb:
5118 // This isn't in AddARMTargetArgs because we want to do this for assembly
5119 // only, not C/C++.
5120 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5121 options::OPT_mno_default_build_attributes, true)) {
5122 CmdArgs.push_back("-mllvm");
5123 CmdArgs.push_back("-arm-add-build-attributes");
5124 }
5125 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005126 }
5127
5128 // Consume all the warning flags. Usually this would be handled more
5129 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5130 // doesn't handle that so rather than warning about unused flags that are
5131 // actually used, we'll lie by omission instead.
5132 // FIXME: Stop lying and consume only the appropriate driver flags
5133 Args.ClaimAllArgs(options::OPT_W_Group);
5134
5135 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5136 getToolChain().getDriver());
5137
5138 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5139
5140 assert(Output.isFilename() && "Unexpected lipo output.");
5141 CmdArgs.push_back("-o");
5142 CmdArgs.push_back(Output.getFilename());
5143
5144 assert(Input.isFilename() && "Invalid input.");
5145 CmdArgs.push_back(Input.getFilename());
5146
5147 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5148 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5149
5150 // Handle the debug info splitting at object creation time if we're
5151 // creating an object.
5152 // TODO: Currently only works on linux with newer objcopy.
5153 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5154 getToolChain().getTriple().isOSLinux())
5155 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5156 SplitDebugName(Args, Input));
5157}
5158
5159// Begin OffloadBundler
5160
5161void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5162 const InputInfo &Output,
5163 const InputInfoList &Inputs,
5164 const llvm::opt::ArgList &TCArgs,
5165 const char *LinkingOutput) const {
5166 // The version with only one output is expected to refer to a bundling job.
5167 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5168
5169 // The bundling command looks like this:
5170 // clang-offload-bundler -type=bc
5171 // -targets=host-triple,openmp-triple1,openmp-triple2
5172 // -outputs=input_file
5173 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5174
5175 ArgStringList CmdArgs;
5176
5177 // Get the type.
5178 CmdArgs.push_back(TCArgs.MakeArgString(
5179 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5180
5181 assert(JA.getInputs().size() == Inputs.size() &&
5182 "Not have inputs for all dependence actions??");
5183
5184 // Get the targets.
5185 SmallString<128> Triples;
5186 Triples += "-targets=";
5187 for (unsigned I = 0; I < Inputs.size(); ++I) {
5188 if (I)
5189 Triples += ',';
5190
5191 Action::OffloadKind CurKind = Action::OFK_Host;
5192 const ToolChain *CurTC = &getToolChain();
5193 const Action *CurDep = JA.getInputs()[I];
5194
5195 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
5196 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
5197 CurKind = A->getOffloadingDeviceKind();
5198 CurTC = TC;
5199 });
5200 }
5201 Triples += Action::GetOffloadKindName(CurKind);
5202 Triples += '-';
5203 Triples += CurTC->getTriple().normalize();
5204 }
5205 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5206
5207 // Get bundled file command.
5208 CmdArgs.push_back(
5209 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5210
5211 // Get unbundled files command.
5212 SmallString<128> UB;
5213 UB += "-inputs=";
5214 for (unsigned I = 0; I < Inputs.size(); ++I) {
5215 if (I)
5216 UB += ',';
5217 UB += Inputs[I].getFilename();
5218 }
5219 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5220
5221 // All the inputs are encoded as commands.
5222 C.addCommand(llvm::make_unique<Command>(
5223 JA, *this,
5224 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5225 CmdArgs, None));
5226}
5227
5228void OffloadBundler::ConstructJobMultipleOutputs(
5229 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5230 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5231 const char *LinkingOutput) const {
5232 // The version with multiple outputs is expected to refer to a unbundling job.
5233 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5234
5235 // The unbundling command looks like this:
5236 // clang-offload-bundler -type=bc
5237 // -targets=host-triple,openmp-triple1,openmp-triple2
5238 // -inputs=input_file
5239 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5240 // -unbundle
5241
5242 ArgStringList CmdArgs;
5243
5244 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5245 InputInfo Input = Inputs.front();
5246
5247 // Get the type.
5248 CmdArgs.push_back(TCArgs.MakeArgString(
5249 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5250
5251 // Get the targets.
5252 SmallString<128> Triples;
5253 Triples += "-targets=";
5254 auto DepInfo = UA.getDependentActionsInfo();
5255 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5256 if (I)
5257 Triples += ',';
5258
5259 auto &Dep = DepInfo[I];
5260 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5261 Triples += '-';
5262 Triples += Dep.DependentToolChain->getTriple().normalize();
5263 }
5264
5265 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5266
5267 // Get bundled file command.
5268 CmdArgs.push_back(
5269 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5270
5271 // Get unbundled files command.
5272 SmallString<128> UB;
5273 UB += "-outputs=";
5274 for (unsigned I = 0; I < Outputs.size(); ++I) {
5275 if (I)
5276 UB += ',';
5277 UB += Outputs[I].getFilename();
5278 }
5279 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5280 CmdArgs.push_back("-unbundle");
5281
5282 // All the inputs are encoded as commands.
5283 C.addCommand(llvm::make_unique<Command>(
5284 JA, *this,
5285 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5286 CmdArgs, None));
5287}