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