blob: 06d782d296930913455f04ce153c3468466f9c4a [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
David L. Jonesf561aba2017-03-08 01:02:16 +00002304 // Handle various floating point optimization flags, mapping them to the
John Brawn5c4c6112017-03-15 14:03:32 +00002305 // appropriate LLVM code generation flags. This is complicated by several
2306 // "umbrella" flags, so we do this by stepping through the flags incrementally
2307 // adjusting what we think is enabled/disabled, then at the end settting the
2308 // LLVM flags based on the final state.
2309 bool HonorInfs = true;
2310 bool HonorNans = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002311 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2312 bool MathErrno = getToolChain().IsMathErrnoDefault();
John Brawn5c4c6112017-03-15 14:03:32 +00002313 bool AssociativeMath = false;
2314 bool ReciprocalMath = false;
2315 bool SignedZeros = true;
2316 bool TrappingMath = true;
2317 StringRef DenormalFpMath = "";
2318 StringRef FpContract = "";
2319
2320 for (Arg *A : Args) {
2321 switch (A->getOption().getID()) {
2322 // If this isn't an FP option skip the claim below
2323 default:
2324 continue;
2325
2326 // Options controlling individual features
2327 case options::OPT_fhonor_infinities: HonorInfs = true; break;
2328 case options::OPT_fno_honor_infinities: HonorInfs = false; break;
2329 case options::OPT_fhonor_nans: HonorNans = true; break;
2330 case options::OPT_fno_honor_nans: HonorNans = false; break;
2331 case options::OPT_fmath_errno: MathErrno = true; break;
2332 case options::OPT_fno_math_errno: MathErrno = false; break;
2333 case options::OPT_fassociative_math: AssociativeMath = true; break;
2334 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2335 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2336 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2337 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2338 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2339 case options::OPT_ftrapping_math: TrappingMath = true; break;
2340 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2341
2342 case options::OPT_fdenormal_fp_math_EQ:
2343 DenormalFpMath = A->getValue();
2344 break;
2345
2346 // Validate and pass through -fp-contract option.
2347 case options::OPT_ffp_contract: {
2348 StringRef Val = A->getValue();
2349 if (Val == "fast" || Val == "on" || Val == "off") {
2350 FpContract = Val;
2351 } else {
2352 D.Diag(diag::err_drv_unsupported_option_argument)
2353 << A->getOption().getName() << Val;
2354 }
2355 break;
2356 }
2357
2358 case options::OPT_ffinite_math_only:
2359 HonorInfs = false;
2360 HonorNans = false;
2361 break;
2362 case options::OPT_fno_finite_math_only:
2363 HonorInfs = true;
2364 HonorNans = true;
2365 break;
2366
2367 case options::OPT_funsafe_math_optimizations:
2368 AssociativeMath = true;
2369 ReciprocalMath = true;
2370 SignedZeros = false;
2371 TrappingMath = false;
2372 break;
2373 case options::OPT_fno_unsafe_math_optimizations:
2374 AssociativeMath = false;
2375 ReciprocalMath = false;
2376 SignedZeros = true;
2377 TrappingMath = true;
2378 // -fno_unsafe_math_optimizations restores default denormal handling
2379 DenormalFpMath = "";
2380 break;
2381
2382 case options::OPT_Ofast:
2383 // If -Ofast is the optimization level, then -ffast-math should be enabled
2384 if (!OFastEnabled)
2385 continue;
2386 LLVM_FALLTHROUGH;
2387 case options::OPT_ffast_math:
2388 HonorInfs = false;
2389 HonorNans = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00002390 MathErrno = false;
John Brawn5c4c6112017-03-15 14:03:32 +00002391 AssociativeMath = true;
2392 ReciprocalMath = true;
2393 SignedZeros = false;
2394 TrappingMath = false;
2395 // If fast-math is set then set the fp-contract mode to fast.
2396 FpContract = "fast";
2397 break;
2398 case options::OPT_fno_fast_math:
2399 HonorInfs = true;
2400 HonorNans = true;
2401 // Turning on -ffast-math (with either flag) removes the need for
2402 // MathErrno. However, turning *off* -ffast-math merely restores the
2403 // toolchain default (which may be false).
2404 MathErrno = getToolChain().IsMathErrnoDefault();
2405 AssociativeMath = false;
2406 ReciprocalMath = false;
2407 SignedZeros = true;
2408 TrappingMath = true;
2409 // -fno_fast_math restores default denormal and fpcontract handling
2410 DenormalFpMath = "";
2411 FpContract = "";
2412 break;
2413 }
2414 // If we handled this option claim it
2415 A->claim();
David L. Jonesf561aba2017-03-08 01:02:16 +00002416 }
John Brawn5c4c6112017-03-15 14:03:32 +00002417
2418 if (!HonorInfs)
2419 CmdArgs.push_back("-menable-no-infs");
2420
2421 if (!HonorNans)
2422 CmdArgs.push_back("-menable-no-nans");
2423
David L. Jonesf561aba2017-03-08 01:02:16 +00002424 if (MathErrno)
2425 CmdArgs.push_back("-fmath-errno");
2426
David L. Jonesf561aba2017-03-08 01:02:16 +00002427 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2428 !TrappingMath)
2429 CmdArgs.push_back("-menable-unsafe-fp-math");
2430
2431 if (!SignedZeros)
2432 CmdArgs.push_back("-fno-signed-zeros");
2433
2434 if (ReciprocalMath)
2435 CmdArgs.push_back("-freciprocal-math");
2436
2437 if (!TrappingMath)
2438 CmdArgs.push_back("-fno-trapping-math");
2439
John Brawn5c4c6112017-03-15 14:03:32 +00002440 if (!DenormalFpMath.empty())
2441 CmdArgs.push_back(Args.MakeArgString("-fdenormal-fp-math="+DenormalFpMath));
David L. Jonesf561aba2017-03-08 01:02:16 +00002442
John Brawn5c4c6112017-03-15 14:03:32 +00002443 if (!FpContract.empty())
2444 CmdArgs.push_back(Args.MakeArgString("-ffp-contract="+FpContract));
David L. Jonesf561aba2017-03-08 01:02:16 +00002445
2446 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
2447
John Brawn5c4c6112017-03-15 14:03:32 +00002448 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2449 // individual features enabled by -ffast-math instead of the option itself as
2450 // that's consistent with gcc's behaviour.
2451 if (!HonorInfs && !HonorNans && !MathErrno && AssociativeMath &&
2452 ReciprocalMath && !SignedZeros && !TrappingMath)
2453 CmdArgs.push_back("-ffast-math");
2454
2455 // Handle __FINITE_MATH_ONLY__ similarly.
2456 if (!HonorInfs && !HonorNans)
2457 CmdArgs.push_back("-ffinite-math-only");
David L. Jonesf561aba2017-03-08 01:02:16 +00002458
2459 // Decide whether to use verbose asm. Verbose assembly is the default on
2460 // toolchains which have the integrated assembler on by default.
2461 bool IsIntegratedAssemblerDefault =
2462 getToolChain().IsIntegratedAssemblerDefault();
2463 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2464 IsIntegratedAssemblerDefault) ||
2465 Args.hasArg(options::OPT_dA))
2466 CmdArgs.push_back("-masm-verbose");
2467
2468 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
2469 IsIntegratedAssemblerDefault))
2470 CmdArgs.push_back("-no-integrated-as");
2471
2472 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2473 CmdArgs.push_back("-mdebug-pass");
2474 CmdArgs.push_back("Structure");
2475 }
2476 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2477 CmdArgs.push_back("-mdebug-pass");
2478 CmdArgs.push_back("Arguments");
2479 }
2480
2481 // Enable -mconstructor-aliases except on darwin, where we have to work around
2482 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
2483 // aliases aren't supported.
2484 if (!getToolChain().getTriple().isOSDarwin() &&
2485 !getToolChain().getTriple().isNVPTX())
2486 CmdArgs.push_back("-mconstructor-aliases");
2487
2488 // Darwin's kernel doesn't support guard variables; just die if we
2489 // try to use them.
2490 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2491 CmdArgs.push_back("-fforbid-guard-variables");
2492
2493 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
2494 false)) {
2495 CmdArgs.push_back("-mms-bitfields");
2496 }
2497
2498 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
2499 options::OPT_mno_pie_copy_relocations,
2500 false)) {
2501 CmdArgs.push_back("-mpie-copy-relocations");
2502 }
2503
2504 // This is a coarse approximation of what llvm-gcc actually does, both
2505 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2506 // complicated ways.
2507 bool AsynchronousUnwindTables =
2508 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2509 options::OPT_fno_asynchronous_unwind_tables,
2510 (getToolChain().IsUnwindTablesDefault() ||
2511 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
2512 !KernelOrKext);
2513 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2514 AsynchronousUnwindTables))
2515 CmdArgs.push_back("-munwind-tables");
2516
2517 getToolChain().addClangTargetOptions(Args, CmdArgs);
2518
2519 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2520 CmdArgs.push_back("-mlimit-float-precision");
2521 CmdArgs.push_back(A->getValue());
2522 }
2523
2524 // FIXME: Handle -mtune=.
2525 (void)Args.hasArg(options::OPT_mtune_EQ);
2526
2527 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2528 CmdArgs.push_back("-mcode-model");
2529 CmdArgs.push_back(A->getValue());
2530 }
2531
2532 // Add the target cpu
2533 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
2534 if (!CPU.empty()) {
2535 CmdArgs.push_back("-target-cpu");
2536 CmdArgs.push_back(Args.MakeArgString(CPU));
2537 }
2538
2539 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2540 CmdArgs.push_back("-mfpmath");
2541 CmdArgs.push_back(A->getValue());
2542 }
2543
2544 // Add the target features
2545 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
2546
2547 // Add target specific flags.
2548 switch (getToolChain().getArch()) {
2549 default:
2550 break;
2551
2552 case llvm::Triple::arm:
2553 case llvm::Triple::armeb:
2554 case llvm::Triple::thumb:
2555 case llvm::Triple::thumbeb:
2556 // Use the effective triple, which takes into account the deployment target.
2557 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
2558 break;
2559
2560 case llvm::Triple::aarch64:
2561 case llvm::Triple::aarch64_be:
2562 AddAArch64TargetArgs(Args, CmdArgs);
2563 break;
2564
2565 case llvm::Triple::mips:
2566 case llvm::Triple::mipsel:
2567 case llvm::Triple::mips64:
2568 case llvm::Triple::mips64el:
2569 AddMIPSTargetArgs(Args, CmdArgs);
2570 break;
2571
2572 case llvm::Triple::ppc:
2573 case llvm::Triple::ppc64:
2574 case llvm::Triple::ppc64le:
2575 AddPPCTargetArgs(Args, CmdArgs);
2576 break;
2577
2578 case llvm::Triple::sparc:
2579 case llvm::Triple::sparcel:
2580 case llvm::Triple::sparcv9:
2581 AddSparcTargetArgs(Args, CmdArgs);
2582 break;
2583
2584 case llvm::Triple::systemz:
2585 AddSystemZTargetArgs(Args, CmdArgs);
2586 break;
2587
2588 case llvm::Triple::x86:
2589 case llvm::Triple::x86_64:
2590 AddX86TargetArgs(Args, CmdArgs);
2591 break;
2592
2593 case llvm::Triple::lanai:
2594 AddLanaiTargetArgs(Args, CmdArgs);
2595 break;
2596
2597 case llvm::Triple::hexagon:
2598 AddHexagonTargetArgs(Args, CmdArgs);
2599 break;
2600
2601 case llvm::Triple::wasm32:
2602 case llvm::Triple::wasm64:
2603 AddWebAssemblyTargetArgs(Args, CmdArgs);
2604 break;
2605 }
2606
2607 // The 'g' groups options involve a somewhat intricate sequence of decisions
2608 // about what to pass from the driver to the frontend, but by the time they
2609 // reach cc1 they've been factored into three well-defined orthogonal choices:
2610 // * what level of debug info to generate
2611 // * what dwarf version to write
2612 // * what debugger tuning to use
2613 // This avoids having to monkey around further in cc1 other than to disable
2614 // codeview if not running in a Windows environment. Perhaps even that
2615 // decision should be made in the driver as well though.
2616 unsigned DwarfVersion = 0;
2617 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
2618 // These two are potentially updated by AddClangCLArgs.
2619 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
2620 bool EmitCodeView = false;
2621
2622 // Add clang-cl arguments.
2623 types::ID InputType = Input.getType();
2624 if (getToolChain().getDriver().IsCLMode())
2625 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
2626
2627 // Pass the linker version in use.
2628 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2629 CmdArgs.push_back("-target-linker-version");
2630 CmdArgs.push_back(A->getValue());
2631 }
2632
2633 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
2634 CmdArgs.push_back("-momit-leaf-frame-pointer");
2635
2636 // Explicitly error on some things we know we don't support and can't just
2637 // ignore.
2638 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
2639 Arg *Unsupported;
2640 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
2641 getToolChain().getArch() == llvm::Triple::x86) {
2642 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
2643 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
2644 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
2645 << Unsupported->getOption().getName();
2646 }
2647 }
2648
2649 Args.AddAllArgs(CmdArgs, options::OPT_v);
2650 Args.AddLastArg(CmdArgs, options::OPT_H);
2651 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
2652 CmdArgs.push_back("-header-include-file");
2653 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
2654 : "-");
2655 }
2656 Args.AddLastArg(CmdArgs, options::OPT_P);
2657 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
2658
2659 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
2660 CmdArgs.push_back("-diagnostic-log-file");
2661 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
2662 : "-");
2663 }
2664
2665 bool splitDwarfInlining =
2666 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2667 options::OPT_fno_split_dwarf_inlining, true);
2668
2669 Args.ClaimAllArgs(options::OPT_g_Group);
2670 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2671 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2672 // If the last option explicitly specified a debug-info level, use it.
2673 if (A->getOption().matches(options::OPT_gN_Group)) {
2674 DebugInfoKind = DebugLevelToInfoKind(*A);
2675 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2676 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2677 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
2678 // This gets a bit more complicated if you've disabled inline info in the
2679 // skeleton CUs (splitDwarfInlining) - then there's value in composing
2680 // split-dwarf and line-tables-only, so let those compose naturally in
2681 // that case.
2682 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2683 if (SplitDwarfArg) {
2684 if (A->getIndex() > SplitDwarfArg->getIndex()) {
2685 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2686 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2687 splitDwarfInlining))
2688 SplitDwarfArg = nullptr;
2689 } else if (splitDwarfInlining)
2690 DebugInfoKind = codegenoptions::NoDebugInfo;
2691 }
2692 } else
2693 // For any other 'g' option, use Limited.
2694 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2695 }
2696
2697 // If a debugger tuning argument appeared, remember it.
2698 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2699 options::OPT_ggdbN_Group)) {
2700 if (A->getOption().matches(options::OPT_glldb))
2701 DebuggerTuning = llvm::DebuggerKind::LLDB;
2702 else if (A->getOption().matches(options::OPT_gsce))
2703 DebuggerTuning = llvm::DebuggerKind::SCE;
2704 else
2705 DebuggerTuning = llvm::DebuggerKind::GDB;
2706 }
2707
2708 // If a -gdwarf argument appeared, remember it.
2709 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2710 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2711 DwarfVersion = DwarfVersionNum(A->getSpelling());
2712
2713 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2714 // argument parsing.
2715 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
2716 // DwarfVersion remains at 0 if no explicit choice was made.
2717 CmdArgs.push_back("-gcodeview");
2718 } else if (DwarfVersion == 0 &&
2719 DebugInfoKind != codegenoptions::NoDebugInfo) {
2720 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
2721 }
2722
2723 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
2724 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2725
2726 // Column info is included by default for everything except PS4 and CodeView.
2727 // Clang doesn't track end columns, just starting columns, which, in theory,
2728 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2729 // debuggers don't handle missing end columns well, so it's better not to
2730 // include any column info.
2731 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
2732 /*Default=*/ !IsPS4CPU && !(IsWindowsMSVC && EmitCodeView)))
2733 CmdArgs.push_back("-dwarf-column-info");
2734
2735 // FIXME: Move backend command line options to the module.
2736 // If -gline-tables-only is the last option it wins.
2737 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2738 Args.hasArg(options::OPT_gmodules)) {
2739 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2740 CmdArgs.push_back("-dwarf-ext-refs");
2741 CmdArgs.push_back("-fmodule-format=obj");
2742 }
2743
2744 // -gsplit-dwarf should turn on -g and enable the backend dwarf
2745 // splitting and extraction.
2746 // FIXME: Currently only works on Linux.
2747 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
2748 if (!splitDwarfInlining)
2749 CmdArgs.push_back("-fno-split-dwarf-inlining");
2750 if (DebugInfoKind == codegenoptions::NoDebugInfo)
2751 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2752 CmdArgs.push_back("-backend-option");
2753 CmdArgs.push_back("-split-dwarf=Enable");
2754 }
2755
2756 // After we've dealt with all combinations of things that could
2757 // make DebugInfoKind be other than None or DebugLineTablesOnly,
2758 // figure out if we need to "upgrade" it to standalone debug info.
2759 // We parse these two '-f' options whether or not they will be used,
2760 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
2761 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
2762 options::OPT_fno_standalone_debug,
2763 getToolChain().GetDefaultStandaloneDebug());
2764 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
2765 DebugInfoKind = codegenoptions::FullDebugInfo;
2766 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
2767 DebuggerTuning);
2768
2769 // -fdebug-macro turns on macro debug info generation.
2770 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
2771 false))
2772 CmdArgs.push_back("-debug-info-macro");
2773
2774 // -ggnu-pubnames turns on gnu style pubnames in the backend.
2775 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
2776 CmdArgs.push_back("-backend-option");
2777 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
2778 }
2779
2780 // -gdwarf-aranges turns on the emission of the aranges section in the
2781 // backend.
2782 // Always enabled on the PS4.
2783 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
2784 CmdArgs.push_back("-backend-option");
2785 CmdArgs.push_back("-generate-arange-section");
2786 }
2787
2788 if (Args.hasFlag(options::OPT_fdebug_types_section,
2789 options::OPT_fno_debug_types_section, false)) {
2790 CmdArgs.push_back("-backend-option");
2791 CmdArgs.push_back("-generate-type-units");
2792 }
2793
2794 bool UseSeparateSections = isUseSeparateSections(Triple);
2795
2796 if (Args.hasFlag(options::OPT_ffunction_sections,
2797 options::OPT_fno_function_sections, UseSeparateSections)) {
2798 CmdArgs.push_back("-ffunction-sections");
2799 }
2800
2801 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
2802 UseSeparateSections)) {
2803 CmdArgs.push_back("-fdata-sections");
2804 }
2805
2806 if (!Args.hasFlag(options::OPT_funique_section_names,
2807 options::OPT_fno_unique_section_names, true))
2808 CmdArgs.push_back("-fno-unique-section-names");
2809
2810 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2811
2812 if (Args.hasFlag(options::OPT_fxray_instrument,
2813 options::OPT_fnoxray_instrument, false)) {
2814 const char *const XRayInstrumentOption = "-fxray-instrument";
2815 if (Triple.getOS() == llvm::Triple::Linux)
2816 switch (Triple.getArch()) {
2817 case llvm::Triple::x86_64:
2818 case llvm::Triple::arm:
2819 case llvm::Triple::aarch64:
2820 case llvm::Triple::ppc64le:
2821 case llvm::Triple::mips:
2822 case llvm::Triple::mipsel:
2823 case llvm::Triple::mips64:
2824 case llvm::Triple::mips64el:
2825 // Supported.
2826 break;
2827 default:
2828 D.Diag(diag::err_drv_clang_unsupported)
2829 << (std::string(XRayInstrumentOption) + " on " + Triple.str());
2830 }
2831 else
2832 D.Diag(diag::err_drv_clang_unsupported)
2833 << (std::string(XRayInstrumentOption) + " on non-Linux target OS");
2834 CmdArgs.push_back(XRayInstrumentOption);
2835 if (const Arg *A =
2836 Args.getLastArg(options::OPT_fxray_instruction_threshold_,
2837 options::OPT_fxray_instruction_threshold_EQ)) {
2838 CmdArgs.push_back("-fxray-instruction-threshold");
2839 CmdArgs.push_back(A->getValue());
2840 }
2841 }
2842
2843 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
2844
2845 // Add runtime flag for PS4 when PGO or Coverage are enabled.
2846 if (getToolChain().getTriple().isPS4CPU())
2847 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
2848
2849 // Pass options for controlling the default header search paths.
2850 if (Args.hasArg(options::OPT_nostdinc)) {
2851 CmdArgs.push_back("-nostdsysteminc");
2852 CmdArgs.push_back("-nobuiltininc");
2853 } else {
2854 if (Args.hasArg(options::OPT_nostdlibinc))
2855 CmdArgs.push_back("-nostdsysteminc");
2856 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2857 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2858 }
2859
2860 // Pass the path to compiler resource files.
2861 CmdArgs.push_back("-resource-dir");
2862 CmdArgs.push_back(D.ResourceDir.c_str());
2863
2864 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2865
2866 bool ARCMTEnabled = false;
2867 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2868 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2869 options::OPT_ccc_arcmt_modify,
2870 options::OPT_ccc_arcmt_migrate)) {
2871 ARCMTEnabled = true;
2872 switch (A->getOption().getID()) {
2873 default:
2874 llvm_unreachable("missed a case");
2875 case options::OPT_ccc_arcmt_check:
2876 CmdArgs.push_back("-arcmt-check");
2877 break;
2878 case options::OPT_ccc_arcmt_modify:
2879 CmdArgs.push_back("-arcmt-modify");
2880 break;
2881 case options::OPT_ccc_arcmt_migrate:
2882 CmdArgs.push_back("-arcmt-migrate");
2883 CmdArgs.push_back("-mt-migrate-directory");
2884 CmdArgs.push_back(A->getValue());
2885
2886 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2887 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2888 break;
2889 }
2890 }
2891 } else {
2892 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2893 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2894 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2895 }
2896
2897 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2898 if (ARCMTEnabled) {
2899 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
2900 << "-ccc-arcmt-migrate";
2901 }
2902 CmdArgs.push_back("-mt-migrate-directory");
2903 CmdArgs.push_back(A->getValue());
2904
2905 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2906 options::OPT_objcmt_migrate_subscripting,
2907 options::OPT_objcmt_migrate_property)) {
2908 // None specified, means enable them all.
2909 CmdArgs.push_back("-objcmt-migrate-literals");
2910 CmdArgs.push_back("-objcmt-migrate-subscripting");
2911 CmdArgs.push_back("-objcmt-migrate-property");
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 }
2917 } else {
2918 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2919 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2920 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2921 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2922 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2923 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2924 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2925 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2926 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2927 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2928 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2929 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2930 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2931 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2932 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2933 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2934 }
2935
2936 // Add preprocessing options like -I, -D, etc. if we are using the
2937 // preprocessor.
2938 //
2939 // FIXME: Support -fpreprocessed
2940 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2941 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
2942
2943 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2944 // that "The compiler can only warn and ignore the option if not recognized".
2945 // When building with ccache, it will pass -D options to clang even on
2946 // preprocessed inputs and configure concludes that -fPIC is not supported.
2947 Args.ClaimAllArgs(options::OPT_D);
2948
2949 // Manually translate -O4 to -O3; let clang reject others.
2950 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2951 if (A->getOption().matches(options::OPT_O4)) {
2952 CmdArgs.push_back("-O3");
2953 D.Diag(diag::warn_O4_is_O3);
2954 } else {
2955 A->render(Args, CmdArgs);
2956 }
2957 }
2958
2959 // Warn about ignored options to clang.
2960 for (const Arg *A :
2961 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
2962 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
2963 A->claim();
2964 }
2965
2966 claimNoWarnArgs(Args);
2967
2968 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
2969
2970 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
2971 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
2972 CmdArgs.push_back("-pedantic");
2973 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
2974 Args.AddLastArg(CmdArgs, options::OPT_w);
2975
2976 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
2977 // (-ansi is equivalent to -std=c89 or -std=c++98).
2978 //
2979 // If a std is supplied, only add -trigraphs if it follows the
2980 // option.
2981 bool ImplyVCPPCXXVer = false;
2982 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2983 if (Std->getOption().matches(options::OPT_ansi))
2984 if (types::isCXX(InputType))
2985 CmdArgs.push_back("-std=c++98");
2986 else
2987 CmdArgs.push_back("-std=c89");
2988 else
2989 Std->render(Args, CmdArgs);
2990
2991 // If -f(no-)trigraphs appears after the language standard flag, honor it.
2992 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
2993 options::OPT_ftrigraphs,
2994 options::OPT_fno_trigraphs))
2995 if (A != Std)
2996 A->render(Args, CmdArgs);
2997 } else {
2998 // Honor -std-default.
2999 //
3000 // FIXME: Clang doesn't correctly handle -std= when the input language
3001 // doesn't match. For the time being just ignore this for C++ inputs;
3002 // eventually we want to do all the standard defaulting here instead of
3003 // splitting it between the driver and clang -cc1.
3004 if (!types::isCXX(InputType))
3005 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3006 /*Joined=*/true);
3007 else if (IsWindowsMSVC)
3008 ImplyVCPPCXXVer = true;
3009
3010 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3011 options::OPT_fno_trigraphs);
3012 }
3013
3014 // GCC's behavior for -Wwrite-strings is a bit strange:
3015 // * In C, this "warning flag" changes the types of string literals from
3016 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3017 // for the discarded qualifier.
3018 // * In C++, this is just a normal warning flag.
3019 //
3020 // Implementing this warning correctly in C is hard, so we follow GCC's
3021 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3022 // a non-const char* in C, rather than using this crude hack.
3023 if (!types::isCXX(InputType)) {
3024 // FIXME: This should behave just like a warning flag, and thus should also
3025 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3026 Arg *WriteStrings =
3027 Args.getLastArg(options::OPT_Wwrite_strings,
3028 options::OPT_Wno_write_strings, options::OPT_w);
3029 if (WriteStrings &&
3030 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3031 CmdArgs.push_back("-fconst-strings");
3032 }
3033
3034 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3035 // during C++ compilation, which it is by default. GCC keeps this define even
3036 // in the presence of '-w', match this behavior bug-for-bug.
3037 if (types::isCXX(InputType) &&
3038 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3039 true)) {
3040 CmdArgs.push_back("-fdeprecated-macro");
3041 }
3042
3043 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3044 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3045 if (Asm->getOption().matches(options::OPT_fasm))
3046 CmdArgs.push_back("-fgnu-keywords");
3047 else
3048 CmdArgs.push_back("-fno-gnu-keywords");
3049 }
3050
3051 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3052 CmdArgs.push_back("-fno-dwarf-directory-asm");
3053
3054 if (ShouldDisableAutolink(Args, getToolChain()))
3055 CmdArgs.push_back("-fno-autolink");
3056
3057 // Add in -fdebug-compilation-dir if necessary.
3058 addDebugCompDirArg(Args, CmdArgs);
3059
3060 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3061 StringRef Map = A->getValue();
3062 if (Map.find('=') == StringRef::npos)
3063 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3064 else
3065 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3066 A->claim();
3067 }
3068
3069 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3070 options::OPT_ftemplate_depth_EQ)) {
3071 CmdArgs.push_back("-ftemplate-depth");
3072 CmdArgs.push_back(A->getValue());
3073 }
3074
3075 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3076 CmdArgs.push_back("-foperator-arrow-depth");
3077 CmdArgs.push_back(A->getValue());
3078 }
3079
3080 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3081 CmdArgs.push_back("-fconstexpr-depth");
3082 CmdArgs.push_back(A->getValue());
3083 }
3084
3085 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3086 CmdArgs.push_back("-fconstexpr-steps");
3087 CmdArgs.push_back(A->getValue());
3088 }
3089
3090 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3091 CmdArgs.push_back("-fbracket-depth");
3092 CmdArgs.push_back(A->getValue());
3093 }
3094
3095 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3096 options::OPT_Wlarge_by_value_copy_def)) {
3097 if (A->getNumValues()) {
3098 StringRef bytes = A->getValue();
3099 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3100 } else
3101 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3102 }
3103
3104 if (Args.hasArg(options::OPT_relocatable_pch))
3105 CmdArgs.push_back("-relocatable-pch");
3106
3107 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3108 CmdArgs.push_back("-fconstant-string-class");
3109 CmdArgs.push_back(A->getValue());
3110 }
3111
3112 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3113 CmdArgs.push_back("-ftabstop");
3114 CmdArgs.push_back(A->getValue());
3115 }
3116
3117 CmdArgs.push_back("-ferror-limit");
3118 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3119 CmdArgs.push_back(A->getValue());
3120 else
3121 CmdArgs.push_back("19");
3122
3123 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3124 CmdArgs.push_back("-fmacro-backtrace-limit");
3125 CmdArgs.push_back(A->getValue());
3126 }
3127
3128 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3129 CmdArgs.push_back("-ftemplate-backtrace-limit");
3130 CmdArgs.push_back(A->getValue());
3131 }
3132
3133 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3134 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3135 CmdArgs.push_back(A->getValue());
3136 }
3137
3138 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3139 CmdArgs.push_back("-fspell-checking-limit");
3140 CmdArgs.push_back(A->getValue());
3141 }
3142
3143 // Pass -fmessage-length=.
3144 CmdArgs.push_back("-fmessage-length");
3145 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3146 CmdArgs.push_back(A->getValue());
3147 } else {
3148 // If -fmessage-length=N was not specified, determine whether this is a
3149 // terminal and, if so, implicitly define -fmessage-length appropriately.
3150 unsigned N = llvm::sys::Process::StandardErrColumns();
3151 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3152 }
3153
3154 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3155 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3156 options::OPT_fvisibility_ms_compat)) {
3157 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3158 CmdArgs.push_back("-fvisibility");
3159 CmdArgs.push_back(A->getValue());
3160 } else {
3161 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3162 CmdArgs.push_back("-fvisibility");
3163 CmdArgs.push_back("hidden");
3164 CmdArgs.push_back("-ftype-visibility");
3165 CmdArgs.push_back("default");
3166 }
3167 }
3168
3169 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3170
3171 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3172
3173 // -fhosted is default.
3174 bool IsHosted = true;
3175 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3176 KernelOrKext) {
3177 CmdArgs.push_back("-ffreestanding");
3178 IsHosted = false;
3179 }
3180
3181 // Forward -f (flag) options which we can pass directly.
3182 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3183 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3184 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3185 // Emulated TLS is enabled by default on Android, and can be enabled manually
3186 // with -femulated-tls.
3187 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
3188 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
3189 EmulatedTLSDefault))
3190 CmdArgs.push_back("-femulated-tls");
3191 // AltiVec-like language extensions aren't relevant for assembling.
3192 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
3193 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
3194 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
3195 }
3196 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3197 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3198
3199 // Forward flags for OpenMP. We don't do this if the current action is an
3200 // device offloading action other than OpenMP.
3201 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3202 options::OPT_fno_openmp, false) &&
3203 (JA.isDeviceOffloading(Action::OFK_None) ||
3204 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
3205 switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
3206 case Driver::OMPRT_OMP:
3207 case Driver::OMPRT_IOMP5:
3208 // Clang can generate useful OpenMP code for these two runtime libraries.
3209 CmdArgs.push_back("-fopenmp");
3210
3211 // If no option regarding the use of TLS in OpenMP codegeneration is
3212 // given, decide a default based on the target. Otherwise rely on the
3213 // options and pass the right information to the frontend.
3214 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3215 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3216 CmdArgs.push_back("-fnoopenmp-use-tls");
3217 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
3218 break;
3219 default:
3220 // By default, if Clang doesn't know how to generate useful OpenMP code
3221 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3222 // down to the actual compilation.
3223 // FIXME: It would be better to have a mode which *only* omits IR
3224 // generation based on the OpenMP support so that we get consistent
3225 // semantic analysis, etc.
3226 break;
3227 }
3228 }
3229
3230 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3231 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3232
3233 // Report an error for -faltivec on anything other than PowerPC.
3234 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
3235 const llvm::Triple::ArchType Arch = getToolChain().getArch();
3236 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
3237 Arch == llvm::Triple::ppc64le))
3238 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3239 << "ppc/ppc64/ppc64le";
3240 }
3241
3242 // -fzvector is incompatible with -faltivec.
3243 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
3244 if (Args.hasArg(options::OPT_faltivec))
3245 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
3246 << "-faltivec";
3247
3248 if (getToolChain().SupportsProfiling())
3249 Args.AddLastArg(CmdArgs, options::OPT_pg);
3250
3251 if (getToolChain().SupportsProfiling())
3252 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
3253
3254 // -flax-vector-conversions is default.
3255 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3256 options::OPT_fno_lax_vector_conversions))
3257 CmdArgs.push_back("-fno-lax-vector-conversions");
3258
3259 if (Args.getLastArg(options::OPT_fapple_kext) ||
3260 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
3261 CmdArgs.push_back("-fapple-kext");
3262
3263 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3264 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3265 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3266 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3267 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3268
3269 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3270 CmdArgs.push_back("-ftrapv-handler");
3271 CmdArgs.push_back(A->getValue());
3272 }
3273
3274 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3275
3276 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3277 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3278 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3279 if (A->getOption().matches(options::OPT_fwrapv))
3280 CmdArgs.push_back("-fwrapv");
3281 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3282 options::OPT_fno_strict_overflow)) {
3283 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3284 CmdArgs.push_back("-fwrapv");
3285 }
3286
3287 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3288 options::OPT_fno_reroll_loops))
3289 if (A->getOption().matches(options::OPT_freroll_loops))
3290 CmdArgs.push_back("-freroll-loops");
3291
3292 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3293 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3294 options::OPT_fno_unroll_loops);
3295
3296 Args.AddLastArg(CmdArgs, options::OPT_pthread);
3297
3298 // -stack-protector=0 is default.
3299 unsigned StackProtectorLevel = 0;
3300 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3301 // doesn't even have a stack!
3302 if (!Triple.isNVPTX()) {
3303 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3304 options::OPT_fstack_protector_all,
3305 options::OPT_fstack_protector_strong,
3306 options::OPT_fstack_protector)) {
3307 if (A->getOption().matches(options::OPT_fstack_protector)) {
3308 StackProtectorLevel = std::max<unsigned>(
3309 LangOptions::SSPOn,
3310 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
3311 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3312 StackProtectorLevel = LangOptions::SSPStrong;
3313 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3314 StackProtectorLevel = LangOptions::SSPReq;
3315 } else {
3316 StackProtectorLevel =
3317 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3318 // Only use a default stack protector on Darwin in case -ffreestanding
3319 // is not specified.
3320 if (Triple.isOSDarwin() && !IsHosted)
3321 StackProtectorLevel = 0;
3322 }
3323 }
3324 if (StackProtectorLevel) {
3325 CmdArgs.push_back("-stack-protector");
3326 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3327 }
3328
3329 // --param ssp-buffer-size=
3330 for (const Arg *A : Args.filtered(options::OPT__param)) {
3331 StringRef Str(A->getValue());
3332 if (Str.startswith("ssp-buffer-size=")) {
3333 if (StackProtectorLevel) {
3334 CmdArgs.push_back("-stack-protector-buffer-size");
3335 // FIXME: Verify the argument is a valid integer.
3336 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3337 }
3338 A->claim();
3339 }
3340 }
3341
3342 // Translate -mstackrealign
3343 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3344 false))
3345 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3346
3347 if (Args.hasArg(options::OPT_mstack_alignment)) {
3348 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3349 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3350 }
3351
3352 if (Args.hasArg(options::OPT_mstack_probe_size)) {
3353 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
3354
3355 if (!Size.empty())
3356 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
3357 else
3358 CmdArgs.push_back("-mstack-probe-size=0");
3359 }
3360
3361 switch (getToolChain().getArch()) {
3362 case llvm::Triple::aarch64:
3363 case llvm::Triple::aarch64_be:
3364 case llvm::Triple::arm:
3365 case llvm::Triple::armeb:
3366 case llvm::Triple::thumb:
3367 case llvm::Triple::thumbeb:
3368 CmdArgs.push_back("-fallow-half-arguments-and-returns");
3369 break;
3370
3371 default:
3372 break;
3373 }
3374
3375 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3376 options::OPT_mno_restrict_it)) {
3377 if (A->getOption().matches(options::OPT_mrestrict_it)) {
3378 CmdArgs.push_back("-backend-option");
3379 CmdArgs.push_back("-arm-restrict-it");
3380 } else {
3381 CmdArgs.push_back("-backend-option");
3382 CmdArgs.push_back("-arm-no-restrict-it");
3383 }
3384 } else if (Triple.isOSWindows() &&
3385 (Triple.getArch() == llvm::Triple::arm ||
3386 Triple.getArch() == llvm::Triple::thumb)) {
3387 // Windows on ARM expects restricted IT blocks
3388 CmdArgs.push_back("-backend-option");
3389 CmdArgs.push_back("-arm-restrict-it");
3390 }
3391
3392 // Forward -cl options to -cc1
3393 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
3394 CmdArgs.push_back("-cl-opt-disable");
3395 }
3396 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
3397 CmdArgs.push_back("-cl-strict-aliasing");
3398 }
3399 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
3400 CmdArgs.push_back("-cl-single-precision-constant");
3401 }
3402 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
3403 CmdArgs.push_back("-cl-finite-math-only");
3404 }
3405 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
3406 CmdArgs.push_back("-cl-kernel-arg-info");
3407 }
3408 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
3409 CmdArgs.push_back("-cl-unsafe-math-optimizations");
3410 }
3411 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
3412 CmdArgs.push_back("-cl-fast-relaxed-math");
3413 }
3414 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
3415 CmdArgs.push_back("-cl-mad-enable");
3416 }
3417 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
3418 CmdArgs.push_back("-cl-no-signed-zeros");
3419 }
3420 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3421 std::string CLStdStr = "-cl-std=";
3422 CLStdStr += A->getValue();
3423 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3424 }
3425 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
3426 CmdArgs.push_back("-cl-denorms-are-zero");
3427 }
3428 if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
3429 CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
3430 }
3431
3432 // Forward -f options with positive and negative forms; we translate
3433 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00003434 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003435 StringRef fname = A->getValue();
3436 if (!llvm::sys::fs::exists(fname))
3437 D.Diag(diag::err_drv_no_such_file) << fname;
3438 else
3439 A->render(Args, CmdArgs);
3440 }
3441
3442 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3443 options::OPT_fno_debug_info_for_profiling, false))
3444 CmdArgs.push_back("-fdebug-info-for-profiling");
3445
3446 // -fbuiltin is default unless -mkernel is used.
3447 bool UseBuiltins =
3448 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3449 !Args.hasArg(options::OPT_mkernel));
3450 if (!UseBuiltins)
3451 CmdArgs.push_back("-fno-builtin");
3452
3453 // -ffreestanding implies -fno-builtin.
3454 if (Args.hasArg(options::OPT_ffreestanding))
3455 UseBuiltins = false;
3456
3457 // Process the -fno-builtin-* options.
3458 for (const auto &Arg : Args) {
3459 const Option &O = Arg->getOption();
3460 if (!O.matches(options::OPT_fno_builtin_))
3461 continue;
3462
3463 Arg->claim();
3464 // If -fno-builtin is specified, then there's no need to pass the option to
3465 // the frontend.
3466 if (!UseBuiltins)
3467 continue;
3468
3469 StringRef FuncName = Arg->getValue();
3470 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3471 }
3472
3473 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3474 options::OPT_fno_assume_sane_operator_new))
3475 CmdArgs.push_back("-fno-assume-sane-operator-new");
3476
3477 // -fblocks=0 is default.
3478 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3479 getToolChain().IsBlocksDefault()) ||
3480 (Args.hasArg(options::OPT_fgnu_runtime) &&
3481 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3482 !Args.hasArg(options::OPT_fno_blocks))) {
3483 CmdArgs.push_back("-fblocks");
3484
3485 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
3486 !getToolChain().hasBlocksRuntime())
3487 CmdArgs.push_back("-fblocks-runtime-optional");
3488 }
3489
3490 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
3491 false) &&
3492 types::isCXX(InputType)) {
3493 CmdArgs.push_back("-fcoroutines-ts");
3494 }
3495
3496 // -fmodules enables the use of precompiled modules (off by default).
3497 // Users can pass -fno-cxx-modules to turn off modules support for
3498 // C++/Objective-C++ programs.
3499 bool HaveClangModules = false;
3500 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3501 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3502 options::OPT_fno_cxx_modules, true);
3503 if (AllowedInCXX || !types::isCXX(InputType)) {
3504 CmdArgs.push_back("-fmodules");
3505 HaveClangModules = true;
3506 }
3507 }
3508
3509 bool HaveAnyModules = HaveClangModules;
3510 if (Args.hasArg(options::OPT_fmodules_ts)) {
3511 CmdArgs.push_back("-fmodules-ts");
3512 HaveAnyModules = true;
3513 }
3514
3515 // -fmodule-maps enables implicit reading of module map files. By default,
3516 // this is enabled if we are using Clang's flavor of precompiled modules.
3517 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3518 options::OPT_fno_implicit_module_maps, HaveClangModules)) {
3519 CmdArgs.push_back("-fimplicit-module-maps");
3520 }
3521
3522 // -fmodules-decluse checks that modules used are declared so (off by
3523 // default).
3524 if (Args.hasFlag(options::OPT_fmodules_decluse,
3525 options::OPT_fno_modules_decluse, false)) {
3526 CmdArgs.push_back("-fmodules-decluse");
3527 }
3528
3529 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3530 // all #included headers are part of modules.
3531 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3532 options::OPT_fno_modules_strict_decluse, false)) {
3533 CmdArgs.push_back("-fmodules-strict-decluse");
3534 }
3535
3536 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3537 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3538 options::OPT_fno_implicit_modules, HaveClangModules)) {
3539 if (HaveAnyModules)
3540 CmdArgs.push_back("-fno-implicit-modules");
3541 } else if (HaveAnyModules) {
3542 // -fmodule-cache-path specifies where our implicitly-built module files
3543 // should be written.
3544 SmallString<128> Path;
3545 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3546 Path = A->getValue();
3547 if (C.isForDiagnostics()) {
3548 // When generating crash reports, we want to emit the modules along with
3549 // the reproduction sources, so we ignore any provided module path.
3550 Path = Output.getFilename();
3551 llvm::sys::path::replace_extension(Path, ".cache");
3552 llvm::sys::path::append(Path, "modules");
3553 } else if (Path.empty()) {
3554 // No module path was provided: use the default.
3555 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
3556 llvm::sys::path::append(Path, "org.llvm.clang.");
3557 appendUserToPath(Path);
3558 llvm::sys::path::append(Path, "ModuleCache");
3559 }
3560 const char Arg[] = "-fmodules-cache-path=";
3561 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3562 CmdArgs.push_back(Args.MakeArgString(Path));
3563 }
3564
3565 if (HaveAnyModules) {
3566 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3567 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path))
3568 CmdArgs.push_back(Args.MakeArgString(
3569 std::string("-fprebuilt-module-path=") + A->getValue()));
3570 }
3571
3572 // -fmodule-name specifies the module that is currently being built (or
3573 // used for header checking by -fmodule-maps).
3574 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3575
3576 // -fmodule-map-file can be used to specify files containing module
3577 // definitions.
3578 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3579
3580 // -fbuiltin-module-map can be used to load the clang
3581 // builtin headers modulemap file.
3582 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3583 SmallString<128> BuiltinModuleMap(getToolChain().getDriver().ResourceDir);
3584 llvm::sys::path::append(BuiltinModuleMap, "include");
3585 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3586 if (llvm::sys::fs::exists(BuiltinModuleMap)) {
3587 CmdArgs.push_back(Args.MakeArgString("-fmodule-map-file=" +
3588 BuiltinModuleMap));
3589 }
3590 }
3591
3592 // -fmodule-file can be used to specify files containing precompiled modules.
3593 if (HaveAnyModules)
3594 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3595 else
3596 Args.ClaimAllArgs(options::OPT_fmodule_file);
3597
3598 // When building modules and generating crashdumps, we need to dump a module
3599 // dependency VFS alongside the output.
3600 if (HaveClangModules && C.isForDiagnostics()) {
3601 SmallString<128> VFSDir(Output.getFilename());
3602 llvm::sys::path::replace_extension(VFSDir, ".cache");
3603 // Add the cache directory as a temp so the crash diagnostics pick it up.
3604 C.addTempFile(Args.MakeArgString(VFSDir));
3605
3606 llvm::sys::path::append(VFSDir, "vfs");
3607 CmdArgs.push_back("-module-dependency-dir");
3608 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3609 }
3610
3611 if (HaveClangModules)
3612 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3613
3614 // Pass through all -fmodules-ignore-macro arguments.
3615 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3616 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3617 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3618
3619 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3620
3621 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3622 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3623 D.Diag(diag::err_drv_argument_not_allowed_with)
3624 << A->getAsString(Args) << "-fbuild-session-timestamp";
3625
3626 llvm::sys::fs::file_status Status;
3627 if (llvm::sys::fs::status(A->getValue(), Status))
3628 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3629 CmdArgs.push_back(
3630 Args.MakeArgString("-fbuild-session-timestamp=" +
3631 Twine((uint64_t)Status.getLastModificationTime()
3632 .time_since_epoch()
3633 .count())));
3634 }
3635
3636 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3637 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3638 options::OPT_fbuild_session_file))
3639 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3640
3641 Args.AddLastArg(CmdArgs,
3642 options::OPT_fmodules_validate_once_per_build_session);
3643 }
3644
3645 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
3646 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3647
3648 // -faccess-control is default.
3649 if (Args.hasFlag(options::OPT_fno_access_control,
3650 options::OPT_faccess_control, false))
3651 CmdArgs.push_back("-fno-access-control");
3652
3653 // -felide-constructors is the default.
3654 if (Args.hasFlag(options::OPT_fno_elide_constructors,
3655 options::OPT_felide_constructors, false))
3656 CmdArgs.push_back("-fno-elide-constructors");
3657
3658 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
3659
3660 if (KernelOrKext || (types::isCXX(InputType) &&
3661 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
3662 RTTIMode == ToolChain::RM_DisabledImplicitly)))
3663 CmdArgs.push_back("-fno-rtti");
3664
3665 // -fshort-enums=0 is default for all architectures except Hexagon.
3666 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
3667 getToolChain().getArch() == llvm::Triple::hexagon))
3668 CmdArgs.push_back("-fshort-enums");
3669
3670 // -fsigned-char is default.
3671 if (Arg *A = Args.getLastArg(
3672 options::OPT_fsigned_char, options::OPT_fno_signed_char,
3673 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
3674 if (A->getOption().matches(options::OPT_funsigned_char) ||
3675 A->getOption().matches(options::OPT_fno_signed_char)) {
3676 CmdArgs.push_back("-fno-signed-char");
3677 }
3678 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
3679 CmdArgs.push_back("-fno-signed-char");
3680 }
3681
3682 // -fuse-cxa-atexit is default.
3683 if (!Args.hasFlag(
3684 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
3685 !IsWindowsCygnus && !IsWindowsGNU &&
3686 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
3687 getToolChain().getArch() != llvm::Triple::hexagon &&
3688 getToolChain().getArch() != llvm::Triple::xcore &&
3689 ((getToolChain().getTriple().getVendor() !=
3690 llvm::Triple::MipsTechnologies) ||
3691 getToolChain().getTriple().hasEnvironment())) ||
3692 KernelOrKext)
3693 CmdArgs.push_back("-fno-use-cxa-atexit");
3694
3695 // -fms-extensions=0 is default.
3696 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3697 IsWindowsMSVC))
3698 CmdArgs.push_back("-fms-extensions");
3699
3700 // -fno-use-line-directives is default.
3701 if (Args.hasFlag(options::OPT_fuse_line_directives,
3702 options::OPT_fno_use_line_directives, false))
3703 CmdArgs.push_back("-fuse-line-directives");
3704
3705 // -fms-compatibility=0 is default.
3706 if (Args.hasFlag(options::OPT_fms_compatibility,
3707 options::OPT_fno_ms_compatibility,
3708 (IsWindowsMSVC &&
3709 Args.hasFlag(options::OPT_fms_extensions,
3710 options::OPT_fno_ms_extensions, true))))
3711 CmdArgs.push_back("-fms-compatibility");
3712
3713 VersionTuple MSVT =
3714 getToolChain().computeMSVCVersion(&getToolChain().getDriver(), Args);
3715 if (!MSVT.empty())
3716 CmdArgs.push_back(
3717 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
3718
3719 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
3720 if (ImplyVCPPCXXVer) {
3721 StringRef LanguageStandard;
3722 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
3723 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
3724 .Case("c++14", "-std=c++14")
3725 .Case("c++latest", "-std=c++1z")
3726 .Default("");
3727 if (LanguageStandard.empty())
3728 D.Diag(clang::diag::warn_drv_unused_argument)
3729 << StdArg->getAsString(Args);
3730 }
3731
3732 if (LanguageStandard.empty()) {
3733 if (IsMSVC2015Compatible)
3734 LanguageStandard = "-std=c++14";
3735 else
3736 LanguageStandard = "-std=c++11";
3737 }
3738
3739 CmdArgs.push_back(LanguageStandard.data());
3740 }
3741
3742 // -fno-borland-extensions is default.
3743 if (Args.hasFlag(options::OPT_fborland_extensions,
3744 options::OPT_fno_borland_extensions, false))
3745 CmdArgs.push_back("-fborland-extensions");
3746
3747 // -fno-declspec is default, except for PS4.
3748 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
3749 getToolChain().getTriple().isPS4()))
3750 CmdArgs.push_back("-fdeclspec");
3751 else if (Args.hasArg(options::OPT_fno_declspec))
3752 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
3753
3754 // -fthreadsafe-static is default, except for MSVC compatibility versions less
3755 // than 19.
3756 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3757 options::OPT_fno_threadsafe_statics,
3758 !IsWindowsMSVC || IsMSVC2015Compatible))
3759 CmdArgs.push_back("-fno-threadsafe-statics");
3760
3761 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
3762 // needs it.
3763 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
3764 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
3765 CmdArgs.push_back("-fdelayed-template-parsing");
3766
3767 // -fgnu-keywords default varies depending on language; only pass if
3768 // specified.
3769 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3770 options::OPT_fno_gnu_keywords))
3771 A->render(Args, CmdArgs);
3772
3773 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
3774 false))
3775 CmdArgs.push_back("-fgnu89-inline");
3776
3777 if (Args.hasArg(options::OPT_fno_inline))
3778 CmdArgs.push_back("-fno-inline");
3779
3780 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
3781 options::OPT_finline_hint_functions,
3782 options::OPT_fno_inline_functions))
3783 InlineArg->render(Args, CmdArgs);
3784
3785 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
3786 options::OPT_fno_experimental_new_pass_manager);
3787
3788 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3789
3790 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3791 // legacy is the default. Except for deployment target of 10.5,
3792 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
3793 // gets ignored silently.
3794 if (objcRuntime.isNonFragile()) {
3795 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3796 options::OPT_fno_objc_legacy_dispatch,
3797 objcRuntime.isLegacyDispatchDefaultForArch(
3798 getToolChain().getArch()))) {
3799 if (getToolChain().UseObjCMixedDispatch())
3800 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3801 else
3802 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3803 }
3804 }
3805
3806 // When ObjectiveC legacy runtime is in effect on MacOSX,
3807 // turn on the option to do Array/Dictionary subscripting
3808 // by default.
3809 if (getToolChain().getArch() == llvm::Triple::x86 &&
3810 getToolChain().getTriple().isMacOSX() &&
3811 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
3812 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
3813 objcRuntime.isNeXTFamily())
3814 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3815
3816 // -fencode-extended-block-signature=1 is default.
3817 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3818 CmdArgs.push_back("-fencode-extended-block-signature");
3819 }
3820
3821 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3822 // NOTE: This logic is duplicated in ToolChains.cpp.
3823 bool ARC = isObjCAutoRefCount(Args);
3824 if (ARC) {
3825 getToolChain().CheckObjCARC();
3826
3827 CmdArgs.push_back("-fobjc-arc");
3828
3829 // FIXME: It seems like this entire block, and several around it should be
3830 // wrapped in isObjC, but for now we just use it here as this is where it
3831 // was being used previously.
3832 if (types::isCXX(InputType) && types::isObjC(InputType)) {
3833 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3834 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3835 else
3836 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3837 }
3838
3839 // Allow the user to enable full exceptions code emission.
3840 // We define off for Objective-CC, on for Objective-C++.
3841 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3842 options::OPT_fno_objc_arc_exceptions,
3843 /*default*/ types::isCXX(InputType)))
3844 CmdArgs.push_back("-fobjc-arc-exceptions");
3845 }
3846
3847 // Silence warning for full exception code emission options when explicitly
3848 // set to use no ARC.
3849 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3850 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3851 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3852 }
3853
3854 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3855 // rewriter.
3856 if (rewriteKind != RK_None)
3857 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3858
3859 // Pass down -fobjc-weak or -fno-objc-weak if present.
3860 if (types::isObjC(InputType)) {
3861 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
3862 options::OPT_fno_objc_weak);
3863 if (!WeakArg) {
3864 // nothing to do
3865 } else if (!objcRuntime.allowsWeak()) {
3866 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3867 D.Diag(diag::err_objc_weak_unsupported);
3868 } else {
3869 WeakArg->render(Args, CmdArgs);
3870 }
3871 }
3872
3873 if (Args.hasFlag(options::OPT_fapplication_extension,
3874 options::OPT_fno_application_extension, false))
3875 CmdArgs.push_back("-fapplication-extension");
3876
3877 // Handle GCC-style exception args.
3878 if (!C.getDriver().IsCLMode())
3879 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
3880 CmdArgs);
3881
3882 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
3883 getToolChain().UseSjLjExceptions(Args))
3884 CmdArgs.push_back("-fsjlj-exceptions");
3885
3886 // C++ "sane" operator new.
3887 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3888 options::OPT_fno_assume_sane_operator_new))
3889 CmdArgs.push_back("-fno-assume-sane-operator-new");
3890
3891 // -frelaxed-template-template-args is off by default, as it is a severe
3892 // breaking change until a corresponding change to template partial ordering
3893 // is provided.
3894 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
3895 options::OPT_fno_relaxed_template_template_args, false))
3896 CmdArgs.push_back("-frelaxed-template-template-args");
3897
3898 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
3899 // most platforms.
3900 if (Args.hasFlag(options::OPT_fsized_deallocation,
3901 options::OPT_fno_sized_deallocation, false))
3902 CmdArgs.push_back("-fsized-deallocation");
3903
3904 // -faligned-allocation is on by default in C++17 onwards and otherwise off
3905 // by default.
3906 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
3907 options::OPT_fno_aligned_allocation,
3908 options::OPT_faligned_new_EQ)) {
3909 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
3910 CmdArgs.push_back("-fno-aligned-allocation");
3911 else
3912 CmdArgs.push_back("-faligned-allocation");
3913 }
3914
3915 // The default new alignment can be specified using a dedicated option or via
3916 // a GCC-compatible option that also turns on aligned allocation.
3917 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
3918 options::OPT_faligned_new_EQ))
3919 CmdArgs.push_back(
3920 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
3921
3922 // -fconstant-cfstrings is default, and may be subject to argument translation
3923 // on Darwin.
3924 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
3925 options::OPT_fno_constant_cfstrings) ||
3926 !Args.hasFlag(options::OPT_mconstant_cfstrings,
3927 options::OPT_mno_constant_cfstrings))
3928 CmdArgs.push_back("-fno-constant-cfstrings");
3929
3930 // -fshort-wchar default varies depending on platform; only
3931 // pass if specified.
3932 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3933 options::OPT_fno_short_wchar))
3934 A->render(Args, CmdArgs);
3935
3936 // -fno-pascal-strings is default, only pass non-default.
3937 if (Args.hasFlag(options::OPT_fpascal_strings,
3938 options::OPT_fno_pascal_strings, false))
3939 CmdArgs.push_back("-fpascal-strings");
3940
3941 // Honor -fpack-struct= and -fpack-struct, if given. Note that
3942 // -fno-pack-struct doesn't apply to -fpack-struct=.
3943 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
3944 std::string PackStructStr = "-fpack-struct=";
3945 PackStructStr += A->getValue();
3946 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
3947 } else if (Args.hasFlag(options::OPT_fpack_struct,
3948 options::OPT_fno_pack_struct, false)) {
3949 CmdArgs.push_back("-fpack-struct=1");
3950 }
3951
3952 // Handle -fmax-type-align=N and -fno-type-align
3953 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
3954 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
3955 if (!SkipMaxTypeAlign) {
3956 std::string MaxTypeAlignStr = "-fmax-type-align=";
3957 MaxTypeAlignStr += A->getValue();
3958 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
3959 }
3960 } else if (getToolChain().getTriple().isOSDarwin()) {
3961 if (!SkipMaxTypeAlign) {
3962 std::string MaxTypeAlignStr = "-fmax-type-align=16";
3963 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
3964 }
3965 }
3966
3967 // -fcommon is the default unless compiling kernel code or the target says so
3968 bool NoCommonDefault =
3969 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
3970 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
3971 !NoCommonDefault))
3972 CmdArgs.push_back("-fno-common");
3973
3974 // -fsigned-bitfields is default, and clang doesn't yet support
3975 // -funsigned-bitfields.
3976 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
3977 options::OPT_funsigned_bitfields))
3978 D.Diag(diag::warn_drv_clang_unsupported)
3979 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
3980
3981 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
3982 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
3983 D.Diag(diag::err_drv_clang_unsupported)
3984 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
3985
3986 // -finput_charset=UTF-8 is default. Reject others
3987 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
3988 StringRef value = inputCharset->getValue();
3989 if (!value.equals_lower("utf-8"))
3990 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
3991 << value;
3992 }
3993
3994 // -fexec_charset=UTF-8 is default. Reject others
3995 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
3996 StringRef value = execCharset->getValue();
3997 if (!value.equals_lower("utf-8"))
3998 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
3999 << value;
4000 }
4001
4002 // -fcaret-diagnostics is default.
4003 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4004 options::OPT_fno_caret_diagnostics, true))
4005 CmdArgs.push_back("-fno-caret-diagnostics");
4006
4007 // -fdiagnostics-fixit-info is default, only pass non-default.
4008 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4009 options::OPT_fno_diagnostics_fixit_info))
4010 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4011
4012 // Enable -fdiagnostics-show-option by default.
4013 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4014 options::OPT_fno_diagnostics_show_option))
4015 CmdArgs.push_back("-fdiagnostics-show-option");
4016
4017 if (const Arg *A =
4018 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4019 CmdArgs.push_back("-fdiagnostics-show-category");
4020 CmdArgs.push_back(A->getValue());
4021 }
4022
4023 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
4024 options::OPT_fno_diagnostics_show_hotness, false))
4025 CmdArgs.push_back("-fdiagnostics-show-hotness");
4026
4027 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4028 CmdArgs.push_back("-fdiagnostics-format");
4029 CmdArgs.push_back(A->getValue());
4030 }
4031
4032 if (Arg *A = Args.getLastArg(
4033 options::OPT_fdiagnostics_show_note_include_stack,
4034 options::OPT_fno_diagnostics_show_note_include_stack)) {
4035 if (A->getOption().matches(
4036 options::OPT_fdiagnostics_show_note_include_stack))
4037 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4038 else
4039 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4040 }
4041
4042 // Color diagnostics are parsed by the driver directly from argv
4043 // and later re-parsed to construct this job; claim any possible
4044 // color diagnostic here to avoid warn_drv_unused_argument and
4045 // diagnose bad OPT_fdiagnostics_color_EQ values.
4046 for (Arg *A : Args) {
4047 const Option &O = A->getOption();
4048 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4049 !O.matches(options::OPT_fdiagnostics_color) &&
4050 !O.matches(options::OPT_fno_color_diagnostics) &&
4051 !O.matches(options::OPT_fno_diagnostics_color) &&
4052 !O.matches(options::OPT_fdiagnostics_color_EQ))
4053 continue;
4054 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
4055 StringRef Value(A->getValue());
4056 if (Value != "always" && Value != "never" && Value != "auto")
4057 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4058 << ("-fdiagnostics-color=" + Value).str();
4059 }
4060 A->claim();
4061 }
4062 if (D.getDiags().getDiagnosticOptions().ShowColors)
4063 CmdArgs.push_back("-fcolor-diagnostics");
4064
4065 if (Args.hasArg(options::OPT_fansi_escape_codes))
4066 CmdArgs.push_back("-fansi-escape-codes");
4067
4068 if (!Args.hasFlag(options::OPT_fshow_source_location,
4069 options::OPT_fno_show_source_location))
4070 CmdArgs.push_back("-fno-show-source-location");
4071
4072 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4073 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4074
4075 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4076 true))
4077 CmdArgs.push_back("-fno-show-column");
4078
4079 if (!Args.hasFlag(options::OPT_fspell_checking,
4080 options::OPT_fno_spell_checking))
4081 CmdArgs.push_back("-fno-spell-checking");
4082
4083 // -fno-asm-blocks is default.
4084 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4085 false))
4086 CmdArgs.push_back("-fasm-blocks");
4087
4088 // -fgnu-inline-asm is default.
4089 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4090 options::OPT_fno_gnu_inline_asm, true))
4091 CmdArgs.push_back("-fno-gnu-inline-asm");
4092
4093 // Enable vectorization per default according to the optimization level
4094 // selected. For optimization levels that want vectorization we use the alias
4095 // option to simplify the hasFlag logic.
4096 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4097 OptSpecifier VectorizeAliasOption =
4098 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4099 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4100 options::OPT_fno_vectorize, EnableVec))
4101 CmdArgs.push_back("-vectorize-loops");
4102
4103 // -fslp-vectorize is enabled based on the optimization level selected.
4104 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4105 OptSpecifier SLPVectAliasOption =
4106 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4107 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4108 options::OPT_fno_slp_vectorize, EnableSLPVec))
4109 CmdArgs.push_back("-vectorize-slp");
4110
4111 // -fno-slp-vectorize-aggressive is default.
4112 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4113 options::OPT_fno_slp_vectorize_aggressive, false))
4114 CmdArgs.push_back("-vectorize-slp-aggressive");
4115
4116 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4117 A->render(Args, CmdArgs);
4118
4119 if (Arg *A = Args.getLastArg(
4120 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4121 A->render(Args, CmdArgs);
4122
4123 // -fdollars-in-identifiers default varies depending on platform and
4124 // language; only pass if specified.
4125 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4126 options::OPT_fno_dollars_in_identifiers)) {
4127 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4128 CmdArgs.push_back("-fdollars-in-identifiers");
4129 else
4130 CmdArgs.push_back("-fno-dollars-in-identifiers");
4131 }
4132
4133 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4134 // practical purposes.
4135 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4136 options::OPT_fno_unit_at_a_time)) {
4137 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4138 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4139 }
4140
4141 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4142 options::OPT_fno_apple_pragma_pack, false))
4143 CmdArgs.push_back("-fapple-pragma-pack");
4144
4145 // le32-specific flags:
4146 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4147 // by default.
4148 if (getToolChain().getArch() == llvm::Triple::le32) {
4149 CmdArgs.push_back("-fno-math-builtin");
4150 }
4151
4152 if (Args.hasFlag(options::OPT_fsave_optimization_record,
4153 options::OPT_fno_save_optimization_record, false)) {
4154 CmdArgs.push_back("-opt-record-file");
4155
4156 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4157 if (A) {
4158 CmdArgs.push_back(A->getValue());
4159 } else {
4160 SmallString<128> F;
4161 if (Output.isFilename() && (Args.hasArg(options::OPT_c) ||
4162 Args.hasArg(options::OPT_S))) {
4163 F = Output.getFilename();
4164 } else {
4165 // Use the input filename.
4166 F = llvm::sys::path::stem(Input.getBaseInput());
4167
4168 // If we're compiling for an offload architecture (i.e. a CUDA device),
4169 // we need to make the file name for the device compilation different
4170 // from the host compilation.
4171 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4172 !JA.isDeviceOffloading(Action::OFK_Host)) {
4173 llvm::sys::path::replace_extension(F, "");
4174 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4175 Triple.normalize());
4176 F += "-";
4177 F += JA.getOffloadingArch();
4178 }
4179 }
4180
4181 llvm::sys::path::replace_extension(F, "opt.yaml");
4182 CmdArgs.push_back(Args.MakeArgString(F));
4183 }
4184 }
4185
4186// Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4187//
4188// FIXME: Now that PR4941 has been fixed this can be enabled.
4189#if 0
4190 if (getToolChain().getTriple().isOSDarwin() &&
4191 (getToolChain().getArch() == llvm::Triple::arm ||
4192 getToolChain().getArch() == llvm::Triple::thumb)) {
4193 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4194 CmdArgs.push_back("-fno-builtin-strcat");
4195 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4196 CmdArgs.push_back("-fno-builtin-strcpy");
4197 }
4198#endif
4199
4200 // Enable rewrite includes if the user's asked for it or if we're generating
4201 // diagnostics.
4202 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4203 // nice to enable this when doing a crashdump for modules as well.
4204 if (Args.hasFlag(options::OPT_frewrite_includes,
4205 options::OPT_fno_rewrite_includes, false) ||
4206 (C.isForDiagnostics() && !HaveAnyModules))
4207 CmdArgs.push_back("-frewrite-includes");
4208
4209 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4210 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4211 options::OPT_traditional_cpp)) {
4212 if (isa<PreprocessJobAction>(JA))
4213 CmdArgs.push_back("-traditional-cpp");
4214 else
4215 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4216 }
4217
4218 Args.AddLastArg(CmdArgs, options::OPT_dM);
4219 Args.AddLastArg(CmdArgs, options::OPT_dD);
4220
4221 // Handle serialized diagnostics.
4222 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4223 CmdArgs.push_back("-serialize-diagnostic-file");
4224 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4225 }
4226
4227 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4228 CmdArgs.push_back("-fretain-comments-from-system-headers");
4229
4230 // Forward -fcomment-block-commands to -cc1.
4231 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4232 // Forward -fparse-all-comments to -cc1.
4233 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4234
4235 // Turn -fplugin=name.so into -load name.so
4236 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4237 CmdArgs.push_back("-load");
4238 CmdArgs.push_back(A->getValue());
4239 A->claim();
4240 }
4241
4242 // Setup statistics file output.
4243 if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
4244 StringRef SaveStats = A->getValue();
4245
4246 SmallString<128> StatsFile;
4247 bool DoSaveStats = false;
4248 if (SaveStats == "obj") {
4249 if (Output.isFilename()) {
4250 StatsFile.assign(Output.getFilename());
4251 llvm::sys::path::remove_filename(StatsFile);
4252 }
4253 DoSaveStats = true;
4254 } else if (SaveStats == "cwd") {
4255 DoSaveStats = true;
4256 } else {
4257 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
4258 }
4259
4260 if (DoSaveStats) {
4261 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
4262 llvm::sys::path::append(StatsFile, BaseName);
4263 llvm::sys::path::replace_extension(StatsFile, "stats");
4264 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
4265 StatsFile));
4266 }
4267 }
4268
4269 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4270 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004271 // -finclude-default-header flag is for preprocessor,
4272 // do not pass it to other cc1 commands when save-temps is enabled
4273 if (C.getDriver().isSaveTempsEnabled() &&
4274 !isa<PreprocessJobAction>(JA)) {
4275 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4276 Arg->claim();
4277 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4278 CmdArgs.push_back(Arg->getValue());
4279 }
4280 }
4281 else {
4282 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4283 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004284 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4285 A->claim();
4286
4287 // We translate this by hand to the -cc1 argument, since nightly test uses
4288 // it and developers have been trained to spell it with -mllvm. Both
4289 // spellings are now deprecated and should be removed.
4290 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4291 CmdArgs.push_back("-disable-llvm-optzns");
4292 } else {
4293 A->render(Args, CmdArgs);
4294 }
4295 }
4296
4297 // With -save-temps, we want to save the unoptimized bitcode output from the
4298 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4299 // by the frontend.
4300 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4301 // has slightly different breakdown between stages.
4302 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4303 // pristine IR generated by the frontend. Ideally, a new compile action should
4304 // be added so both IR can be captured.
4305 if (C.getDriver().isSaveTempsEnabled() &&
4306 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4307 isa<CompileJobAction>(JA))
4308 CmdArgs.push_back("-disable-llvm-passes");
4309
4310 if (Output.getType() == types::TY_Dependencies) {
4311 // Handled with other dependency code.
4312 } else if (Output.isFilename()) {
4313 CmdArgs.push_back("-o");
4314 CmdArgs.push_back(Output.getFilename());
4315 } else {
4316 assert(Output.isNothing() && "Invalid output.");
4317 }
4318
4319 addDashXForInput(Args, Input, CmdArgs);
4320
4321 if (Input.isFilename())
4322 CmdArgs.push_back(Input.getFilename());
4323 else
4324 Input.getInputArg().renderAsInput(Args, CmdArgs);
4325
4326 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4327
4328 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4329
4330 // Optionally embed the -cc1 level arguments into the debug info, for build
4331 // analysis.
4332 if (getToolChain().UseDwarfDebugFlags()) {
4333 ArgStringList OriginalArgs;
4334 for (const auto &Arg : Args)
4335 Arg->render(Args, OriginalArgs);
4336
4337 SmallString<256> Flags;
4338 Flags += Exec;
4339 for (const char *OriginalArg : OriginalArgs) {
4340 SmallString<128> EscapedArg;
4341 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4342 Flags += " ";
4343 Flags += EscapedArg;
4344 }
4345 CmdArgs.push_back("-dwarf-debug-flags");
4346 CmdArgs.push_back(Args.MakeArgString(Flags));
4347 }
4348
4349 // Add the split debug info name to the command lines here so we
4350 // can propagate it to the backend.
4351 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
4352 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4353 isa<BackendJobAction>(JA));
4354 const char *SplitDwarfOut;
4355 if (SplitDwarf) {
4356 CmdArgs.push_back("-split-dwarf-file");
4357 SplitDwarfOut = SplitDebugName(Args, Input);
4358 CmdArgs.push_back(SplitDwarfOut);
4359 }
4360
4361 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4362 // Include them with -fcuda-include-gpubinary.
4363 if (IsCuda && Inputs.size() > 1)
4364 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
4365 CmdArgs.push_back("-fcuda-include-gpubinary");
4366 CmdArgs.push_back(I->getFilename());
4367 }
4368
4369 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4370 // to specify the result of the compile phase on the host, so the meaningful
4371 // device declarations can be identified. Also, -fopenmp-is-device is passed
4372 // along to tell the frontend that it is generating code for a device, so that
4373 // only the relevant declarations are emitted.
4374 if (IsOpenMPDevice && Inputs.size() == 2) {
4375 CmdArgs.push_back("-fopenmp-is-device");
4376 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4377 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4378 }
4379
4380 // For all the host OpenMP offloading compile jobs we need to pass the targets
4381 // information using -fopenmp-targets= option.
4382 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4383 SmallString<128> TargetInfo("-fopenmp-targets=");
4384
4385 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4386 assert(Tgts && Tgts->getNumValues() &&
4387 "OpenMP offloading has to have targets specified.");
4388 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4389 if (i)
4390 TargetInfo += ',';
4391 // We need to get the string from the triple because it may be not exactly
4392 // the same as the one we get directly from the arguments.
4393 llvm::Triple T(Tgts->getValue(i));
4394 TargetInfo += T.getTriple();
4395 }
4396 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4397 }
4398
4399 bool WholeProgramVTables =
4400 Args.hasFlag(options::OPT_fwhole_program_vtables,
4401 options::OPT_fno_whole_program_vtables, false);
4402 if (WholeProgramVTables) {
4403 if (!D.isUsingLTO())
4404 D.Diag(diag::err_drv_argument_only_allowed_with)
4405 << "-fwhole-program-vtables"
4406 << "-flto";
4407 CmdArgs.push_back("-fwhole-program-vtables");
4408 }
4409
4410 // Finally add the compile command to the compilation.
4411 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4412 Output.getType() == types::TY_Object &&
4413 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4414 auto CLCommand =
4415 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4416 C.addCommand(llvm::make_unique<FallbackCommand>(
4417 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4418 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4419 isa<PrecompileJobAction>(JA)) {
4420 // In /fallback builds, run the main compilation even if the pch generation
4421 // fails, so that the main compilation's fallback to cl.exe runs.
4422 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4423 CmdArgs, Inputs));
4424 } else {
4425 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4426 }
4427
4428 // Handle the debug info splitting at object creation time if we're
4429 // creating an object.
4430 // TODO: Currently only works on linux with newer objcopy.
4431 if (SplitDwarf && Output.getType() == types::TY_Object)
4432 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4433
4434 if (Arg *A = Args.getLastArg(options::OPT_pg))
4435 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4436 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4437 << A->getAsString(Args);
4438
4439 // Claim some arguments which clang supports automatically.
4440
4441 // -fpch-preprocess is used with gcc to add a special marker in the output to
4442 // include the PCH file. Clang's PTH solution is completely transparent, so we
4443 // do not need to deal with it at all.
4444 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4445
4446 // Claim some arguments which clang doesn't support, but we don't
4447 // care to warn the user about.
4448 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4449 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4450
4451 // Disable warnings for clang -E -emit-llvm foo.c
4452 Args.ClaimAllArgs(options::OPT_emit_llvm);
4453}
4454
4455Clang::Clang(const ToolChain &TC)
4456 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4457 // as it is for other tools. Some operations on a Tool actually test
4458 // whether that tool is Clang based on the Tool's Name as a string.
4459 : Tool("clang", "clang frontend", TC, RF_Full) {}
4460
4461Clang::~Clang() {}
4462
4463/// Add options related to the Objective-C runtime/ABI.
4464///
4465/// Returns true if the runtime is non-fragile.
4466ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4467 ArgStringList &cmdArgs,
4468 RewriteKind rewriteKind) const {
4469 // Look for the controlling runtime option.
4470 Arg *runtimeArg =
4471 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4472 options::OPT_fobjc_runtime_EQ);
4473
4474 // Just forward -fobjc-runtime= to the frontend. This supercedes
4475 // options about fragility.
4476 if (runtimeArg &&
4477 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4478 ObjCRuntime runtime;
4479 StringRef value = runtimeArg->getValue();
4480 if (runtime.tryParse(value)) {
4481 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4482 << value;
4483 }
4484
4485 runtimeArg->render(args, cmdArgs);
4486 return runtime;
4487 }
4488
4489 // Otherwise, we'll need the ABI "version". Version numbers are
4490 // slightly confusing for historical reasons:
4491 // 1 - Traditional "fragile" ABI
4492 // 2 - Non-fragile ABI, version 1
4493 // 3 - Non-fragile ABI, version 2
4494 unsigned objcABIVersion = 1;
4495 // If -fobjc-abi-version= is present, use that to set the version.
4496 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4497 StringRef value = abiArg->getValue();
4498 if (value == "1")
4499 objcABIVersion = 1;
4500 else if (value == "2")
4501 objcABIVersion = 2;
4502 else if (value == "3")
4503 objcABIVersion = 3;
4504 else
4505 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4506 } else {
4507 // Otherwise, determine if we are using the non-fragile ABI.
4508 bool nonFragileABIIsDefault =
4509 (rewriteKind == RK_NonFragile ||
4510 (rewriteKind == RK_None &&
4511 getToolChain().IsObjCNonFragileABIDefault()));
4512 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4513 options::OPT_fno_objc_nonfragile_abi,
4514 nonFragileABIIsDefault)) {
4515// Determine the non-fragile ABI version to use.
4516#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4517 unsigned nonFragileABIVersion = 1;
4518#else
4519 unsigned nonFragileABIVersion = 2;
4520#endif
4521
4522 if (Arg *abiArg =
4523 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4524 StringRef value = abiArg->getValue();
4525 if (value == "1")
4526 nonFragileABIVersion = 1;
4527 else if (value == "2")
4528 nonFragileABIVersion = 2;
4529 else
4530 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4531 << value;
4532 }
4533
4534 objcABIVersion = 1 + nonFragileABIVersion;
4535 } else {
4536 objcABIVersion = 1;
4537 }
4538 }
4539
4540 // We don't actually care about the ABI version other than whether
4541 // it's non-fragile.
4542 bool isNonFragile = objcABIVersion != 1;
4543
4544 // If we have no runtime argument, ask the toolchain for its default runtime.
4545 // However, the rewriter only really supports the Mac runtime, so assume that.
4546 ObjCRuntime runtime;
4547 if (!runtimeArg) {
4548 switch (rewriteKind) {
4549 case RK_None:
4550 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4551 break;
4552 case RK_Fragile:
4553 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4554 break;
4555 case RK_NonFragile:
4556 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4557 break;
4558 }
4559
4560 // -fnext-runtime
4561 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4562 // On Darwin, make this use the default behavior for the toolchain.
4563 if (getToolChain().getTriple().isOSDarwin()) {
4564 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4565
4566 // Otherwise, build for a generic macosx port.
4567 } else {
4568 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4569 }
4570
4571 // -fgnu-runtime
4572 } else {
4573 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4574 // Legacy behaviour is to target the gnustep runtime if we are in
4575 // non-fragile mode or the GCC runtime in fragile mode.
4576 if (isNonFragile)
4577 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4578 else
4579 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4580 }
4581
4582 cmdArgs.push_back(
4583 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4584 return runtime;
4585}
4586
4587static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4588 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4589 I += HaveDash;
4590 return !HaveDash;
4591}
4592
4593namespace {
4594struct EHFlags {
4595 bool Synch = false;
4596 bool Asynch = false;
4597 bool NoUnwindC = false;
4598};
4599} // end anonymous namespace
4600
4601/// /EH controls whether to run destructor cleanups when exceptions are
4602/// thrown. There are three modifiers:
4603/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4604/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4605/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4606/// - c: Assume that extern "C" functions are implicitly nounwind.
4607/// The default is /EHs-c-, meaning cleanups are disabled.
4608static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4609 EHFlags EH;
4610
4611 std::vector<std::string> EHArgs =
4612 Args.getAllArgValues(options::OPT__SLASH_EH);
4613 for (auto EHVal : EHArgs) {
4614 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4615 switch (EHVal[I]) {
4616 case 'a':
4617 EH.Asynch = maybeConsumeDash(EHVal, I);
4618 if (EH.Asynch)
4619 EH.Synch = false;
4620 continue;
4621 case 'c':
4622 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
4623 continue;
4624 case 's':
4625 EH.Synch = maybeConsumeDash(EHVal, I);
4626 if (EH.Synch)
4627 EH.Asynch = false;
4628 continue;
4629 default:
4630 break;
4631 }
4632 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4633 break;
4634 }
4635 }
4636 // The /GX, /GX- flags are only processed if there are not /EH flags.
4637 // The default is that /GX is not specified.
4638 if (EHArgs.empty() &&
4639 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
4640 /*default=*/false)) {
4641 EH.Synch = true;
4642 EH.NoUnwindC = true;
4643 }
4644
4645 return EH;
4646}
4647
4648void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
4649 ArgStringList &CmdArgs,
4650 codegenoptions::DebugInfoKind *DebugInfoKind,
4651 bool *EmitCodeView) const {
4652 unsigned RTOptionID = options::OPT__SLASH_MT;
4653
4654 if (Args.hasArg(options::OPT__SLASH_LDd))
4655 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4656 // but defining _DEBUG is sticky.
4657 RTOptionID = options::OPT__SLASH_MTd;
4658
4659 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4660 RTOptionID = A->getOption().getID();
4661
4662 StringRef FlagForCRT;
4663 switch (RTOptionID) {
4664 case options::OPT__SLASH_MD:
4665 if (Args.hasArg(options::OPT__SLASH_LDd))
4666 CmdArgs.push_back("-D_DEBUG");
4667 CmdArgs.push_back("-D_MT");
4668 CmdArgs.push_back("-D_DLL");
4669 FlagForCRT = "--dependent-lib=msvcrt";
4670 break;
4671 case options::OPT__SLASH_MDd:
4672 CmdArgs.push_back("-D_DEBUG");
4673 CmdArgs.push_back("-D_MT");
4674 CmdArgs.push_back("-D_DLL");
4675 FlagForCRT = "--dependent-lib=msvcrtd";
4676 break;
4677 case options::OPT__SLASH_MT:
4678 if (Args.hasArg(options::OPT__SLASH_LDd))
4679 CmdArgs.push_back("-D_DEBUG");
4680 CmdArgs.push_back("-D_MT");
4681 CmdArgs.push_back("-flto-visibility-public-std");
4682 FlagForCRT = "--dependent-lib=libcmt";
4683 break;
4684 case options::OPT__SLASH_MTd:
4685 CmdArgs.push_back("-D_DEBUG");
4686 CmdArgs.push_back("-D_MT");
4687 CmdArgs.push_back("-flto-visibility-public-std");
4688 FlagForCRT = "--dependent-lib=libcmtd";
4689 break;
4690 default:
4691 llvm_unreachable("Unexpected option ID.");
4692 }
4693
4694 if (Args.hasArg(options::OPT__SLASH_Zl)) {
4695 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4696 } else {
4697 CmdArgs.push_back(FlagForCRT.data());
4698
4699 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4700 // users want. The /Za flag to cl.exe turns this off, but it's not
4701 // implemented in clang.
4702 CmdArgs.push_back("--dependent-lib=oldnames");
4703 }
4704
4705 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4706 // would produce interleaved output, so ignore /showIncludes in such cases.
4707 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
4708 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4709 A->render(Args, CmdArgs);
4710
4711 // This controls whether or not we emit RTTI data for polymorphic types.
4712 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4713 /*default=*/false))
4714 CmdArgs.push_back("-fno-rtti-data");
4715
4716 // This controls whether or not we emit stack-protector instrumentation.
4717 // In MSVC, Buffer Security Check (/GS) is on by default.
4718 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
4719 /*default=*/true)) {
4720 CmdArgs.push_back("-stack-protector");
4721 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
4722 }
4723
4724 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
4725 if (Arg *DebugInfoArg =
4726 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
4727 options::OPT_gline_tables_only)) {
4728 *EmitCodeView = true;
4729 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
4730 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
4731 else
4732 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4733 CmdArgs.push_back("-gcodeview");
4734 } else {
4735 *EmitCodeView = false;
4736 }
4737
4738 const Driver &D = getToolChain().getDriver();
4739 EHFlags EH = parseClangCLEHFlags(D, Args);
4740 if (EH.Synch || EH.Asynch) {
4741 if (types::isCXX(InputType))
4742 CmdArgs.push_back("-fcxx-exceptions");
4743 CmdArgs.push_back("-fexceptions");
4744 }
4745 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
4746 CmdArgs.push_back("-fexternc-nounwind");
4747
4748 // /EP should expand to -E -P.
4749 if (Args.hasArg(options::OPT__SLASH_EP)) {
4750 CmdArgs.push_back("-E");
4751 CmdArgs.push_back("-P");
4752 }
4753
4754 unsigned VolatileOptionID;
4755 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
4756 getToolChain().getArch() == llvm::Triple::x86)
4757 VolatileOptionID = options::OPT__SLASH_volatile_ms;
4758 else
4759 VolatileOptionID = options::OPT__SLASH_volatile_iso;
4760
4761 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
4762 VolatileOptionID = A->getOption().getID();
4763
4764 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
4765 CmdArgs.push_back("-fms-volatile");
4766
4767 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
4768 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
4769 if (MostGeneralArg && BestCaseArg)
4770 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4771 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
4772
4773 if (MostGeneralArg) {
4774 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
4775 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
4776 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
4777
4778 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
4779 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
4780 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
4781 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4782 << FirstConflict->getAsString(Args)
4783 << SecondConflict->getAsString(Args);
4784
4785 if (SingleArg)
4786 CmdArgs.push_back("-fms-memptr-rep=single");
4787 else if (MultipleArg)
4788 CmdArgs.push_back("-fms-memptr-rep=multiple");
4789 else
4790 CmdArgs.push_back("-fms-memptr-rep=virtual");
4791 }
4792
4793 if (Args.getLastArg(options::OPT__SLASH_Gd))
4794 CmdArgs.push_back("-fdefault-calling-conv=cdecl");
4795 else if (Args.getLastArg(options::OPT__SLASH_Gr))
4796 CmdArgs.push_back("-fdefault-calling-conv=fastcall");
4797 else if (Args.getLastArg(options::OPT__SLASH_Gz))
4798 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4799 else if (Args.getLastArg(options::OPT__SLASH_Gv))
4800 CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
4801
4802 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
4803 A->render(Args, CmdArgs);
4804
4805 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
4806 CmdArgs.push_back("-fdiagnostics-format");
4807 if (Args.hasArg(options::OPT__SLASH_fallback))
4808 CmdArgs.push_back("msvc-fallback");
4809 else
4810 CmdArgs.push_back("msvc");
4811 }
4812}
4813
4814visualstudio::Compiler *Clang::getCLFallback() const {
4815 if (!CLFallback)
4816 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
4817 return CLFallback.get();
4818}
4819
4820
4821const char *Clang::getBaseInputName(const ArgList &Args,
4822 const InputInfo &Input) {
4823 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
4824}
4825
4826const char *Clang::getBaseInputStem(const ArgList &Args,
4827 const InputInfoList &Inputs) {
4828 const char *Str = getBaseInputName(Args, Inputs[0]);
4829
4830 if (const char *End = strrchr(Str, '.'))
4831 return Args.MakeArgString(std::string(Str, End));
4832
4833 return Str;
4834}
4835
4836const char *Clang::getDependencyFileName(const ArgList &Args,
4837 const InputInfoList &Inputs) {
4838 // FIXME: Think about this more.
4839 std::string Res;
4840
4841 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4842 std::string Str(OutputOpt->getValue());
4843 Res = Str.substr(0, Str.rfind('.'));
4844 } else {
4845 Res = getBaseInputStem(Args, Inputs);
4846 }
4847 return Args.MakeArgString(Res + ".d");
4848}
4849
4850// Begin ClangAs
4851
4852void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
4853 ArgStringList &CmdArgs) const {
4854 StringRef CPUName;
4855 StringRef ABIName;
4856 const llvm::Triple &Triple = getToolChain().getTriple();
4857 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
4858
4859 CmdArgs.push_back("-target-abi");
4860 CmdArgs.push_back(ABIName.data());
4861}
4862
4863void ClangAs::AddX86TargetArgs(const ArgList &Args,
4864 ArgStringList &CmdArgs) const {
4865 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
4866 StringRef Value = A->getValue();
4867 if (Value == "intel" || Value == "att") {
4868 CmdArgs.push_back("-mllvm");
4869 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
4870 } else {
4871 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
4872 << A->getOption().getName() << Value;
4873 }
4874 }
4875}
4876
4877void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
4878 const InputInfo &Output, const InputInfoList &Inputs,
4879 const ArgList &Args,
4880 const char *LinkingOutput) const {
4881 ArgStringList CmdArgs;
4882
4883 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4884 const InputInfo &Input = Inputs[0];
4885
4886 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
4887 const std::string &TripleStr = Triple.getTriple();
4888
4889 // Don't warn about "clang -w -c foo.s"
4890 Args.ClaimAllArgs(options::OPT_w);
4891 // and "clang -emit-llvm -c foo.s"
4892 Args.ClaimAllArgs(options::OPT_emit_llvm);
4893
4894 claimNoWarnArgs(Args);
4895
4896 // Invoke ourselves in -cc1as mode.
4897 //
4898 // FIXME: Implement custom jobs for internal actions.
4899 CmdArgs.push_back("-cc1as");
4900
4901 // Add the "effective" target triple.
4902 CmdArgs.push_back("-triple");
4903 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4904
4905 // Set the output mode, we currently only expect to be used as a real
4906 // assembler.
4907 CmdArgs.push_back("-filetype");
4908 CmdArgs.push_back("obj");
4909
4910 // Set the main file name, so that debug info works even with
4911 // -save-temps or preprocessed assembly.
4912 CmdArgs.push_back("-main-file-name");
4913 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
4914
4915 // Add the target cpu
4916 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
4917 if (!CPU.empty()) {
4918 CmdArgs.push_back("-target-cpu");
4919 CmdArgs.push_back(Args.MakeArgString(CPU));
4920 }
4921
4922 // Add the target features
4923 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
4924
4925 // Ignore explicit -force_cpusubtype_ALL option.
4926 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4927
4928 // Pass along any -I options so we get proper .include search paths.
4929 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
4930
4931 // Determine the original source input.
4932 const Action *SourceAction = &JA;
4933 while (SourceAction->getKind() != Action::InputClass) {
4934 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4935 SourceAction = SourceAction->getInputs()[0];
4936 }
4937
4938 // Forward -g and handle debug info related flags, assuming we are dealing
4939 // with an actual assembly file.
4940 bool WantDebug = false;
4941 unsigned DwarfVersion = 0;
4942 Args.ClaimAllArgs(options::OPT_g_Group);
4943 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4944 WantDebug = !A->getOption().matches(options::OPT_g0) &&
4945 !A->getOption().matches(options::OPT_ggdb0);
4946 if (WantDebug)
4947 DwarfVersion = DwarfVersionNum(A->getSpelling());
4948 }
4949 if (DwarfVersion == 0)
4950 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4951
4952 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4953
4954 if (SourceAction->getType() == types::TY_Asm ||
4955 SourceAction->getType() == types::TY_PP_Asm) {
4956 // You might think that it would be ok to set DebugInfoKind outside of
4957 // the guard for source type, however there is a test which asserts
4958 // that some assembler invocation receives no -debug-info-kind,
4959 // and it's not clear whether that test is just overly restrictive.
4960 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
4961 : codegenoptions::NoDebugInfo);
4962 // Add the -fdebug-compilation-dir flag if needed.
4963 addDebugCompDirArg(Args, CmdArgs);
4964
4965 // Set the AT_producer to the clang version when using the integrated
4966 // assembler on assembly source files.
4967 CmdArgs.push_back("-dwarf-debug-producer");
4968 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
4969
4970 // And pass along -I options
4971 Args.AddAllArgs(CmdArgs, options::OPT_I);
4972 }
4973 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4974 llvm::DebuggerKind::Default);
4975
4976 // Handle -fPIC et al -- the relocation-model affects the assembler
4977 // for some targets.
4978 llvm::Reloc::Model RelocationModel;
4979 unsigned PICLevel;
4980 bool IsPIE;
4981 std::tie(RelocationModel, PICLevel, IsPIE) =
4982 ParsePICArgs(getToolChain(), Args);
4983
4984 const char *RMName = RelocationModelName(RelocationModel);
4985 if (RMName) {
4986 CmdArgs.push_back("-mrelocation-model");
4987 CmdArgs.push_back(RMName);
4988 }
4989
4990 // Optionally embed the -cc1as level arguments into the debug info, for build
4991 // analysis.
4992 if (getToolChain().UseDwarfDebugFlags()) {
4993 ArgStringList OriginalArgs;
4994 for (const auto &Arg : Args)
4995 Arg->render(Args, OriginalArgs);
4996
4997 SmallString<256> Flags;
4998 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4999 Flags += Exec;
5000 for (const char *OriginalArg : OriginalArgs) {
5001 SmallString<128> EscapedArg;
5002 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5003 Flags += " ";
5004 Flags += EscapedArg;
5005 }
5006 CmdArgs.push_back("-dwarf-debug-flags");
5007 CmdArgs.push_back(Args.MakeArgString(Flags));
5008 }
5009
5010 // FIXME: Add -static support, once we have it.
5011
5012 // Add target specific flags.
5013 switch (getToolChain().getArch()) {
5014 default:
5015 break;
5016
5017 case llvm::Triple::mips:
5018 case llvm::Triple::mipsel:
5019 case llvm::Triple::mips64:
5020 case llvm::Triple::mips64el:
5021 AddMIPSTargetArgs(Args, CmdArgs);
5022 break;
5023
5024 case llvm::Triple::x86:
5025 case llvm::Triple::x86_64:
5026 AddX86TargetArgs(Args, CmdArgs);
5027 break;
5028 }
5029
5030 // Consume all the warning flags. Usually this would be handled more
5031 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5032 // doesn't handle that so rather than warning about unused flags that are
5033 // actually used, we'll lie by omission instead.
5034 // FIXME: Stop lying and consume only the appropriate driver flags
5035 Args.ClaimAllArgs(options::OPT_W_Group);
5036
5037 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5038 getToolChain().getDriver());
5039
5040 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5041
5042 assert(Output.isFilename() && "Unexpected lipo output.");
5043 CmdArgs.push_back("-o");
5044 CmdArgs.push_back(Output.getFilename());
5045
5046 assert(Input.isFilename() && "Invalid input.");
5047 CmdArgs.push_back(Input.getFilename());
5048
5049 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5050 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5051
5052 // Handle the debug info splitting at object creation time if we're
5053 // creating an object.
5054 // TODO: Currently only works on linux with newer objcopy.
5055 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5056 getToolChain().getTriple().isOSLinux())
5057 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5058 SplitDebugName(Args, Input));
5059}
5060
5061// Begin OffloadBundler
5062
5063void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5064 const InputInfo &Output,
5065 const InputInfoList &Inputs,
5066 const llvm::opt::ArgList &TCArgs,
5067 const char *LinkingOutput) const {
5068 // The version with only one output is expected to refer to a bundling job.
5069 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5070
5071 // The bundling command looks like this:
5072 // clang-offload-bundler -type=bc
5073 // -targets=host-triple,openmp-triple1,openmp-triple2
5074 // -outputs=input_file
5075 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5076
5077 ArgStringList CmdArgs;
5078
5079 // Get the type.
5080 CmdArgs.push_back(TCArgs.MakeArgString(
5081 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5082
5083 assert(JA.getInputs().size() == Inputs.size() &&
5084 "Not have inputs for all dependence actions??");
5085
5086 // Get the targets.
5087 SmallString<128> Triples;
5088 Triples += "-targets=";
5089 for (unsigned I = 0; I < Inputs.size(); ++I) {
5090 if (I)
5091 Triples += ',';
5092
5093 Action::OffloadKind CurKind = Action::OFK_Host;
5094 const ToolChain *CurTC = &getToolChain();
5095 const Action *CurDep = JA.getInputs()[I];
5096
5097 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
5098 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
5099 CurKind = A->getOffloadingDeviceKind();
5100 CurTC = TC;
5101 });
5102 }
5103 Triples += Action::GetOffloadKindName(CurKind);
5104 Triples += '-';
5105 Triples += CurTC->getTriple().normalize();
5106 }
5107 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5108
5109 // Get bundled file command.
5110 CmdArgs.push_back(
5111 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5112
5113 // Get unbundled files command.
5114 SmallString<128> UB;
5115 UB += "-inputs=";
5116 for (unsigned I = 0; I < Inputs.size(); ++I) {
5117 if (I)
5118 UB += ',';
5119 UB += Inputs[I].getFilename();
5120 }
5121 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5122
5123 // All the inputs are encoded as commands.
5124 C.addCommand(llvm::make_unique<Command>(
5125 JA, *this,
5126 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5127 CmdArgs, None));
5128}
5129
5130void OffloadBundler::ConstructJobMultipleOutputs(
5131 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5132 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5133 const char *LinkingOutput) const {
5134 // The version with multiple outputs is expected to refer to a unbundling job.
5135 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5136
5137 // The unbundling command looks like this:
5138 // clang-offload-bundler -type=bc
5139 // -targets=host-triple,openmp-triple1,openmp-triple2
5140 // -inputs=input_file
5141 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5142 // -unbundle
5143
5144 ArgStringList CmdArgs;
5145
5146 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5147 InputInfo Input = Inputs.front();
5148
5149 // Get the type.
5150 CmdArgs.push_back(TCArgs.MakeArgString(
5151 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5152
5153 // Get the targets.
5154 SmallString<128> Triples;
5155 Triples += "-targets=";
5156 auto DepInfo = UA.getDependentActionsInfo();
5157 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5158 if (I)
5159 Triples += ',';
5160
5161 auto &Dep = DepInfo[I];
5162 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5163 Triples += '-';
5164 Triples += Dep.DependentToolChain->getTriple().normalize();
5165 }
5166
5167 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5168
5169 // Get bundled file command.
5170 CmdArgs.push_back(
5171 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5172
5173 // Get unbundled files command.
5174 SmallString<128> UB;
5175 UB += "-outputs=";
5176 for (unsigned I = 0; I < Outputs.size(); ++I) {
5177 if (I)
5178 UB += ',';
5179 UB += Outputs[I].getFilename();
5180 }
5181 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5182 CmdArgs.push_back("-unbundle");
5183
5184 // All the inputs are encoded as commands.
5185 C.addCommand(llvm::make_unique<Command>(
5186 JA, *this,
5187 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5188 CmdArgs, None));
5189}