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