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