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