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