blob: c72c69d144991e20ba25e5899f46ea4c5c5ede01 [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"
David L. Jonesf561aba2017-03-08 01:02:16 +000028#include "clang/Driver/DriverDiagnostic.h"
29#include "clang/Driver/Options.h"
30#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000031#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000032#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000033#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000034#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;
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000532 case llvm::Triple::riscv32:
533 case llvm::Triple::riscv64:
534 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000535 default:
536 break;
537 }
538
539 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
540 switch (Triple.getArch()) {
541 // Don't use a frame pointer on linux if optimizing for certain targets.
542 case llvm::Triple::mips64:
543 case llvm::Triple::mips64el:
544 case llvm::Triple::mips:
545 case llvm::Triple::mipsel:
546 case llvm::Triple::ppc:
547 case llvm::Triple::ppc64:
548 case llvm::Triple::ppc64le:
549 case llvm::Triple::systemz:
550 case llvm::Triple::x86:
551 case llvm::Triple::x86_64:
552 return !areOptimizationsEnabled(Args);
553 default:
554 return true;
555 }
556 }
557
558 if (Triple.isOSWindows()) {
559 switch (Triple.getArch()) {
560 case llvm::Triple::x86:
561 return !areOptimizationsEnabled(Args);
562 case llvm::Triple::x86_64:
563 return Triple.isOSBinFormatMachO();
564 case llvm::Triple::arm:
565 case llvm::Triple::thumb:
566 // Windows on ARM builds with FPO disabled to aid fast stack walking
567 return true;
568 default:
569 // All other supported Windows ISAs use xdata unwind information, so frame
570 // pointers are not generally useful.
571 return false;
572 }
573 }
574
575 return true;
576}
577
578static bool shouldUseFramePointer(const ArgList &Args,
579 const llvm::Triple &Triple) {
580 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
581 options::OPT_fomit_frame_pointer))
582 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
583 mustUseNonLeafFramePointerForTarget(Triple);
584
585 if (Args.hasArg(options::OPT_pg))
586 return true;
587
588 return useFramePointerForTargetByDefault(Args, Triple);
589}
590
591static bool shouldUseLeafFramePointer(const ArgList &Args,
592 const llvm::Triple &Triple) {
593 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
594 options::OPT_momit_leaf_frame_pointer))
595 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
596
597 if (Args.hasArg(options::OPT_pg))
598 return true;
599
600 if (Triple.isPS4CPU())
601 return false;
602
603 return useFramePointerForTargetByDefault(Args, Triple);
604}
605
606/// Add a CC1 option to specify the debug compilation directory.
607static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
608 SmallString<128> cwd;
609 if (!llvm::sys::fs::current_path(cwd)) {
610 CmdArgs.push_back("-fdebug-compilation-dir");
611 CmdArgs.push_back(Args.MakeArgString(cwd));
612 }
613}
614
615/// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
616/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
617static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
618 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
619 if (A->getOption().matches(options::OPT_O4) ||
620 A->getOption().matches(options::OPT_Ofast))
621 return true;
622
623 if (A->getOption().matches(options::OPT_O0))
624 return false;
625
626 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
627
628 // Vectorize -Os.
629 StringRef S(A->getValue());
630 if (S == "s")
631 return true;
632
633 // Don't vectorize -Oz, unless it's the slp vectorizer.
634 if (S == "z")
635 return isSlpVec;
636
637 unsigned OptLevel = 0;
638 if (S.getAsInteger(10, OptLevel))
639 return false;
640
641 return OptLevel > 1;
642 }
643
644 return false;
645}
646
647/// Add -x lang to \p CmdArgs for \p Input.
648static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
649 ArgStringList &CmdArgs) {
650 // When using -verify-pch, we don't want to provide the type
651 // 'precompiled-header' if it was inferred from the file extension
652 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
653 return;
654
655 CmdArgs.push_back("-x");
656 if (Args.hasArg(options::OPT_rewrite_objc))
657 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000658 else {
659 // Map the driver type to the frontend type. This is mostly an identity
660 // mapping, except that the distinction between module interface units
661 // and other source files does not exist at the frontend layer.
662 const char *ClangType;
663 switch (Input.getType()) {
664 case types::TY_CXXModule:
665 ClangType = "c++";
666 break;
667 case types::TY_PP_CXXModule:
668 ClangType = "c++-cpp-output";
669 break;
670 default:
671 ClangType = types::getTypeName(Input.getType());
672 break;
673 }
674 CmdArgs.push_back(ClangType);
675 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000676}
677
678static void appendUserToPath(SmallVectorImpl<char> &Result) {
679#ifdef LLVM_ON_UNIX
680 const char *Username = getenv("LOGNAME");
681#else
682 const char *Username = getenv("USERNAME");
683#endif
684 if (Username) {
685 // Validate that LoginName can be used in a path, and get its length.
686 size_t Len = 0;
687 for (const char *P = Username; *P; ++P, ++Len) {
688 if (!clang::isAlphanumeric(*P) && *P != '_') {
689 Username = nullptr;
690 break;
691 }
692 }
693
694 if (Username && Len > 0) {
695 Result.append(Username, Username + Len);
696 return;
697 }
698 }
699
700// Fallback to user id.
701#ifdef LLVM_ON_UNIX
702 std::string UID = llvm::utostr(getuid());
703#else
704 // FIXME: Windows seems to have an 'SID' that might work.
705 std::string UID = "9999";
706#endif
707 Result.append(UID.begin(), UID.end());
708}
709
710static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
711 const InputInfo &Output, const ArgList &Args,
712 ArgStringList &CmdArgs) {
713
714 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
715 options::OPT_fprofile_generate_EQ,
716 options::OPT_fno_profile_generate);
717 if (PGOGenerateArg &&
718 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
719 PGOGenerateArg = nullptr;
720
721 auto *ProfileGenerateArg = Args.getLastArg(
722 options::OPT_fprofile_instr_generate,
723 options::OPT_fprofile_instr_generate_EQ,
724 options::OPT_fno_profile_instr_generate);
725 if (ProfileGenerateArg &&
726 ProfileGenerateArg->getOption().matches(
727 options::OPT_fno_profile_instr_generate))
728 ProfileGenerateArg = nullptr;
729
730 if (PGOGenerateArg && ProfileGenerateArg)
731 D.Diag(diag::err_drv_argument_not_allowed_with)
732 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
733
734 auto *ProfileUseArg = getLastProfileUseArg(Args);
735
736 if (PGOGenerateArg && ProfileUseArg)
737 D.Diag(diag::err_drv_argument_not_allowed_with)
738 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
739
740 if (ProfileGenerateArg && ProfileUseArg)
741 D.Diag(diag::err_drv_argument_not_allowed_with)
742 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
743
744 if (ProfileGenerateArg) {
745 if (ProfileGenerateArg->getOption().matches(
746 options::OPT_fprofile_instr_generate_EQ))
747 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
748 ProfileGenerateArg->getValue()));
749 // The default is to use Clang Instrumentation.
750 CmdArgs.push_back("-fprofile-instrument=clang");
751 }
752
753 if (PGOGenerateArg) {
754 CmdArgs.push_back("-fprofile-instrument=llvm");
755 if (PGOGenerateArg->getOption().matches(
756 options::OPT_fprofile_generate_EQ)) {
757 SmallString<128> Path(PGOGenerateArg->getValue());
758 llvm::sys::path::append(Path, "default_%m.profraw");
759 CmdArgs.push_back(
760 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
761 }
762 }
763
764 if (ProfileUseArg) {
765 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
766 CmdArgs.push_back(Args.MakeArgString(
767 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
768 else if ((ProfileUseArg->getOption().matches(
769 options::OPT_fprofile_use_EQ) ||
770 ProfileUseArg->getOption().matches(
771 options::OPT_fprofile_instr_use))) {
772 SmallString<128> Path(
773 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
774 if (Path.empty() || llvm::sys::fs::is_directory(Path))
775 llvm::sys::path::append(Path, "default.profdata");
776 CmdArgs.push_back(
777 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
778 }
779 }
780
781 if (Args.hasArg(options::OPT_ftest_coverage) ||
782 Args.hasArg(options::OPT_coverage))
783 CmdArgs.push_back("-femit-coverage-notes");
784 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
785 false) ||
786 Args.hasArg(options::OPT_coverage))
787 CmdArgs.push_back("-femit-coverage-data");
788
789 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000790 options::OPT_fno_coverage_mapping, false)) {
791 if (!ProfileGenerateArg)
792 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
793 << "-fcoverage-mapping"
794 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000795
David L. Jonesf561aba2017-03-08 01:02:16 +0000796 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000797 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000798
799 if (C.getArgs().hasArg(options::OPT_c) ||
800 C.getArgs().hasArg(options::OPT_S)) {
801 if (Output.isFilename()) {
802 CmdArgs.push_back("-coverage-notes-file");
803 SmallString<128> OutputFilename;
804 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
805 OutputFilename = FinalOutput->getValue();
806 else
807 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
808 SmallString<128> CoverageFilename = OutputFilename;
809 if (llvm::sys::path::is_relative(CoverageFilename)) {
810 SmallString<128> Pwd;
811 if (!llvm::sys::fs::current_path(Pwd)) {
812 llvm::sys::path::append(Pwd, CoverageFilename);
813 CoverageFilename.swap(Pwd);
814 }
815 }
816 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
817 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
818
819 // Leave -fprofile-dir= an unused argument unless .gcda emission is
820 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
821 // the flag used. There is no -fno-profile-dir, so the user has no
822 // targeted way to suppress the warning.
823 if (Args.hasArg(options::OPT_fprofile_arcs) ||
824 Args.hasArg(options::OPT_coverage)) {
825 CmdArgs.push_back("-coverage-data-file");
826 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
827 CoverageFilename = FProfileDir->getValue();
828 llvm::sys::path::append(CoverageFilename, OutputFilename);
829 }
830 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
831 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
832 }
833 }
834 }
835}
836
837/// \brief Check whether the given input tree contains any compilation actions.
838static bool ContainsCompileAction(const Action *A) {
839 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
840 return true;
841
842 for (const auto &AI : A->inputs())
843 if (ContainsCompileAction(AI))
844 return true;
845
846 return false;
847}
848
849/// \brief Check if -relax-all should be passed to the internal assembler.
850/// This is done by default when compiling non-assembler source with -O0.
851static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
852 bool RelaxDefault = true;
853
854 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
855 RelaxDefault = A->getOption().matches(options::OPT_O0);
856
857 if (RelaxDefault) {
858 RelaxDefault = false;
859 for (const auto &Act : C.getActions()) {
860 if (ContainsCompileAction(Act)) {
861 RelaxDefault = true;
862 break;
863 }
864 }
865 }
866
867 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
868 RelaxDefault);
869}
870
871// Extract the integer N from a string spelled "-dwarf-N", returning 0
872// on mismatch. The StringRef input (rather than an Arg) allows
873// for use by the "-Xassembler" option parser.
874static unsigned DwarfVersionNum(StringRef ArgValue) {
875 return llvm::StringSwitch<unsigned>(ArgValue)
876 .Case("-gdwarf-2", 2)
877 .Case("-gdwarf-3", 3)
878 .Case("-gdwarf-4", 4)
879 .Case("-gdwarf-5", 5)
880 .Default(0);
881}
882
883static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
884 codegenoptions::DebugInfoKind DebugInfoKind,
885 unsigned DwarfVersion,
886 llvm::DebuggerKind DebuggerTuning) {
887 switch (DebugInfoKind) {
888 case codegenoptions::DebugLineTablesOnly:
889 CmdArgs.push_back("-debug-info-kind=line-tables-only");
890 break;
891 case codegenoptions::LimitedDebugInfo:
892 CmdArgs.push_back("-debug-info-kind=limited");
893 break;
894 case codegenoptions::FullDebugInfo:
895 CmdArgs.push_back("-debug-info-kind=standalone");
896 break;
897 default:
898 break;
899 }
900 if (DwarfVersion > 0)
901 CmdArgs.push_back(
902 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
903 switch (DebuggerTuning) {
904 case llvm::DebuggerKind::GDB:
905 CmdArgs.push_back("-debugger-tuning=gdb");
906 break;
907 case llvm::DebuggerKind::LLDB:
908 CmdArgs.push_back("-debugger-tuning=lldb");
909 break;
910 case llvm::DebuggerKind::SCE:
911 CmdArgs.push_back("-debugger-tuning=sce");
912 break;
913 default:
914 break;
915 }
916}
917
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000918static void RenderDebugInfoCompressionArgs(const ArgList &Args,
919 ArgStringList &CmdArgs,
920 const Driver &D) {
921 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
922 if (!A)
923 return;
924
925 if (A->getOption().getID() == options::OPT_gz) {
926 if (llvm::zlib::isAvailable())
927 CmdArgs.push_back("-compress-debug-sections");
928 else
929 D.Diag(diag::warn_debug_compression_unavailable);
930 return;
931 }
932
933 StringRef Value = A->getValue();
934 if (Value == "none") {
935 CmdArgs.push_back("-compress-debug-sections=none");
936 } else if (Value == "zlib" || Value == "zlib-gnu") {
937 if (llvm::zlib::isAvailable()) {
938 CmdArgs.push_back(
939 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
940 } else {
941 D.Diag(diag::warn_debug_compression_unavailable);
942 }
943 } else {
944 D.Diag(diag::err_drv_unsupported_option_argument)
945 << A->getOption().getName() << Value;
946 }
947}
948
David L. Jonesf561aba2017-03-08 01:02:16 +0000949static const char *RelocationModelName(llvm::Reloc::Model Model) {
950 switch (Model) {
951 case llvm::Reloc::Static:
952 return "static";
953 case llvm::Reloc::PIC_:
954 return "pic";
955 case llvm::Reloc::DynamicNoPIC:
956 return "dynamic-no-pic";
957 case llvm::Reloc::ROPI:
958 return "ropi";
959 case llvm::Reloc::RWPI:
960 return "rwpi";
961 case llvm::Reloc::ROPI_RWPI:
962 return "ropi-rwpi";
963 }
964 llvm_unreachable("Unknown Reloc::Model kind");
965}
966
967void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
968 const Driver &D, const ArgList &Args,
969 ArgStringList &CmdArgs,
970 const InputInfo &Output,
971 const InputInfoList &Inputs) const {
972 Arg *A;
973 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
974
975 CheckPreprocessingOptions(D, Args);
976
977 Args.AddLastArg(CmdArgs, options::OPT_C);
978 Args.AddLastArg(CmdArgs, options::OPT_CC);
979
980 // Handle dependency file generation.
981 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
982 (A = Args.getLastArg(options::OPT_MD)) ||
983 (A = Args.getLastArg(options::OPT_MMD))) {
984 // Determine the output location.
985 const char *DepFile;
986 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
987 DepFile = MF->getValue();
988 C.addFailureResultFile(DepFile, &JA);
989 } else if (Output.getType() == types::TY_Dependencies) {
990 DepFile = Output.getFilename();
991 } else if (A->getOption().matches(options::OPT_M) ||
992 A->getOption().matches(options::OPT_MM)) {
993 DepFile = "-";
994 } else {
995 DepFile = getDependencyFileName(Args, Inputs);
996 C.addFailureResultFile(DepFile, &JA);
997 }
998 CmdArgs.push_back("-dependency-file");
999 CmdArgs.push_back(DepFile);
1000
1001 // Add a default target if one wasn't specified.
1002 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1003 const char *DepTarget;
1004
1005 // If user provided -o, that is the dependency target, except
1006 // when we are only generating a dependency file.
1007 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1008 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1009 DepTarget = OutputOpt->getValue();
1010 } else {
1011 // Otherwise derive from the base input.
1012 //
1013 // FIXME: This should use the computed output file location.
1014 SmallString<128> P(Inputs[0].getBaseInput());
1015 llvm::sys::path::replace_extension(P, "o");
1016 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1017 }
1018
Yuka Takahashicdb53482017-06-16 16:01:13 +00001019 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1020 CmdArgs.push_back("-w");
1021 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001022 CmdArgs.push_back("-MT");
1023 SmallString<128> Quoted;
1024 QuoteTarget(DepTarget, Quoted);
1025 CmdArgs.push_back(Args.MakeArgString(Quoted));
1026 }
1027
1028 if (A->getOption().matches(options::OPT_M) ||
1029 A->getOption().matches(options::OPT_MD))
1030 CmdArgs.push_back("-sys-header-deps");
1031 if ((isa<PrecompileJobAction>(JA) &&
1032 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1033 Args.hasArg(options::OPT_fmodule_file_deps))
1034 CmdArgs.push_back("-module-file-deps");
1035 }
1036
1037 if (Args.hasArg(options::OPT_MG)) {
1038 if (!A || A->getOption().matches(options::OPT_MD) ||
1039 A->getOption().matches(options::OPT_MMD))
1040 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1041 CmdArgs.push_back("-MG");
1042 }
1043
1044 Args.AddLastArg(CmdArgs, options::OPT_MP);
1045 Args.AddLastArg(CmdArgs, options::OPT_MV);
1046
1047 // Convert all -MQ <target> args to -MT <quoted target>
1048 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1049 A->claim();
1050
1051 if (A->getOption().matches(options::OPT_MQ)) {
1052 CmdArgs.push_back("-MT");
1053 SmallString<128> Quoted;
1054 QuoteTarget(A->getValue(), Quoted);
1055 CmdArgs.push_back(Args.MakeArgString(Quoted));
1056
1057 // -MT flag - no change
1058 } else {
1059 A->render(Args, CmdArgs);
1060 }
1061 }
1062
1063 // Add offload include arguments specific for CUDA. This must happen before
1064 // we -I or -include anything else, because we must pick up the CUDA headers
1065 // from the particular CUDA installation, rather than from e.g.
1066 // /usr/local/include.
1067 if (JA.isOffloading(Action::OFK_Cuda))
1068 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1069
1070 // Add -i* options, and automatically translate to
1071 // -include-pch/-include-pth for transparent PCH support. It's
1072 // wonky, but we include looking for .gch so we can support seamless
1073 // replacement into a build system already set up to be generating
1074 // .gch files.
1075 int YcIndex = -1, YuIndex = -1;
1076 {
1077 int AI = -1;
1078 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1079 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1080 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1081 // Walk the whole i_Group and skip non "-include" flags so that the index
1082 // here matches the index in the next loop below.
1083 ++AI;
1084 if (!A->getOption().matches(options::OPT_include))
1085 continue;
1086 if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
1087 YcIndex = AI;
1088 if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
1089 YuIndex = AI;
1090 }
1091 }
1092 if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
1093 Driver::InputList Inputs;
1094 D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
1095 assert(Inputs.size() == 1 && "Need one input when building pch");
1096 CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
1097 Inputs[0].second->getValue()));
1098 }
1099
1100 bool RenderedImplicitInclude = false;
1101 int AI = -1;
1102 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1103 ++AI;
1104
1105 if (getToolChain().getDriver().IsCLMode() &&
1106 A->getOption().matches(options::OPT_include)) {
1107 // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
1108 // include is compiled into foo.h, and everything after goes into
1109 // the .obj file. /Yufoo.h means that all includes prior to and including
1110 // foo.h are completely skipped and replaced with a use of the pch file
1111 // for foo.h. (Each flag can have at most one value, multiple /Yc flags
1112 // just mean that the last one wins.) If /Yc and /Yu are both present
1113 // and refer to the same file, /Yc wins.
1114 // Note that OPT__SLASH_FI gets mapped to OPT_include.
1115 // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
1116 // cl.exe seems to support both flags with different values, but that
1117 // seems strange (which flag does /Fp now refer to?), so don't implement
1118 // that until someone needs it.
1119 int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
1120 if (PchIndex != -1) {
1121 if (isa<PrecompileJobAction>(JA)) {
1122 // When building the pch, skip all includes after the pch.
1123 assert(YcIndex != -1 && PchIndex == YcIndex);
1124 if (AI >= YcIndex)
1125 continue;
1126 } else {
1127 // When using the pch, skip all includes prior to the pch.
1128 if (AI < PchIndex) {
1129 A->claim();
1130 continue;
1131 }
1132 if (AI == PchIndex) {
1133 A->claim();
1134 CmdArgs.push_back("-include-pch");
1135 CmdArgs.push_back(
1136 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
1137 continue;
1138 }
1139 }
1140 }
1141 } else if (A->getOption().matches(options::OPT_include)) {
1142 // Handling of gcc-style gch precompiled headers.
1143 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1144 RenderedImplicitInclude = true;
1145
1146 // Use PCH if the user requested it.
1147 bool UsePCH = D.CCCUsePCH;
1148
1149 bool FoundPTH = false;
1150 bool FoundPCH = false;
1151 SmallString<128> P(A->getValue());
1152 // We want the files to have a name like foo.h.pch. Add a dummy extension
1153 // so that replace_extension does the right thing.
1154 P += ".dummy";
1155 if (UsePCH) {
1156 llvm::sys::path::replace_extension(P, "pch");
1157 if (llvm::sys::fs::exists(P))
1158 FoundPCH = true;
1159 }
1160
1161 if (!FoundPCH) {
1162 llvm::sys::path::replace_extension(P, "pth");
1163 if (llvm::sys::fs::exists(P))
1164 FoundPTH = true;
1165 }
1166
1167 if (!FoundPCH && !FoundPTH) {
1168 llvm::sys::path::replace_extension(P, "gch");
1169 if (llvm::sys::fs::exists(P)) {
1170 FoundPCH = UsePCH;
1171 FoundPTH = !UsePCH;
1172 }
1173 }
1174
1175 if (FoundPCH || FoundPTH) {
1176 if (IsFirstImplicitInclude) {
1177 A->claim();
1178 if (UsePCH)
1179 CmdArgs.push_back("-include-pch");
1180 else
1181 CmdArgs.push_back("-include-pth");
1182 CmdArgs.push_back(Args.MakeArgString(P));
1183 continue;
1184 } else {
1185 // Ignore the PCH if not first on command line and emit warning.
1186 D.Diag(diag::warn_drv_pch_not_first_include) << P
1187 << A->getAsString(Args);
1188 }
1189 }
1190 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1191 // Handling of paths which must come late. These entries are handled by
1192 // the toolchain itself after the resource dir is inserted in the right
1193 // search order.
1194 // Do not claim the argument so that the use of the argument does not
1195 // silently go unnoticed on toolchains which do not honour the option.
1196 continue;
1197 }
1198
1199 // Not translated, render as usual.
1200 A->claim();
1201 A->render(Args, CmdArgs);
1202 }
1203
1204 Args.AddAllArgs(CmdArgs,
1205 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1206 options::OPT_F, options::OPT_index_header_map});
1207
1208 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1209
1210 // FIXME: There is a very unfortunate problem here, some troubled
1211 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1212 // really support that we would have to parse and then translate
1213 // those options. :(
1214 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1215 options::OPT_Xpreprocessor);
1216
1217 // -I- is a deprecated GCC feature, reject it.
1218 if (Arg *A = Args.getLastArg(options::OPT_I_))
1219 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1220
1221 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1222 // -isysroot to the CC1 invocation.
1223 StringRef sysroot = C.getSysRoot();
1224 if (sysroot != "") {
1225 if (!Args.hasArg(options::OPT_isysroot)) {
1226 CmdArgs.push_back("-isysroot");
1227 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1228 }
1229 }
1230
1231 // Parse additional include paths from environment variables.
1232 // FIXME: We should probably sink the logic for handling these from the
1233 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1234 // CPATH - included following the user specified includes (but prior to
1235 // builtin and standard includes).
1236 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1237 // C_INCLUDE_PATH - system includes enabled when compiling C.
1238 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1239 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1240 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1241 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1242 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1243 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1244 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1245
1246 // While adding the include arguments, we also attempt to retrieve the
1247 // arguments of related offloading toolchains or arguments that are specific
1248 // of an offloading programming model.
1249
1250 // Add C++ include arguments, if needed.
1251 if (types::isCXX(Inputs[0].getType()))
1252 forAllAssociatedToolChains(C, JA, getToolChain(),
1253 [&Args, &CmdArgs](const ToolChain &TC) {
1254 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1255 });
1256
1257 // Add system include arguments for all targets but IAMCU.
1258 if (!IsIAMCU)
1259 forAllAssociatedToolChains(C, JA, getToolChain(),
1260 [&Args, &CmdArgs](const ToolChain &TC) {
1261 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1262 });
1263 else {
1264 // For IAMCU add special include arguments.
1265 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1266 }
1267}
1268
1269// FIXME: Move to target hook.
1270static bool isSignedCharDefault(const llvm::Triple &Triple) {
1271 switch (Triple.getArch()) {
1272 default:
1273 return true;
1274
1275 case llvm::Triple::aarch64:
1276 case llvm::Triple::aarch64_be:
1277 case llvm::Triple::arm:
1278 case llvm::Triple::armeb:
1279 case llvm::Triple::thumb:
1280 case llvm::Triple::thumbeb:
1281 if (Triple.isOSDarwin() || Triple.isOSWindows())
1282 return true;
1283 return false;
1284
1285 case llvm::Triple::ppc:
1286 case llvm::Triple::ppc64:
1287 if (Triple.isOSDarwin())
1288 return true;
1289 return false;
1290
1291 case llvm::Triple::hexagon:
1292 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001293 case llvm::Triple::riscv32:
1294 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001295 case llvm::Triple::systemz:
1296 case llvm::Triple::xcore:
1297 return false;
1298 }
1299}
1300
1301static bool isNoCommonDefault(const llvm::Triple &Triple) {
1302 switch (Triple.getArch()) {
1303 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001304 if (Triple.isOSFuchsia())
1305 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001306 return false;
1307
1308 case llvm::Triple::xcore:
1309 case llvm::Triple::wasm32:
1310 case llvm::Triple::wasm64:
1311 return true;
1312 }
1313}
1314
1315void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1316 ArgStringList &CmdArgs, bool KernelOrKext) const {
1317 // Select the ABI to use.
1318 // FIXME: Support -meabi.
1319 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1320 const char *ABIName = nullptr;
Eric Christopher53b2cb72017-06-30 00:03:56 +00001321 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
David L. Jonesf561aba2017-03-08 01:02:16 +00001322 ABIName = A->getValue();
Eric Christopher53b2cb72017-06-30 00:03:56 +00001323 else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001324 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001325 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001326 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001327
David L. Jonesf561aba2017-03-08 01:02:16 +00001328 CmdArgs.push_back("-target-abi");
1329 CmdArgs.push_back(ABIName);
1330
1331 // Determine floating point ABI from the options & target defaults.
1332 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1333 if (ABI == arm::FloatABI::Soft) {
1334 // Floating point operations and argument passing are soft.
1335 // FIXME: This changes CPP defines, we need -target-soft-float.
1336 CmdArgs.push_back("-msoft-float");
1337 CmdArgs.push_back("-mfloat-abi");
1338 CmdArgs.push_back("soft");
1339 } else if (ABI == arm::FloatABI::SoftFP) {
1340 // Floating point operations are hard, but argument passing is soft.
1341 CmdArgs.push_back("-mfloat-abi");
1342 CmdArgs.push_back("soft");
1343 } else {
1344 // Floating point operations and argument passing are hard.
1345 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1346 CmdArgs.push_back("-mfloat-abi");
1347 CmdArgs.push_back("hard");
1348 }
1349
1350 // Forward the -mglobal-merge option for explicit control over the pass.
1351 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1352 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001353 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001354 if (A->getOption().matches(options::OPT_mno_global_merge))
1355 CmdArgs.push_back("-arm-global-merge=false");
1356 else
1357 CmdArgs.push_back("-arm-global-merge=true");
1358 }
1359
1360 if (!Args.hasFlag(options::OPT_mimplicit_float,
1361 options::OPT_mno_implicit_float, true))
1362 CmdArgs.push_back("-no-implicit-float");
1363}
1364
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001365void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1366 const ArgList &Args, bool KernelOrKext,
1367 ArgStringList &CmdArgs) const {
1368 const ToolChain &TC = getToolChain();
1369
1370 // Add the target features
1371 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1372
1373 // Add target specific flags.
1374 switch (TC.getArch()) {
1375 default:
1376 break;
1377
1378 case llvm::Triple::arm:
1379 case llvm::Triple::armeb:
1380 case llvm::Triple::thumb:
1381 case llvm::Triple::thumbeb:
1382 // Use the effective triple, which takes into account the deployment target.
1383 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1384 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1385 break;
1386
1387 case llvm::Triple::aarch64:
1388 case llvm::Triple::aarch64_be:
1389 AddAArch64TargetArgs(Args, CmdArgs);
1390 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1391 break;
1392
1393 case llvm::Triple::mips:
1394 case llvm::Triple::mipsel:
1395 case llvm::Triple::mips64:
1396 case llvm::Triple::mips64el:
1397 AddMIPSTargetArgs(Args, CmdArgs);
1398 break;
1399
1400 case llvm::Triple::ppc:
1401 case llvm::Triple::ppc64:
1402 case llvm::Triple::ppc64le:
1403 AddPPCTargetArgs(Args, CmdArgs);
1404 break;
1405
Alex Bradbury71f45452018-01-11 13:36:56 +00001406 case llvm::Triple::riscv32:
1407 case llvm::Triple::riscv64:
1408 AddRISCVTargetArgs(Args, CmdArgs);
1409 break;
1410
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001411 case llvm::Triple::sparc:
1412 case llvm::Triple::sparcel:
1413 case llvm::Triple::sparcv9:
1414 AddSparcTargetArgs(Args, CmdArgs);
1415 break;
1416
1417 case llvm::Triple::systemz:
1418 AddSystemZTargetArgs(Args, CmdArgs);
1419 break;
1420
1421 case llvm::Triple::x86:
1422 case llvm::Triple::x86_64:
1423 AddX86TargetArgs(Args, CmdArgs);
1424 break;
1425
1426 case llvm::Triple::lanai:
1427 AddLanaiTargetArgs(Args, CmdArgs);
1428 break;
1429
1430 case llvm::Triple::hexagon:
1431 AddHexagonTargetArgs(Args, CmdArgs);
1432 break;
1433
1434 case llvm::Triple::wasm32:
1435 case llvm::Triple::wasm64:
1436 AddWebAssemblyTargetArgs(Args, CmdArgs);
1437 break;
1438 }
1439}
1440
David L. Jonesf561aba2017-03-08 01:02:16 +00001441void Clang::AddAArch64TargetArgs(const ArgList &Args,
1442 ArgStringList &CmdArgs) const {
1443 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1444
1445 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1446 Args.hasArg(options::OPT_mkernel) ||
1447 Args.hasArg(options::OPT_fapple_kext))
1448 CmdArgs.push_back("-disable-red-zone");
1449
1450 if (!Args.hasFlag(options::OPT_mimplicit_float,
1451 options::OPT_mno_implicit_float, true))
1452 CmdArgs.push_back("-no-implicit-float");
1453
1454 const char *ABIName = nullptr;
1455 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1456 ABIName = A->getValue();
1457 else if (Triple.isOSDarwin())
1458 ABIName = "darwinpcs";
1459 else
1460 ABIName = "aapcs";
1461
1462 CmdArgs.push_back("-target-abi");
1463 CmdArgs.push_back(ABIName);
1464
1465 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1466 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001467 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001468 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1469 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1470 else
1471 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1472 } else if (Triple.isAndroid()) {
1473 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001474 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001475 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1476 }
1477
1478 // Forward the -mglobal-merge option for explicit control over the pass.
1479 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1480 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001481 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001482 if (A->getOption().matches(options::OPT_mno_global_merge))
1483 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1484 else
1485 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1486 }
Jessica Paquette8e71ee32018-05-02 16:42:51 +00001487
Jessica Paquette544bb552018-05-08 20:58:32 +00001488 if (!Args.hasArg(options::OPT_mno_outline) &&
1489 Args.getLastArg(options::OPT_moutline)) {
Jessica Paquette8e71ee32018-05-02 16:42:51 +00001490 CmdArgs.push_back("-mllvm");
1491 CmdArgs.push_back("-enable-machine-outliner");
1492 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001493}
1494
1495void Clang::AddMIPSTargetArgs(const ArgList &Args,
1496 ArgStringList &CmdArgs) const {
1497 const Driver &D = getToolChain().getDriver();
1498 StringRef CPUName;
1499 StringRef ABIName;
1500 const llvm::Triple &Triple = getToolChain().getTriple();
1501 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1502
1503 CmdArgs.push_back("-target-abi");
1504 CmdArgs.push_back(ABIName.data());
1505
1506 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1507 if (ABI == mips::FloatABI::Soft) {
1508 // Floating point operations and argument passing are soft.
1509 CmdArgs.push_back("-msoft-float");
1510 CmdArgs.push_back("-mfloat-abi");
1511 CmdArgs.push_back("soft");
1512 } else {
1513 // Floating point operations and argument passing are hard.
1514 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1515 CmdArgs.push_back("-mfloat-abi");
1516 CmdArgs.push_back("hard");
1517 }
1518
1519 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1520 if (A->getOption().matches(options::OPT_mxgot)) {
1521 CmdArgs.push_back("-mllvm");
1522 CmdArgs.push_back("-mxgot");
1523 }
1524 }
1525
1526 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1527 options::OPT_mno_ldc1_sdc1)) {
1528 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1529 CmdArgs.push_back("-mllvm");
1530 CmdArgs.push_back("-mno-ldc1-sdc1");
1531 }
1532 }
1533
1534 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1535 options::OPT_mno_check_zero_division)) {
1536 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1537 CmdArgs.push_back("-mllvm");
1538 CmdArgs.push_back("-mno-check-zero-division");
1539 }
1540 }
1541
1542 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1543 StringRef v = A->getValue();
1544 CmdArgs.push_back("-mllvm");
1545 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1546 A->claim();
1547 }
1548
Simon Dardis31636a12017-07-20 14:04:12 +00001549 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1550 Arg *ABICalls =
1551 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1552
1553 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1554 // -mgpopt is the default for static, -fno-pic environments but these two
1555 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1556 // the only case where -mllvm -mgpopt is passed.
1557 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1558 // passed explicitly when compiling something with -mabicalls
1559 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001560 //
1561 // When the ABI in use is N64, we also need to determine the PIC mode that
1562 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001563 bool NoABICalls =
1564 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001565
1566 llvm::Reloc::Model RelocationModel;
1567 unsigned PICLevel;
1568 bool IsPIE;
1569 std::tie(RelocationModel, PICLevel, IsPIE) =
1570 ParsePICArgs(getToolChain(), Args);
1571
1572 NoABICalls = NoABICalls ||
1573 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1574
Simon Dardis31636a12017-07-20 14:04:12 +00001575 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1576 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1577 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1578 CmdArgs.push_back("-mllvm");
1579 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001580
1581 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1582 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001583 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001584 options::OPT_mno_extern_sdata);
1585 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1586 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001587 if (LocalSData) {
1588 CmdArgs.push_back("-mllvm");
1589 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1590 CmdArgs.push_back("-mlocal-sdata=1");
1591 } else {
1592 CmdArgs.push_back("-mlocal-sdata=0");
1593 }
1594 LocalSData->claim();
1595 }
1596
Simon Dardis7d318782017-07-24 14:02:09 +00001597 if (ExternSData) {
1598 CmdArgs.push_back("-mllvm");
1599 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1600 CmdArgs.push_back("-mextern-sdata=1");
1601 } else {
1602 CmdArgs.push_back("-mextern-sdata=0");
1603 }
1604 ExternSData->claim();
1605 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001606
1607 if (EmbeddedData) {
1608 CmdArgs.push_back("-mllvm");
1609 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1610 CmdArgs.push_back("-membedded-data=1");
1611 } else {
1612 CmdArgs.push_back("-membedded-data=0");
1613 }
1614 EmbeddedData->claim();
1615 }
1616
Simon Dardis31636a12017-07-20 14:04:12 +00001617 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1618 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1619
1620 if (GPOpt)
1621 GPOpt->claim();
1622
David L. Jonesf561aba2017-03-08 01:02:16 +00001623 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1624 StringRef Val = StringRef(A->getValue());
1625 if (mips::hasCompactBranches(CPUName)) {
1626 if (Val == "never" || Val == "always" || Val == "optimal") {
1627 CmdArgs.push_back("-mllvm");
1628 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1629 } else
1630 D.Diag(diag::err_drv_unsupported_option_argument)
1631 << A->getOption().getName() << Val;
1632 } else
1633 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1634 }
1635}
1636
1637void Clang::AddPPCTargetArgs(const ArgList &Args,
1638 ArgStringList &CmdArgs) const {
1639 // Select the ABI to use.
1640 const char *ABIName = nullptr;
1641 if (getToolChain().getTriple().isOSLinux())
1642 switch (getToolChain().getArch()) {
1643 case llvm::Triple::ppc64: {
1644 // When targeting a processor that supports QPX, or if QPX is
1645 // specifically enabled, default to using the ABI that supports QPX (so
1646 // long as it is not specifically disabled).
1647 bool HasQPX = false;
1648 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1649 HasQPX = A->getValue() == StringRef("a2q");
1650 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1651 if (HasQPX) {
1652 ABIName = "elfv1-qpx";
1653 break;
1654 }
1655
1656 ABIName = "elfv1";
1657 break;
1658 }
1659 case llvm::Triple::ppc64le:
1660 ABIName = "elfv2";
1661 break;
1662 default:
1663 break;
1664 }
1665
1666 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1667 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1668 // the option if given as we don't have backend support for any targets
1669 // that don't use the altivec abi.
1670 if (StringRef(A->getValue()) != "altivec")
1671 ABIName = A->getValue();
1672
1673 ppc::FloatABI FloatABI =
1674 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1675
1676 if (FloatABI == ppc::FloatABI::Soft) {
1677 // Floating point operations and argument passing are soft.
1678 CmdArgs.push_back("-msoft-float");
1679 CmdArgs.push_back("-mfloat-abi");
1680 CmdArgs.push_back("soft");
1681 } else {
1682 // Floating point operations and argument passing are hard.
1683 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1684 CmdArgs.push_back("-mfloat-abi");
1685 CmdArgs.push_back("hard");
1686 }
1687
1688 if (ABIName) {
1689 CmdArgs.push_back("-target-abi");
1690 CmdArgs.push_back(ABIName);
1691 }
1692}
1693
Alex Bradbury71f45452018-01-11 13:36:56 +00001694void Clang::AddRISCVTargetArgs(const ArgList &Args,
1695 ArgStringList &CmdArgs) const {
1696 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001697 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001698 const char *ABIName = nullptr;
1699 const llvm::Triple &Triple = getToolChain().getTriple();
1700 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1701 ABIName = A->getValue();
1702 else if (Triple.getArch() == llvm::Triple::riscv32)
1703 ABIName = "ilp32";
1704 else if (Triple.getArch() == llvm::Triple::riscv64)
1705 ABIName = "lp64";
1706 else
1707 llvm_unreachable("Unexpected triple!");
1708
1709 CmdArgs.push_back("-target-abi");
1710 CmdArgs.push_back(ABIName);
1711}
1712
David L. Jonesf561aba2017-03-08 01:02:16 +00001713void Clang::AddSparcTargetArgs(const ArgList &Args,
1714 ArgStringList &CmdArgs) const {
1715 sparc::FloatABI FloatABI =
1716 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1717
1718 if (FloatABI == sparc::FloatABI::Soft) {
1719 // Floating point operations and argument passing are soft.
1720 CmdArgs.push_back("-msoft-float");
1721 CmdArgs.push_back("-mfloat-abi");
1722 CmdArgs.push_back("soft");
1723 } else {
1724 // Floating point operations and argument passing are hard.
1725 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1726 CmdArgs.push_back("-mfloat-abi");
1727 CmdArgs.push_back("hard");
1728 }
1729}
1730
1731void Clang::AddSystemZTargetArgs(const ArgList &Args,
1732 ArgStringList &CmdArgs) const {
1733 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1734 CmdArgs.push_back("-mbackchain");
1735}
1736
1737void Clang::AddX86TargetArgs(const ArgList &Args,
1738 ArgStringList &CmdArgs) const {
1739 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1740 Args.hasArg(options::OPT_mkernel) ||
1741 Args.hasArg(options::OPT_fapple_kext))
1742 CmdArgs.push_back("-disable-red-zone");
1743
1744 // Default to avoid implicit floating-point for kernel/kext code, but allow
1745 // that to be overridden with -mno-soft-float.
1746 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1747 Args.hasArg(options::OPT_fapple_kext));
1748 if (Arg *A = Args.getLastArg(
1749 options::OPT_msoft_float, options::OPT_mno_soft_float,
1750 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1751 const Option &O = A->getOption();
1752 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1753 O.matches(options::OPT_msoft_float));
1754 }
1755 if (NoImplicitFloat)
1756 CmdArgs.push_back("-no-implicit-float");
1757
1758 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1759 StringRef Value = A->getValue();
1760 if (Value == "intel" || Value == "att") {
1761 CmdArgs.push_back("-mllvm");
1762 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1763 } else {
1764 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1765 << A->getOption().getName() << Value;
1766 }
Nico Webere3712cf2018-01-17 13:34:20 +00001767 } else if (getToolChain().getDriver().IsCLMode()) {
1768 CmdArgs.push_back("-mllvm");
1769 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001770 }
1771
1772 // Set flags to support MCU ABI.
1773 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1774 CmdArgs.push_back("-mfloat-abi");
1775 CmdArgs.push_back("soft");
1776 CmdArgs.push_back("-mstack-alignment=4");
1777 }
1778}
1779
1780void Clang::AddHexagonTargetArgs(const ArgList &Args,
1781 ArgStringList &CmdArgs) const {
1782 CmdArgs.push_back("-mqdsp6-compat");
1783 CmdArgs.push_back("-Wreturn-type");
1784
1785 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001786 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001787 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1788 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001789 }
1790
1791 if (!Args.hasArg(options::OPT_fno_short_enums))
1792 CmdArgs.push_back("-fshort-enums");
1793 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1794 CmdArgs.push_back("-mllvm");
1795 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1796 }
1797 CmdArgs.push_back("-mllvm");
1798 CmdArgs.push_back("-machine-sink-split=0");
1799}
1800
1801void Clang::AddLanaiTargetArgs(const ArgList &Args,
1802 ArgStringList &CmdArgs) const {
1803 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1804 StringRef CPUName = A->getValue();
1805
1806 CmdArgs.push_back("-target-cpu");
1807 CmdArgs.push_back(Args.MakeArgString(CPUName));
1808 }
1809 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1810 StringRef Value = A->getValue();
1811 // Only support mregparm=4 to support old usage. Report error for all other
1812 // cases.
1813 int Mregparm;
1814 if (Value.getAsInteger(10, Mregparm)) {
1815 if (Mregparm != 4) {
1816 getToolChain().getDriver().Diag(
1817 diag::err_drv_unsupported_option_argument)
1818 << A->getOption().getName() << Value;
1819 }
1820 }
1821 }
1822}
1823
1824void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1825 ArgStringList &CmdArgs) const {
1826 // Default to "hidden" visibility.
1827 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1828 options::OPT_fvisibility_ms_compat)) {
1829 CmdArgs.push_back("-fvisibility");
1830 CmdArgs.push_back("hidden");
1831 }
1832}
1833
1834void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1835 StringRef Target, const InputInfo &Output,
1836 const InputInfo &Input, const ArgList &Args) const {
1837 // If this is a dry run, do not create the compilation database file.
1838 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1839 return;
1840
1841 using llvm::yaml::escape;
1842 const Driver &D = getToolChain().getDriver();
1843
1844 if (!CompilationDatabase) {
1845 std::error_code EC;
1846 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1847 if (EC) {
1848 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1849 << EC.message();
1850 return;
1851 }
1852 CompilationDatabase = std::move(File);
1853 }
1854 auto &CDB = *CompilationDatabase;
1855 SmallString<128> Buf;
1856 if (llvm::sys::fs::current_path(Buf))
1857 Buf = ".";
1858 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1859 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1860 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1861 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1862 Buf = "-x";
1863 Buf += types::getTypeName(Input.getType());
1864 CDB << ", \"" << escape(Buf) << "\"";
1865 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1866 Buf = "--sysroot=";
1867 Buf += D.SysRoot;
1868 CDB << ", \"" << escape(Buf) << "\"";
1869 }
1870 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1871 for (auto &A: Args) {
1872 auto &O = A->getOption();
1873 // Skip language selection, which is positional.
1874 if (O.getID() == options::OPT_x)
1875 continue;
1876 // Skip writing dependency output and the compilation database itself.
1877 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1878 continue;
1879 // Skip inputs.
1880 if (O.getKind() == Option::InputClass)
1881 continue;
1882 // All other arguments are quoted and appended.
1883 ArgStringList ASL;
1884 A->render(Args, ASL);
1885 for (auto &it: ASL)
1886 CDB << ", \"" << escape(it) << "\"";
1887 }
1888 Buf = "--target=";
1889 Buf += Target;
1890 CDB << ", \"" << escape(Buf) << "\"]},\n";
1891}
1892
1893static void CollectArgsForIntegratedAssembler(Compilation &C,
1894 const ArgList &Args,
1895 ArgStringList &CmdArgs,
1896 const Driver &D) {
1897 if (UseRelaxAll(C, Args))
1898 CmdArgs.push_back("-mrelax-all");
1899
1900 // Only default to -mincremental-linker-compatible if we think we are
1901 // targeting the MSVC linker.
1902 bool DefaultIncrementalLinkerCompatible =
1903 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1904 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1905 options::OPT_mno_incremental_linker_compatible,
1906 DefaultIncrementalLinkerCompatible))
1907 CmdArgs.push_back("-mincremental-linker-compatible");
1908
1909 switch (C.getDefaultToolChain().getArch()) {
1910 case llvm::Triple::arm:
1911 case llvm::Triple::armeb:
1912 case llvm::Triple::thumb:
1913 case llvm::Triple::thumbeb:
1914 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1915 StringRef Value = A->getValue();
1916 if (Value == "always" || Value == "never" || Value == "arm" ||
1917 Value == "thumb") {
1918 CmdArgs.push_back("-mllvm");
1919 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1920 } else {
1921 D.Diag(diag::err_drv_unsupported_option_argument)
1922 << A->getOption().getName() << Value;
1923 }
1924 }
1925 break;
1926 default:
1927 break;
1928 }
1929
1930 // When passing -I arguments to the assembler we sometimes need to
1931 // unconditionally take the next argument. For example, when parsing
1932 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1933 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1934 // arg after parsing the '-I' arg.
1935 bool TakeNextArg = false;
1936
Petr Hosek5668d832017-11-22 01:38:31 +00001937 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00001938 const char *MipsTargetFeature = nullptr;
1939 for (const Arg *A :
1940 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1941 A->claim();
1942
1943 for (StringRef Value : A->getValues()) {
1944 if (TakeNextArg) {
1945 CmdArgs.push_back(Value.data());
1946 TakeNextArg = false;
1947 continue;
1948 }
1949
1950 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1951 Value == "-mbig-obj")
1952 continue; // LLVM handles bigobj automatically
1953
1954 switch (C.getDefaultToolChain().getArch()) {
1955 default:
1956 break;
Peter Smith3947cb32017-11-20 13:43:55 +00001957 case llvm::Triple::thumb:
1958 case llvm::Triple::thumbeb:
1959 case llvm::Triple::arm:
1960 case llvm::Triple::armeb:
1961 if (Value == "-mthumb")
1962 // -mthumb has already been processed in ComputeLLVMTriple()
1963 // recognize but skip over here.
1964 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00001965 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00001966 case llvm::Triple::mips:
1967 case llvm::Triple::mipsel:
1968 case llvm::Triple::mips64:
1969 case llvm::Triple::mips64el:
1970 if (Value == "--trap") {
1971 CmdArgs.push_back("-target-feature");
1972 CmdArgs.push_back("+use-tcc-in-div");
1973 continue;
1974 }
1975 if (Value == "--break") {
1976 CmdArgs.push_back("-target-feature");
1977 CmdArgs.push_back("-use-tcc-in-div");
1978 continue;
1979 }
1980 if (Value.startswith("-msoft-float")) {
1981 CmdArgs.push_back("-target-feature");
1982 CmdArgs.push_back("+soft-float");
1983 continue;
1984 }
1985 if (Value.startswith("-mhard-float")) {
1986 CmdArgs.push_back("-target-feature");
1987 CmdArgs.push_back("-soft-float");
1988 continue;
1989 }
1990
1991 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1992 .Case("-mips1", "+mips1")
1993 .Case("-mips2", "+mips2")
1994 .Case("-mips3", "+mips3")
1995 .Case("-mips4", "+mips4")
1996 .Case("-mips5", "+mips5")
1997 .Case("-mips32", "+mips32")
1998 .Case("-mips32r2", "+mips32r2")
1999 .Case("-mips32r3", "+mips32r3")
2000 .Case("-mips32r5", "+mips32r5")
2001 .Case("-mips32r6", "+mips32r6")
2002 .Case("-mips64", "+mips64")
2003 .Case("-mips64r2", "+mips64r2")
2004 .Case("-mips64r3", "+mips64r3")
2005 .Case("-mips64r5", "+mips64r5")
2006 .Case("-mips64r6", "+mips64r6")
2007 .Default(nullptr);
2008 if (MipsTargetFeature)
2009 continue;
2010 }
2011
2012 if (Value == "-force_cpusubtype_ALL") {
2013 // Do nothing, this is the default and we don't support anything else.
2014 } else if (Value == "-L") {
2015 CmdArgs.push_back("-msave-temp-labels");
2016 } else if (Value == "--fatal-warnings") {
2017 CmdArgs.push_back("-massembler-fatal-warnings");
2018 } else if (Value == "--noexecstack") {
2019 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002020 } else if (Value.startswith("-compress-debug-sections") ||
2021 Value.startswith("--compress-debug-sections") ||
2022 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002023 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002024 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002025 } else if (Value == "-mrelax-relocations=yes" ||
2026 Value == "--mrelax-relocations=yes") {
2027 UseRelaxRelocations = true;
2028 } else if (Value == "-mrelax-relocations=no" ||
2029 Value == "--mrelax-relocations=no") {
2030 UseRelaxRelocations = false;
2031 } else if (Value.startswith("-I")) {
2032 CmdArgs.push_back(Value.data());
2033 // We need to consume the next argument if the current arg is a plain
2034 // -I. The next arg will be the include directory.
2035 if (Value == "-I")
2036 TakeNextArg = true;
2037 } else if (Value.startswith("-gdwarf-")) {
2038 // "-gdwarf-N" options are not cc1as options.
2039 unsigned DwarfVersion = DwarfVersionNum(Value);
2040 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2041 CmdArgs.push_back(Value.data());
2042 } else {
2043 RenderDebugEnablingArgs(Args, CmdArgs,
2044 codegenoptions::LimitedDebugInfo,
2045 DwarfVersion, llvm::DebuggerKind::Default);
2046 }
2047 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2048 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2049 // Do nothing, we'll validate it later.
2050 } else if (Value == "-defsym") {
2051 if (A->getNumValues() != 2) {
2052 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2053 break;
2054 }
2055 const char *S = A->getValue(1);
2056 auto Pair = StringRef(S).split('=');
2057 auto Sym = Pair.first;
2058 auto SVal = Pair.second;
2059
2060 if (Sym.empty() || SVal.empty()) {
2061 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2062 break;
2063 }
2064 int64_t IVal;
2065 if (SVal.getAsInteger(0, IVal)) {
2066 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2067 break;
2068 }
2069 CmdArgs.push_back(Value.data());
2070 TakeNextArg = true;
2071 } else {
2072 D.Diag(diag::err_drv_unsupported_option_argument)
2073 << A->getOption().getName() << Value;
2074 }
2075 }
2076 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002077 if (UseRelaxRelocations)
2078 CmdArgs.push_back("--mrelax-relocations");
2079 if (MipsTargetFeature != nullptr) {
2080 CmdArgs.push_back("-target-feature");
2081 CmdArgs.push_back(MipsTargetFeature);
2082 }
2083}
2084
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002085static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2086 bool OFastEnabled, const ArgList &Args,
2087 ArgStringList &CmdArgs) {
2088 // Handle various floating point optimization flags, mapping them to the
2089 // appropriate LLVM code generation flags. This is complicated by several
2090 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002091 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002092 // LLVM flags based on the final state.
2093 bool HonorINFs = true;
2094 bool HonorNaNs = true;
2095 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2096 bool MathErrno = TC.IsMathErrnoDefault();
2097 bool AssociativeMath = false;
2098 bool ReciprocalMath = false;
2099 bool SignedZeros = true;
2100 bool TrappingMath = true;
2101 StringRef DenormalFPMath = "";
2102 StringRef FPContract = "";
2103
2104 for (const Arg *A : Args) {
2105 switch (A->getOption().getID()) {
2106 // If this isn't an FP option skip the claim below
2107 default: continue;
2108
2109 // Options controlling individual features
2110 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2111 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2112 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2113 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2114 case options::OPT_fmath_errno: MathErrno = true; break;
2115 case options::OPT_fno_math_errno: MathErrno = false; break;
2116 case options::OPT_fassociative_math: AssociativeMath = true; break;
2117 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2118 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2119 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2120 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2121 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2122 case options::OPT_ftrapping_math: TrappingMath = true; break;
2123 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2124
2125 case options::OPT_fdenormal_fp_math_EQ:
2126 DenormalFPMath = A->getValue();
2127 break;
2128
2129 // Validate and pass through -fp-contract option.
2130 case options::OPT_ffp_contract: {
2131 StringRef Val = A->getValue();
2132 if (Val == "fast" || Val == "on" || Val == "off")
2133 FPContract = Val;
2134 else
2135 D.Diag(diag::err_drv_unsupported_option_argument)
2136 << A->getOption().getName() << Val;
2137 break;
2138 }
2139
2140 case options::OPT_ffinite_math_only:
2141 HonorINFs = false;
2142 HonorNaNs = false;
2143 break;
2144 case options::OPT_fno_finite_math_only:
2145 HonorINFs = true;
2146 HonorNaNs = true;
2147 break;
2148
2149 case options::OPT_funsafe_math_optimizations:
2150 AssociativeMath = true;
2151 ReciprocalMath = true;
2152 SignedZeros = false;
2153 TrappingMath = false;
2154 break;
2155 case options::OPT_fno_unsafe_math_optimizations:
2156 AssociativeMath = false;
2157 ReciprocalMath = false;
2158 SignedZeros = true;
2159 TrappingMath = true;
2160 // -fno_unsafe_math_optimizations restores default denormal handling
2161 DenormalFPMath = "";
2162 break;
2163
2164 case options::OPT_Ofast:
2165 // If -Ofast is the optimization level, then -ffast-math should be enabled
2166 if (!OFastEnabled)
2167 continue;
2168 LLVM_FALLTHROUGH;
2169 case options::OPT_ffast_math:
2170 HonorINFs = false;
2171 HonorNaNs = false;
2172 MathErrno = false;
2173 AssociativeMath = true;
2174 ReciprocalMath = true;
2175 SignedZeros = false;
2176 TrappingMath = false;
2177 // If fast-math is set then set the fp-contract mode to fast.
2178 FPContract = "fast";
2179 break;
2180 case options::OPT_fno_fast_math:
2181 HonorINFs = true;
2182 HonorNaNs = true;
2183 // Turning on -ffast-math (with either flag) removes the need for
2184 // MathErrno. However, turning *off* -ffast-math merely restores the
2185 // toolchain default (which may be false).
2186 MathErrno = TC.IsMathErrnoDefault();
2187 AssociativeMath = false;
2188 ReciprocalMath = false;
2189 SignedZeros = true;
2190 TrappingMath = true;
2191 // -fno_fast_math restores default denormal and fpcontract handling
2192 DenormalFPMath = "";
2193 FPContract = "";
2194 break;
2195 }
2196
2197 // If we handled this option claim it
2198 A->claim();
2199 }
2200
2201 if (!HonorINFs)
2202 CmdArgs.push_back("-menable-no-infs");
2203
2204 if (!HonorNaNs)
2205 CmdArgs.push_back("-menable-no-nans");
2206
2207 if (MathErrno)
2208 CmdArgs.push_back("-fmath-errno");
2209
2210 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2211 !TrappingMath)
2212 CmdArgs.push_back("-menable-unsafe-fp-math");
2213
2214 if (!SignedZeros)
2215 CmdArgs.push_back("-fno-signed-zeros");
2216
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002217 if (AssociativeMath && !SignedZeros && !TrappingMath)
2218 CmdArgs.push_back("-mreassociate");
2219
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002220 if (ReciprocalMath)
2221 CmdArgs.push_back("-freciprocal-math");
2222
2223 if (!TrappingMath)
2224 CmdArgs.push_back("-fno-trapping-math");
2225
2226 if (!DenormalFPMath.empty())
2227 CmdArgs.push_back(
2228 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2229
2230 if (!FPContract.empty())
2231 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2232
2233 ParseMRecip(D, Args, CmdArgs);
2234
2235 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2236 // individual features enabled by -ffast-math instead of the option itself as
2237 // that's consistent with gcc's behaviour.
2238 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2239 ReciprocalMath && !SignedZeros && !TrappingMath)
2240 CmdArgs.push_back("-ffast-math");
2241
2242 // Handle __FINITE_MATH_ONLY__ similarly.
2243 if (!HonorINFs && !HonorNaNs)
2244 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002245
2246 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2247 CmdArgs.push_back("-mfpmath");
2248 CmdArgs.push_back(A->getValue());
2249 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002250
2251 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002252 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2253 options::OPT_fstrict_float_cast_overflow, false))
2254 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002255}
2256
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002257static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2258 const llvm::Triple &Triple,
2259 const InputInfo &Input) {
2260 // Enable region store model by default.
2261 CmdArgs.push_back("-analyzer-store=region");
2262
2263 // Treat blocks as analysis entry points.
2264 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2265
2266 CmdArgs.push_back("-analyzer-eagerly-assume");
2267
2268 // Add default argument set.
2269 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2270 CmdArgs.push_back("-analyzer-checker=core");
2271 CmdArgs.push_back("-analyzer-checker=apiModeling");
2272
2273 if (!Triple.isWindowsMSVCEnvironment()) {
2274 CmdArgs.push_back("-analyzer-checker=unix");
2275 } else {
2276 // Enable "unix" checkers that also work on Windows.
2277 CmdArgs.push_back("-analyzer-checker=unix.API");
2278 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2279 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2280 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2281 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2282 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2283 }
2284
2285 // Disable some unix checkers for PS4.
2286 if (Triple.isPS4CPU()) {
2287 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2288 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2289 }
2290
2291 if (Triple.isOSDarwin())
2292 CmdArgs.push_back("-analyzer-checker=osx");
2293
2294 CmdArgs.push_back("-analyzer-checker=deadcode");
2295
2296 if (types::isCXX(Input.getType()))
2297 CmdArgs.push_back("-analyzer-checker=cplusplus");
2298
2299 if (!Triple.isPS4CPU()) {
2300 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2301 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2302 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2303 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2304 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2305 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2306 }
2307
2308 // Default nullability checks.
2309 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2310 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2311 }
2312
2313 // Set the output format. The default is plist, for (lame) historical reasons.
2314 CmdArgs.push_back("-analyzer-output");
2315 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2316 CmdArgs.push_back(A->getValue());
2317 else
2318 CmdArgs.push_back("plist");
2319
2320 // Disable the presentation of standard compiler warnings when using
2321 // --analyze. We only want to show static analyzer diagnostics or frontend
2322 // errors.
2323 CmdArgs.push_back("-w");
2324
2325 // Add -Xanalyzer arguments when running as analyzer.
2326 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2327}
2328
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002329static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002330 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002331 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2332
2333 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2334 // doesn't even have a stack!
2335 if (EffectiveTriple.isNVPTX())
2336 return;
2337
2338 // -stack-protector=0 is default.
2339 unsigned StackProtectorLevel = 0;
2340 unsigned DefaultStackProtectorLevel =
2341 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2342
2343 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2344 options::OPT_fstack_protector_all,
2345 options::OPT_fstack_protector_strong,
2346 options::OPT_fstack_protector)) {
2347 if (A->getOption().matches(options::OPT_fstack_protector))
2348 StackProtectorLevel =
2349 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2350 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2351 StackProtectorLevel = LangOptions::SSPStrong;
2352 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2353 StackProtectorLevel = LangOptions::SSPReq;
2354 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002355 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002356 }
2357
2358 if (StackProtectorLevel) {
2359 CmdArgs.push_back("-stack-protector");
2360 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2361 }
2362
2363 // --param ssp-buffer-size=
2364 for (const Arg *A : Args.filtered(options::OPT__param)) {
2365 StringRef Str(A->getValue());
2366 if (Str.startswith("ssp-buffer-size=")) {
2367 if (StackProtectorLevel) {
2368 CmdArgs.push_back("-stack-protector-buffer-size");
2369 // FIXME: Verify the argument is a valid integer.
2370 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2371 }
2372 A->claim();
2373 }
2374 }
2375}
2376
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002377static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2378 const unsigned ForwardedArguments[] = {
2379 options::OPT_cl_opt_disable,
2380 options::OPT_cl_strict_aliasing,
2381 options::OPT_cl_single_precision_constant,
2382 options::OPT_cl_finite_math_only,
2383 options::OPT_cl_kernel_arg_info,
2384 options::OPT_cl_unsafe_math_optimizations,
2385 options::OPT_cl_fast_relaxed_math,
2386 options::OPT_cl_mad_enable,
2387 options::OPT_cl_no_signed_zeros,
2388 options::OPT_cl_denorms_are_zero,
2389 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002390 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002391 };
2392
2393 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2394 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2395 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2396 }
2397
2398 for (const auto &Arg : ForwardedArguments)
2399 if (const auto *A = Args.getLastArg(Arg))
2400 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2401}
2402
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002403static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2404 ArgStringList &CmdArgs) {
2405 bool ARCMTEnabled = false;
2406 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2407 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2408 options::OPT_ccc_arcmt_modify,
2409 options::OPT_ccc_arcmt_migrate)) {
2410 ARCMTEnabled = true;
2411 switch (A->getOption().getID()) {
2412 default: llvm_unreachable("missed a case");
2413 case options::OPT_ccc_arcmt_check:
2414 CmdArgs.push_back("-arcmt-check");
2415 break;
2416 case options::OPT_ccc_arcmt_modify:
2417 CmdArgs.push_back("-arcmt-modify");
2418 break;
2419 case options::OPT_ccc_arcmt_migrate:
2420 CmdArgs.push_back("-arcmt-migrate");
2421 CmdArgs.push_back("-mt-migrate-directory");
2422 CmdArgs.push_back(A->getValue());
2423
2424 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2425 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2426 break;
2427 }
2428 }
2429 } else {
2430 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2431 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2432 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2433 }
2434
2435 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2436 if (ARCMTEnabled)
2437 D.Diag(diag::err_drv_argument_not_allowed_with)
2438 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2439
2440 CmdArgs.push_back("-mt-migrate-directory");
2441 CmdArgs.push_back(A->getValue());
2442
2443 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2444 options::OPT_objcmt_migrate_subscripting,
2445 options::OPT_objcmt_migrate_property)) {
2446 // None specified, means enable them all.
2447 CmdArgs.push_back("-objcmt-migrate-literals");
2448 CmdArgs.push_back("-objcmt-migrate-subscripting");
2449 CmdArgs.push_back("-objcmt-migrate-property");
2450 } else {
2451 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2452 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2453 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2454 }
2455 } else {
2456 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2457 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2458 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2459 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2460 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2461 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2462 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2463 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2464 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2465 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2466 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2467 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2468 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2469 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2470 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2471 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2472 }
2473}
2474
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002475static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2476 const ArgList &Args, ArgStringList &CmdArgs) {
2477 // -fbuiltin is default unless -mkernel is used.
2478 bool UseBuiltins =
2479 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2480 !Args.hasArg(options::OPT_mkernel));
2481 if (!UseBuiltins)
2482 CmdArgs.push_back("-fno-builtin");
2483
2484 // -ffreestanding implies -fno-builtin.
2485 if (Args.hasArg(options::OPT_ffreestanding))
2486 UseBuiltins = false;
2487
2488 // Process the -fno-builtin-* options.
2489 for (const auto &Arg : Args) {
2490 const Option &O = Arg->getOption();
2491 if (!O.matches(options::OPT_fno_builtin_))
2492 continue;
2493
2494 Arg->claim();
2495
2496 // If -fno-builtin is specified, then there's no need to pass the option to
2497 // the frontend.
2498 if (!UseBuiltins)
2499 continue;
2500
2501 StringRef FuncName = Arg->getValue();
2502 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2503 }
2504
2505 // le32-specific flags:
2506 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2507 // by default.
2508 if (TC.getArch() == llvm::Triple::le32)
2509 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002510}
2511
Adrian Prantl70599032018-02-09 18:43:10 +00002512void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2513 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2514 llvm::sys::path::append(Result, "org.llvm.clang.");
2515 appendUserToPath(Result);
2516 llvm::sys::path::append(Result, "ModuleCache");
2517}
2518
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002519static void RenderModulesOptions(Compilation &C, const Driver &D,
2520 const ArgList &Args, const InputInfo &Input,
2521 const InputInfo &Output,
2522 ArgStringList &CmdArgs, bool &HaveModules) {
2523 // -fmodules enables the use of precompiled modules (off by default).
2524 // Users can pass -fno-cxx-modules to turn off modules support for
2525 // C++/Objective-C++ programs.
2526 bool HaveClangModules = false;
2527 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2528 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2529 options::OPT_fno_cxx_modules, true);
2530 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2531 CmdArgs.push_back("-fmodules");
2532 HaveClangModules = true;
2533 }
2534 }
2535
2536 HaveModules = HaveClangModules;
2537 if (Args.hasArg(options::OPT_fmodules_ts)) {
2538 CmdArgs.push_back("-fmodules-ts");
2539 HaveModules = true;
2540 }
2541
2542 // -fmodule-maps enables implicit reading of module map files. By default,
2543 // this is enabled if we are using Clang's flavor of precompiled modules.
2544 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2545 options::OPT_fno_implicit_module_maps, HaveClangModules))
2546 CmdArgs.push_back("-fimplicit-module-maps");
2547
2548 // -fmodules-decluse checks that modules used are declared so (off by default)
2549 if (Args.hasFlag(options::OPT_fmodules_decluse,
2550 options::OPT_fno_modules_decluse, false))
2551 CmdArgs.push_back("-fmodules-decluse");
2552
2553 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2554 // all #included headers are part of modules.
2555 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2556 options::OPT_fno_modules_strict_decluse, false))
2557 CmdArgs.push_back("-fmodules-strict-decluse");
2558
2559 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002560 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002561 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2562 options::OPT_fno_implicit_modules, HaveClangModules)) {
2563 if (HaveModules)
2564 CmdArgs.push_back("-fno-implicit-modules");
2565 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002566 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002567 // -fmodule-cache-path specifies where our implicitly-built module files
2568 // should be written.
2569 SmallString<128> Path;
2570 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2571 Path = A->getValue();
2572
2573 if (C.isForDiagnostics()) {
2574 // When generating crash reports, we want to emit the modules along with
2575 // the reproduction sources, so we ignore any provided module path.
2576 Path = Output.getFilename();
2577 llvm::sys::path::replace_extension(Path, ".cache");
2578 llvm::sys::path::append(Path, "modules");
2579 } else if (Path.empty()) {
2580 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002581 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002582 }
2583
2584 const char Arg[] = "-fmodules-cache-path=";
2585 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2586 CmdArgs.push_back(Args.MakeArgString(Path));
2587 }
2588
2589 if (HaveModules) {
2590 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2591 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2592 CmdArgs.push_back(Args.MakeArgString(
2593 std::string("-fprebuilt-module-path=") + A->getValue()));
2594 A->claim();
2595 }
2596 }
2597
2598 // -fmodule-name specifies the module that is currently being built (or
2599 // used for header checking by -fmodule-maps).
2600 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2601
2602 // -fmodule-map-file can be used to specify files containing module
2603 // definitions.
2604 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2605
2606 // -fbuiltin-module-map can be used to load the clang
2607 // builtin headers modulemap file.
2608 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2609 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2610 llvm::sys::path::append(BuiltinModuleMap, "include");
2611 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2612 if (llvm::sys::fs::exists(BuiltinModuleMap))
2613 CmdArgs.push_back(
2614 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2615 }
2616
2617 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2618 // names to precompiled module files (the module is loaded only if used).
2619 // The -fmodule-file=<file> form can be used to unconditionally load
2620 // precompiled module files (whether used or not).
2621 if (HaveModules)
2622 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2623 else
2624 Args.ClaimAllArgs(options::OPT_fmodule_file);
2625
2626 // When building modules and generating crashdumps, we need to dump a module
2627 // dependency VFS alongside the output.
2628 if (HaveClangModules && C.isForDiagnostics()) {
2629 SmallString<128> VFSDir(Output.getFilename());
2630 llvm::sys::path::replace_extension(VFSDir, ".cache");
2631 // Add the cache directory as a temp so the crash diagnostics pick it up.
2632 C.addTempFile(Args.MakeArgString(VFSDir));
2633
2634 llvm::sys::path::append(VFSDir, "vfs");
2635 CmdArgs.push_back("-module-dependency-dir");
2636 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2637 }
2638
2639 if (HaveClangModules)
2640 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2641
2642 // Pass through all -fmodules-ignore-macro arguments.
2643 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2644 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2645 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2646
2647 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2648
2649 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2650 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2651 D.Diag(diag::err_drv_argument_not_allowed_with)
2652 << A->getAsString(Args) << "-fbuild-session-timestamp";
2653
2654 llvm::sys::fs::file_status Status;
2655 if (llvm::sys::fs::status(A->getValue(), Status))
2656 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2657 CmdArgs.push_back(
2658 Args.MakeArgString("-fbuild-session-timestamp=" +
2659 Twine((uint64_t)Status.getLastModificationTime()
2660 .time_since_epoch()
2661 .count())));
2662 }
2663
2664 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2665 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2666 options::OPT_fbuild_session_file))
2667 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2668
2669 Args.AddLastArg(CmdArgs,
2670 options::OPT_fmodules_validate_once_per_build_session);
2671 }
2672
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002673 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2674 options::OPT_fno_modules_validate_system_headers,
2675 ImplicitModules))
2676 CmdArgs.push_back("-fmodules-validate-system-headers");
2677
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002678 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2679}
2680
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002681static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2682 ArgStringList &CmdArgs) {
2683 // -fsigned-char is default.
2684 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2685 options::OPT_fno_signed_char,
2686 options::OPT_funsigned_char,
2687 options::OPT_fno_unsigned_char)) {
2688 if (A->getOption().matches(options::OPT_funsigned_char) ||
2689 A->getOption().matches(options::OPT_fno_signed_char)) {
2690 CmdArgs.push_back("-fno-signed-char");
2691 }
2692 } else if (!isSignedCharDefault(T)) {
2693 CmdArgs.push_back("-fno-signed-char");
2694 }
2695
Richard Smith3a8244d2018-05-01 05:02:45 +00002696 if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2697 CmdArgs.push_back("-fchar8_t");
2698
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002699 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2700 options::OPT_fno_short_wchar)) {
2701 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2702 CmdArgs.push_back("-fwchar-type=short");
2703 CmdArgs.push_back("-fno-signed-wchar");
2704 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002705 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002706 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002707 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2708 T.getOS() == llvm::Triple::OpenBSD))
2709 CmdArgs.push_back("-fno-signed-wchar");
2710 else
2711 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002712 }
2713 }
2714}
2715
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002716static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2717 const llvm::Triple &T, const ArgList &Args,
2718 ObjCRuntime &Runtime, bool InferCovariantReturns,
2719 const InputInfo &Input, ArgStringList &CmdArgs) {
2720 const llvm::Triple::ArchType Arch = TC.getArch();
2721
2722 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2723 // is the default. Except for deployment target of 10.5, next runtime is
2724 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2725 if (Runtime.isNonFragile()) {
2726 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2727 options::OPT_fno_objc_legacy_dispatch,
2728 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2729 if (TC.UseObjCMixedDispatch())
2730 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2731 else
2732 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2733 }
2734 }
2735
2736 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2737 // to do Array/Dictionary subscripting by default.
2738 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2739 !T.isMacOSXVersionLT(10, 7) &&
2740 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2741 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2742
2743 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2744 // NOTE: This logic is duplicated in ToolChains.cpp.
2745 if (isObjCAutoRefCount(Args)) {
2746 TC.CheckObjCARC();
2747
2748 CmdArgs.push_back("-fobjc-arc");
2749
2750 // FIXME: It seems like this entire block, and several around it should be
2751 // wrapped in isObjC, but for now we just use it here as this is where it
2752 // was being used previously.
2753 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2754 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2755 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2756 else
2757 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2758 }
2759
2760 // Allow the user to enable full exceptions code emission.
2761 // We default off for Objective-C, on for Objective-C++.
2762 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2763 options::OPT_fno_objc_arc_exceptions,
2764 /*default=*/types::isCXX(Input.getType())))
2765 CmdArgs.push_back("-fobjc-arc-exceptions");
2766 }
2767
2768 // Silence warning for full exception code emission options when explicitly
2769 // set to use no ARC.
2770 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2771 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2772 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2773 }
2774
2775 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2776 // rewriter.
2777 if (InferCovariantReturns)
2778 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2779
2780 // Pass down -fobjc-weak or -fno-objc-weak if present.
2781 if (types::isObjC(Input.getType())) {
2782 auto WeakArg =
2783 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2784 if (!WeakArg) {
2785 // nothing to do
2786 } else if (!Runtime.allowsWeak()) {
2787 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2788 D.Diag(diag::err_objc_weak_unsupported);
2789 } else {
2790 WeakArg->render(Args, CmdArgs);
2791 }
2792 }
2793}
2794
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002795static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2796 ArgStringList &CmdArgs) {
2797 bool CaretDefault = true;
2798 bool ColumnDefault = true;
2799
2800 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2801 options::OPT__SLASH_diagnostics_column,
2802 options::OPT__SLASH_diagnostics_caret)) {
2803 switch (A->getOption().getID()) {
2804 case options::OPT__SLASH_diagnostics_caret:
2805 CaretDefault = true;
2806 ColumnDefault = true;
2807 break;
2808 case options::OPT__SLASH_diagnostics_column:
2809 CaretDefault = false;
2810 ColumnDefault = true;
2811 break;
2812 case options::OPT__SLASH_diagnostics_classic:
2813 CaretDefault = false;
2814 ColumnDefault = false;
2815 break;
2816 }
2817 }
2818
2819 // -fcaret-diagnostics is default.
2820 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2821 options::OPT_fno_caret_diagnostics, CaretDefault))
2822 CmdArgs.push_back("-fno-caret-diagnostics");
2823
2824 // -fdiagnostics-fixit-info is default, only pass non-default.
2825 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2826 options::OPT_fno_diagnostics_fixit_info))
2827 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2828
2829 // Enable -fdiagnostics-show-option by default.
2830 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2831 options::OPT_fno_diagnostics_show_option))
2832 CmdArgs.push_back("-fdiagnostics-show-option");
2833
2834 if (const Arg *A =
2835 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2836 CmdArgs.push_back("-fdiagnostics-show-category");
2837 CmdArgs.push_back(A->getValue());
2838 }
2839
2840 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2841 options::OPT_fno_diagnostics_show_hotness, false))
2842 CmdArgs.push_back("-fdiagnostics-show-hotness");
2843
2844 if (const Arg *A =
2845 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2846 std::string Opt =
2847 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2848 CmdArgs.push_back(Args.MakeArgString(Opt));
2849 }
2850
2851 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2852 CmdArgs.push_back("-fdiagnostics-format");
2853 CmdArgs.push_back(A->getValue());
2854 }
2855
2856 if (const Arg *A = Args.getLastArg(
2857 options::OPT_fdiagnostics_show_note_include_stack,
2858 options::OPT_fno_diagnostics_show_note_include_stack)) {
2859 const Option &O = A->getOption();
2860 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2861 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2862 else
2863 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2864 }
2865
2866 // Color diagnostics are parsed by the driver directly from argv and later
2867 // re-parsed to construct this job; claim any possible color diagnostic here
2868 // to avoid warn_drv_unused_argument and diagnose bad
2869 // OPT_fdiagnostics_color_EQ values.
2870 for (const Arg *A : Args) {
2871 const Option &O = A->getOption();
2872 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2873 !O.matches(options::OPT_fdiagnostics_color) &&
2874 !O.matches(options::OPT_fno_color_diagnostics) &&
2875 !O.matches(options::OPT_fno_diagnostics_color) &&
2876 !O.matches(options::OPT_fdiagnostics_color_EQ))
2877 continue;
2878
2879 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2880 StringRef Value(A->getValue());
2881 if (Value != "always" && Value != "never" && Value != "auto")
2882 D.Diag(diag::err_drv_clang_unsupported)
2883 << ("-fdiagnostics-color=" + Value).str();
2884 }
2885 A->claim();
2886 }
2887
2888 if (D.getDiags().getDiagnosticOptions().ShowColors)
2889 CmdArgs.push_back("-fcolor-diagnostics");
2890
2891 if (Args.hasArg(options::OPT_fansi_escape_codes))
2892 CmdArgs.push_back("-fansi-escape-codes");
2893
2894 if (!Args.hasFlag(options::OPT_fshow_source_location,
2895 options::OPT_fno_show_source_location))
2896 CmdArgs.push_back("-fno-show-source-location");
2897
2898 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2899 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2900
2901 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2902 ColumnDefault))
2903 CmdArgs.push_back("-fno-show-column");
2904
2905 if (!Args.hasFlag(options::OPT_fspell_checking,
2906 options::OPT_fno_spell_checking))
2907 CmdArgs.push_back("-fno-spell-checking");
2908}
2909
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002910static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2911 const llvm::Triple &T, const ArgList &Args,
2912 bool EmitCodeView, bool IsWindowsMSVC,
2913 ArgStringList &CmdArgs,
2914 codegenoptions::DebugInfoKind &DebugInfoKind,
2915 const Arg *&SplitDWARFArg) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002916 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2917 options::OPT_fno_debug_info_for_profiling, false))
2918 CmdArgs.push_back("-fdebug-info-for-profiling");
2919
2920 // The 'g' groups options involve a somewhat intricate sequence of decisions
2921 // about what to pass from the driver to the frontend, but by the time they
2922 // reach cc1 they've been factored into three well-defined orthogonal choices:
2923 // * what level of debug info to generate
2924 // * what dwarf version to write
2925 // * what debugger tuning to use
2926 // This avoids having to monkey around further in cc1 other than to disable
2927 // codeview if not running in a Windows environment. Perhaps even that
2928 // decision should be made in the driver as well though.
2929 unsigned DWARFVersion = 0;
2930 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2931
2932 bool SplitDWARFInlining =
2933 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2934 options::OPT_fno_split_dwarf_inlining, true);
2935
2936 Args.ClaimAllArgs(options::OPT_g_Group);
2937
2938 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2939
2940 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2941 // If the last option explicitly specified a debug-info level, use it.
2942 if (A->getOption().matches(options::OPT_gN_Group)) {
2943 DebugInfoKind = DebugLevelToInfoKind(*A);
2944 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2945 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2946 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2947 // This gets a bit more complicated if you've disabled inline info in the
2948 // skeleton CUs (SplitDWARFInlining) - then there's value in composing
2949 // split-dwarf and line-tables-only, so let those compose naturally in
2950 // that case.
2951 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2952 if (SplitDWARFArg) {
2953 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2954 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2955 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2956 SplitDWARFInlining))
2957 SplitDWARFArg = nullptr;
2958 } else if (SplitDWARFInlining)
2959 DebugInfoKind = codegenoptions::NoDebugInfo;
2960 }
2961 } else {
2962 // For any other 'g' option, use Limited.
2963 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2964 }
2965 }
2966
2967 // If a debugger tuning argument appeared, remember it.
2968 if (const Arg *A =
2969 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2970 if (A->getOption().matches(options::OPT_glldb))
2971 DebuggerTuning = llvm::DebuggerKind::LLDB;
2972 else if (A->getOption().matches(options::OPT_gsce))
2973 DebuggerTuning = llvm::DebuggerKind::SCE;
2974 else
2975 DebuggerTuning = llvm::DebuggerKind::GDB;
2976 }
2977
2978 // If a -gdwarf argument appeared, remember it.
2979 if (const Arg *A =
2980 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2981 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2982 DWARFVersion = DwarfVersionNum(A->getSpelling());
2983
2984 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2985 // argument parsing.
Reid Kleckner54af3e72018-02-26 22:55:33 +00002986 if (EmitCodeView) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002987 // DWARFVersion remains at 0 if no explicit choice was made.
2988 CmdArgs.push_back("-gcodeview");
2989 } else if (DWARFVersion == 0 &&
2990 DebugInfoKind != codegenoptions::NoDebugInfo) {
2991 DWARFVersion = TC.GetDefaultDwarfVersion();
2992 }
2993
2994 // We ignore flag -gstrict-dwarf for now.
2995 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2996 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2997
Paul Robinsona8280812017-09-29 21:25:07 +00002998 // Column info is included by default for everything except SCE and CodeView.
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002999 // Clang doesn't track end columns, just starting columns, which, in theory,
3000 // is fine for CodeView (and PDB). In practice, however, the Microsoft
3001 // debuggers don't handle missing end columns well, so it's better not to
3002 // include any column info.
3003 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003004 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003005 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003006 CmdArgs.push_back("-dwarf-column-info");
3007
3008 // FIXME: Move backend command line options to the module.
3009 // If -gline-tables-only is the last option it wins.
3010 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3011 Args.hasArg(options::OPT_gmodules)) {
3012 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3013 CmdArgs.push_back("-dwarf-ext-refs");
3014 CmdArgs.push_back("-fmodule-format=obj");
3015 }
3016
3017 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3018 // splitting and extraction.
3019 // FIXME: Currently only works on Linux.
3020 if (T.isOSLinux()) {
3021 if (!SplitDWARFInlining)
3022 CmdArgs.push_back("-fno-split-dwarf-inlining");
3023
3024 if (SplitDWARFArg) {
3025 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3026 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3027 CmdArgs.push_back("-enable-split-dwarf");
3028 }
3029 }
3030
3031 // After we've dealt with all combinations of things that could
3032 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3033 // figure out if we need to "upgrade" it to standalone debug info.
3034 // We parse these two '-f' options whether or not they will be used,
3035 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3036 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3037 options::OPT_fno_standalone_debug,
3038 TC.GetDefaultStandaloneDebug());
3039 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3040 DebugInfoKind = codegenoptions::FullDebugInfo;
3041
Scott Lindera2fbcef2018-02-26 17:32:31 +00003042 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, false)) {
3043 // Source embedding is a vendor extension to DWARF v5. By now we have
3044 // checked if a DWARF version was stated explicitly, and have otherwise
3045 // fallen back to the target default, so if this is still not at least 5 we
3046 // emit an error.
3047 if (DWARFVersion < 5)
3048 D.Diag(diag::err_drv_argument_only_allowed_with)
3049 << Args.getLastArg(options::OPT_gembed_source)->getAsString(Args)
3050 << "-gdwarf-5";
3051 CmdArgs.push_back("-gembed-source");
3052 }
3053
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003054 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3055 DebuggerTuning);
3056
3057 // -fdebug-macro turns on macro debug info generation.
3058 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3059 false))
3060 CmdArgs.push_back("-debug-info-macro");
3061
3062 // -ggnu-pubnames turns on gnu style pubnames in the backend.
Peter Collingbourneb52e2362017-09-12 21:50:41 +00003063 if (Args.hasArg(options::OPT_ggnu_pubnames))
3064 CmdArgs.push_back("-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003065
3066 // -gdwarf-aranges turns on the emission of the aranges section in the
3067 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003068 // Always enabled for SCE tuning.
3069 if (Args.hasArg(options::OPT_gdwarf_aranges) ||
3070 DebuggerTuning == llvm::DebuggerKind::SCE) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003071 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003072 CmdArgs.push_back("-generate-arange-section");
3073 }
3074
3075 if (Args.hasFlag(options::OPT_fdebug_types_section,
3076 options::OPT_fno_debug_types_section, false)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003077 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003078 CmdArgs.push_back("-generate-type-units");
3079 }
3080
Paul Robinson1787f812017-09-28 18:37:02 +00003081 // Decide how to render forward declarations of template instantiations.
3082 // SCE wants full descriptions, others just get them in the name.
3083 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3084 CmdArgs.push_back("-debug-forward-template-params");
3085
Paul Robinsona8280812017-09-29 21:25:07 +00003086 // Do we need to explicitly import anonymous namespaces into the parent scope?
3087 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3088 CmdArgs.push_back("-dwarf-explicit-import");
3089
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003090 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
3091}
3092
David L. Jonesf561aba2017-03-08 01:02:16 +00003093void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3094 const InputInfo &Output, const InputInfoList &Inputs,
3095 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003096 const llvm::Triple &RawTriple = getToolChain().getTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003097 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3098 const std::string &TripleStr = Triple.getTriple();
3099
3100 bool KernelOrKext =
3101 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3102 const Driver &D = getToolChain().getDriver();
3103 ArgStringList CmdArgs;
3104
3105 // Check number of inputs for sanity. We need at least one input.
3106 assert(Inputs.size() >= 1 && "Must have at least one input.");
3107 const InputInfo &Input = Inputs[0];
3108 // CUDA compilation may have multiple inputs (source file + results of
3109 // device-side compilations). OpenMP device jobs also take the host IR as a
3110 // second input. All other jobs are expected to have exactly one
3111 // input.
3112 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3113 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3114 assert((IsCuda || (IsOpenMPDevice && Inputs.size() == 2) ||
3115 Inputs.size() == 1) &&
3116 "Unable to handle multiple inputs.");
3117
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00003118 const llvm::Triple *AuxTriple =
3119 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3120
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003121 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3122 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3123 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003124 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003125
3126 // Adjust IsWindowsXYZ for CUDA compilations. Even when compiling in device
3127 // mode (i.e., getToolchain().getTriple() is NVPTX, not Windows), we need to
3128 // pass Windows-specific flags to cc1.
3129 if (IsCuda) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003130 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3131 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3132 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3133 }
3134
3135 // C++ is not supported for IAMCU.
3136 if (IsIAMCU && types::isCXX(Input.getType()))
3137 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3138
3139 // Invoke ourselves in -cc1 mode.
3140 //
3141 // FIXME: Implement custom jobs for internal actions.
3142 CmdArgs.push_back("-cc1");
3143
3144 // Add the "effective" target triple.
3145 CmdArgs.push_back("-triple");
3146 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3147
3148 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3149 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3150 Args.ClaimAllArgs(options::OPT_MJ);
3151 }
3152
3153 if (IsCuda) {
3154 // We have to pass the triple of the host if compiling for a CUDA device and
3155 // vice-versa.
3156 std::string NormalizedTriple;
3157 if (JA.isDeviceOffloading(Action::OFK_Cuda))
3158 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3159 ->getTriple()
3160 .normalize();
3161 else
3162 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3163 ->getTriple()
3164 .normalize();
3165
3166 CmdArgs.push_back("-aux-triple");
3167 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3168 }
3169
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003170 if (IsOpenMPDevice) {
3171 // We have to pass the triple of the host if compiling for an OpenMP device.
3172 std::string NormalizedTriple =
3173 C.getSingleOffloadToolChain<Action::OFK_Host>()
3174 ->getTriple()
3175 .normalize();
3176 CmdArgs.push_back("-aux-triple");
3177 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3178 }
3179
David L. Jonesf561aba2017-03-08 01:02:16 +00003180 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3181 Triple.getArch() == llvm::Triple::thumb)) {
3182 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3183 unsigned Version;
3184 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3185 if (Version < 7)
3186 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3187 << TripleStr;
3188 }
3189
3190 // Push all default warning arguments that are specific to
3191 // the given target. These come before user provided warning options
3192 // are provided.
3193 getToolChain().addClangWarningOptions(CmdArgs);
3194
3195 // Select the appropriate action.
3196 RewriteKind rewriteKind = RK_None;
3197
3198 if (isa<AnalyzeJobAction>(JA)) {
3199 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3200 CmdArgs.push_back("-analyze");
3201 } else if (isa<MigrateJobAction>(JA)) {
3202 CmdArgs.push_back("-migrate");
3203 } else if (isa<PreprocessJobAction>(JA)) {
3204 if (Output.getType() == types::TY_Dependencies)
3205 CmdArgs.push_back("-Eonly");
3206 else {
3207 CmdArgs.push_back("-E");
3208 if (Args.hasArg(options::OPT_rewrite_objc) &&
3209 !Args.hasArg(options::OPT_g_Group))
3210 CmdArgs.push_back("-P");
3211 }
3212 } else if (isa<AssembleJobAction>(JA)) {
3213 CmdArgs.push_back("-emit-obj");
3214
3215 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3216
3217 // Also ignore explicit -force_cpusubtype_ALL option.
3218 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3219 } else if (isa<PrecompileJobAction>(JA)) {
3220 // Use PCH if the user requested it.
3221 bool UsePCH = D.CCCUsePCH;
3222
3223 if (JA.getType() == types::TY_Nothing)
3224 CmdArgs.push_back("-fsyntax-only");
3225 else if (JA.getType() == types::TY_ModuleFile)
3226 CmdArgs.push_back("-emit-module-interface");
3227 else if (UsePCH)
3228 CmdArgs.push_back("-emit-pch");
3229 else
3230 CmdArgs.push_back("-emit-pth");
3231 } else if (isa<VerifyPCHJobAction>(JA)) {
3232 CmdArgs.push_back("-verify-pch");
3233 } else {
3234 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3235 "Invalid action for clang tool.");
3236 if (JA.getType() == types::TY_Nothing) {
3237 CmdArgs.push_back("-fsyntax-only");
3238 } else if (JA.getType() == types::TY_LLVM_IR ||
3239 JA.getType() == types::TY_LTO_IR) {
3240 CmdArgs.push_back("-emit-llvm");
3241 } else if (JA.getType() == types::TY_LLVM_BC ||
3242 JA.getType() == types::TY_LTO_BC) {
3243 CmdArgs.push_back("-emit-llvm-bc");
3244 } else if (JA.getType() == types::TY_PP_Asm) {
3245 CmdArgs.push_back("-S");
3246 } else if (JA.getType() == types::TY_AST) {
3247 CmdArgs.push_back("-emit-pch");
3248 } else if (JA.getType() == types::TY_ModuleFile) {
3249 CmdArgs.push_back("-module-file-info");
3250 } else if (JA.getType() == types::TY_RewrittenObjC) {
3251 CmdArgs.push_back("-rewrite-objc");
3252 rewriteKind = RK_NonFragile;
3253 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3254 CmdArgs.push_back("-rewrite-objc");
3255 rewriteKind = RK_Fragile;
3256 } else {
3257 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3258 }
3259
3260 // Preserve use-list order by default when emitting bitcode, so that
3261 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3262 // same result as running passes here. For LTO, we don't need to preserve
3263 // the use-list order, since serialization to bitcode is part of the flow.
3264 if (JA.getType() == types::TY_LLVM_BC)
3265 CmdArgs.push_back("-emit-llvm-uselists");
3266
Artem Belevichecb178b2018-03-21 22:22:59 +00003267 // Device-side jobs do not support LTO.
3268 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3269 JA.isDeviceOffloading(Action::OFK_Host));
3270
3271 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003272 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3273
Paul Robinsond23f2a82017-07-13 21:25:47 +00003274 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3275 // does not support LTO unit features (CFI, whole program vtable opt)
3276 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003277 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003278 D.getLTOMode() == LTOK_Full)
3279 CmdArgs.push_back("-flto-unit");
3280 }
3281 }
3282
3283 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3284 if (!types::isLLVMIR(Input.getType()))
3285 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3286 << "-x ir";
3287 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3288 }
3289
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003290 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003291 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3292
David L. Jonesf561aba2017-03-08 01:02:16 +00003293 // Embed-bitcode option.
3294 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3295 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3296 // Add flags implied by -fembed-bitcode.
3297 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3298 // Disable all llvm IR level optimizations.
3299 CmdArgs.push_back("-disable-llvm-passes");
3300 }
3301 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3302 CmdArgs.push_back("-fembed-bitcode=marker");
3303
3304 // We normally speed up the clang process a bit by skipping destructors at
3305 // exit, but when we're generating diagnostics we can rely on some of the
3306 // cleanup.
3307 if (!C.isForDiagnostics())
3308 CmdArgs.push_back("-disable-free");
3309
David L. Jonesf561aba2017-03-08 01:02:16 +00003310#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003311 const bool IsAssertBuild = false;
3312#else
3313 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003314#endif
3315
Eric Fiselier123c7492018-02-07 18:36:51 +00003316 // Disable the verification pass in -asserts builds.
3317 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003318 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003319
3320 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003321 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3322 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003323 CmdArgs.push_back("-discard-value-names");
3324
David L. Jonesf561aba2017-03-08 01:02:16 +00003325 // Set the main file name, so that debug info works even with
3326 // -save-temps.
3327 CmdArgs.push_back("-main-file-name");
3328 CmdArgs.push_back(getBaseInputName(Args, Input));
3329
3330 // Some flags which affect the language (via preprocessor
3331 // defines).
3332 if (Args.hasArg(options::OPT_static))
3333 CmdArgs.push_back("-static-define");
3334
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003335 if (isa<AnalyzeJobAction>(JA))
3336 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003337
3338 CheckCodeGenerationOptions(D, Args);
3339
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003340 unsigned FunctionAlignment = ParseFunctionAlignment(getToolChain(), Args);
3341 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3342 if (FunctionAlignment) {
3343 CmdArgs.push_back("-function-alignment");
3344 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3345 }
3346
David L. Jonesf561aba2017-03-08 01:02:16 +00003347 llvm::Reloc::Model RelocationModel;
3348 unsigned PICLevel;
3349 bool IsPIE;
3350 std::tie(RelocationModel, PICLevel, IsPIE) =
3351 ParsePICArgs(getToolChain(), Args);
3352
3353 const char *RMName = RelocationModelName(RelocationModel);
3354
3355 if ((RelocationModel == llvm::Reloc::ROPI ||
3356 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3357 types::isCXX(Input.getType()) &&
3358 !Args.hasArg(options::OPT_fallow_unsupported))
3359 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3360
3361 if (RMName) {
3362 CmdArgs.push_back("-mrelocation-model");
3363 CmdArgs.push_back(RMName);
3364 }
3365 if (PICLevel > 0) {
3366 CmdArgs.push_back("-pic-level");
3367 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3368 if (IsPIE)
3369 CmdArgs.push_back("-pic-is-pie");
3370 }
3371
3372 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3373 CmdArgs.push_back("-meabi");
3374 CmdArgs.push_back(A->getValue());
3375 }
3376
3377 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003378 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3379 if (!getToolChain().isThreadModelSupported(A->getValue()))
3380 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3381 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003382 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003383 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003384 else
3385 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3386
3387 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3388
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003389 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3390 options::OPT_fno_merge_all_constants, false))
3391 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003392
3393 // LLVM Code Generator Options.
3394
3395 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3396 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3397 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3398 options::OPT_frewrite_map_file_EQ)) {
3399 StringRef Map = A->getValue();
3400 if (!llvm::sys::fs::exists(Map)) {
3401 D.Diag(diag::err_drv_no_such_file) << Map;
3402 } else {
3403 CmdArgs.push_back("-frewrite-map-file");
3404 CmdArgs.push_back(A->getValue());
3405 A->claim();
3406 }
3407 }
3408 }
3409
3410 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3411 StringRef v = A->getValue();
3412 CmdArgs.push_back("-mllvm");
3413 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3414 A->claim();
3415 }
3416
3417 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3418 true))
3419 CmdArgs.push_back("-fno-jump-tables");
3420
Dehao Chen5e97f232017-08-24 21:37:33 +00003421 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3422 options::OPT_fno_profile_sample_accurate, false))
3423 CmdArgs.push_back("-fprofile-sample-accurate");
3424
David L. Jonesf561aba2017-03-08 01:02:16 +00003425 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3426 options::OPT_fno_preserve_as_comments, true))
3427 CmdArgs.push_back("-fno-preserve-as-comments");
3428
3429 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3430 CmdArgs.push_back("-mregparm");
3431 CmdArgs.push_back(A->getValue());
3432 }
3433
3434 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3435 options::OPT_freg_struct_return)) {
3436 if (getToolChain().getArch() != llvm::Triple::x86) {
3437 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003438 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003439 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3440 CmdArgs.push_back("-fpcc-struct-return");
3441 } else {
3442 assert(A->getOption().matches(options::OPT_freg_struct_return));
3443 CmdArgs.push_back("-freg-struct-return");
3444 }
3445 }
3446
3447 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3448 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3449
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003450 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003451 CmdArgs.push_back("-mdisable-fp-elim");
3452 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3453 options::OPT_fno_zero_initialized_in_bss))
3454 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3455
3456 bool OFastEnabled = isOptimizationLevelFast(Args);
3457 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3458 // enabled. This alias option is being used to simplify the hasFlag logic.
3459 OptSpecifier StrictAliasingAliasOption =
3460 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3461 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3462 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003463 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003464 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3465 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3466 CmdArgs.push_back("-relaxed-aliasing");
3467 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3468 options::OPT_fno_struct_path_tbaa))
3469 CmdArgs.push_back("-no-struct-path-tbaa");
3470 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3471 false))
3472 CmdArgs.push_back("-fstrict-enums");
3473 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3474 true))
3475 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003476 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3477 options::OPT_fno_allow_editor_placeholders, false))
3478 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003479 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3480 options::OPT_fno_strict_vtable_pointers,
3481 false))
3482 CmdArgs.push_back("-fstrict-vtable-pointers");
3483 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3484 options::OPT_fno_optimize_sibling_calls))
3485 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003486 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003487 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003488 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003489
Wei Mi9b3d6272017-10-16 16:50:27 +00003490 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3491 options::OPT_fno_fine_grained_bitfield_accesses);
3492
David L. Jonesf561aba2017-03-08 01:02:16 +00003493 // Handle segmented stacks.
3494 if (Args.hasArg(options::OPT_fsplit_stack))
3495 CmdArgs.push_back("-split-stacks");
3496
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00003497 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003498
3499 // Decide whether to use verbose asm. Verbose assembly is the default on
3500 // toolchains which have the integrated assembler on by default.
3501 bool IsIntegratedAssemblerDefault =
3502 getToolChain().IsIntegratedAssemblerDefault();
3503 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3504 IsIntegratedAssemblerDefault) ||
3505 Args.hasArg(options::OPT_dA))
3506 CmdArgs.push_back("-masm-verbose");
3507
3508 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3509 IsIntegratedAssemblerDefault))
3510 CmdArgs.push_back("-no-integrated-as");
3511
3512 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3513 CmdArgs.push_back("-mdebug-pass");
3514 CmdArgs.push_back("Structure");
3515 }
3516 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3517 CmdArgs.push_back("-mdebug-pass");
3518 CmdArgs.push_back("Arguments");
3519 }
3520
3521 // Enable -mconstructor-aliases except on darwin, where we have to work around
3522 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3523 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003524 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003525 CmdArgs.push_back("-mconstructor-aliases");
3526
3527 // Darwin's kernel doesn't support guard variables; just die if we
3528 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003529 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003530 CmdArgs.push_back("-fforbid-guard-variables");
3531
3532 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3533 false)) {
3534 CmdArgs.push_back("-mms-bitfields");
3535 }
3536
3537 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3538 options::OPT_mno_pie_copy_relocations,
3539 false)) {
3540 CmdArgs.push_back("-mpie-copy-relocations");
3541 }
3542
Sriraman Tallam5c651482017-11-07 19:37:51 +00003543 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3544 CmdArgs.push_back("-fno-plt");
3545 }
3546
Vedant Kumardf502592017-09-12 22:51:53 +00003547 // -fhosted is default.
3548 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3549 // use Freestanding.
3550 bool Freestanding =
3551 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3552 KernelOrKext;
3553 if (Freestanding)
3554 CmdArgs.push_back("-ffreestanding");
3555
David L. Jonesf561aba2017-03-08 01:02:16 +00003556 // This is a coarse approximation of what llvm-gcc actually does, both
3557 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3558 // complicated ways.
3559 bool AsynchronousUnwindTables =
3560 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3561 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00003562 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003563 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003564 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003565 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3566 AsynchronousUnwindTables))
3567 CmdArgs.push_back("-munwind-tables");
3568
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00003569 getToolChain().addClangTargetOptions(Args, CmdArgs,
3570 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003571
3572 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3573 CmdArgs.push_back("-mlimit-float-precision");
3574 CmdArgs.push_back(A->getValue());
3575 }
3576
3577 // FIXME: Handle -mtune=.
3578 (void)Args.hasArg(options::OPT_mtune_EQ);
3579
3580 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3581 CmdArgs.push_back("-mcode-model");
3582 CmdArgs.push_back(A->getValue());
3583 }
3584
3585 // Add the target cpu
3586 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3587 if (!CPU.empty()) {
3588 CmdArgs.push_back("-target-cpu");
3589 CmdArgs.push_back(Args.MakeArgString(CPU));
3590 }
3591
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003592 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003593
David L. Jonesf561aba2017-03-08 01:02:16 +00003594 // These two are potentially updated by AddClangCLArgs.
3595 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3596 bool EmitCodeView = false;
3597
3598 // Add clang-cl arguments.
3599 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003600 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003601 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
Reid Kleckner54af3e72018-02-26 22:55:33 +00003602 else
3603 EmitCodeView = Args.hasArg(options::OPT_gcodeview);
David L. Jonesf561aba2017-03-08 01:02:16 +00003604
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003605 const Arg *SplitDWARFArg = nullptr;
3606 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3607 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3608
3609 // Add the split debug info name to the command lines here so we
3610 // can propagate it to the backend.
3611 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3612 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3613 isa<BackendJobAction>(JA));
3614 const char *SplitDWARFOut;
3615 if (SplitDWARF) {
3616 CmdArgs.push_back("-split-dwarf-file");
3617 SplitDWARFOut = SplitDebugName(Args, Input);
3618 CmdArgs.push_back(SplitDWARFOut);
3619 }
3620
David L. Jonesf561aba2017-03-08 01:02:16 +00003621 // Pass the linker version in use.
3622 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3623 CmdArgs.push_back("-target-linker-version");
3624 CmdArgs.push_back(A->getValue());
3625 }
3626
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003627 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003628 CmdArgs.push_back("-momit-leaf-frame-pointer");
3629
3630 // Explicitly error on some things we know we don't support and can't just
3631 // ignore.
3632 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3633 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003634 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
David L. Jonesf561aba2017-03-08 01:02:16 +00003635 getToolChain().getArch() == llvm::Triple::x86) {
3636 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3637 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3638 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3639 << Unsupported->getOption().getName();
3640 }
Eric Christopher758aad72017-03-21 22:06:18 +00003641 // The faltivec option has been superseded by the maltivec option.
3642 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3643 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3644 << Unsupported->getOption().getName()
3645 << "please use -maltivec and include altivec.h explicitly";
3646 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3647 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3648 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00003649 }
3650
3651 Args.AddAllArgs(CmdArgs, options::OPT_v);
3652 Args.AddLastArg(CmdArgs, options::OPT_H);
3653 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3654 CmdArgs.push_back("-header-include-file");
3655 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3656 : "-");
3657 }
3658 Args.AddLastArg(CmdArgs, options::OPT_P);
3659 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3660
3661 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3662 CmdArgs.push_back("-diagnostic-log-file");
3663 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3664 : "-");
3665 }
3666
David L. Jonesf561aba2017-03-08 01:02:16 +00003667 bool UseSeparateSections = isUseSeparateSections(Triple);
3668
3669 if (Args.hasFlag(options::OPT_ffunction_sections,
3670 options::OPT_fno_function_sections, UseSeparateSections)) {
3671 CmdArgs.push_back("-ffunction-sections");
3672 }
3673
3674 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3675 UseSeparateSections)) {
3676 CmdArgs.push_back("-fdata-sections");
3677 }
3678
3679 if (!Args.hasFlag(options::OPT_funique_section_names,
3680 options::OPT_fno_unique_section_names, true))
3681 CmdArgs.push_back("-fno-unique-section-names");
3682
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00003683 if (auto *A = Args.getLastArg(
3684 options::OPT_finstrument_functions,
3685 options::OPT_finstrument_functions_after_inlining,
3686 options::OPT_finstrument_function_entry_bare))
3687 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003688
Artem Belevichc30bcad2018-01-24 17:41:02 +00003689 // NVPTX doesn't support PGO or coverage. There's no runtime support for
3690 // sampling, overhead of call arc collection is way too high and there's no
3691 // way to collect the output.
3692 if (!Triple.isNVPTX())
3693 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003694
Richard Smithf667ad52017-08-26 01:04:35 +00003695 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3696 ABICompatArg->render(Args, CmdArgs);
3697
David L. Jonesf561aba2017-03-08 01:02:16 +00003698 // Add runtime flag for PS4 when PGO or Coverage are enabled.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003699 if (RawTriple.isPS4CPU())
David L. Jonesf561aba2017-03-08 01:02:16 +00003700 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
3701
3702 // Pass options for controlling the default header search paths.
3703 if (Args.hasArg(options::OPT_nostdinc)) {
3704 CmdArgs.push_back("-nostdsysteminc");
3705 CmdArgs.push_back("-nobuiltininc");
3706 } else {
3707 if (Args.hasArg(options::OPT_nostdlibinc))
3708 CmdArgs.push_back("-nostdsysteminc");
3709 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3710 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3711 }
3712
3713 // Pass the path to compiler resource files.
3714 CmdArgs.push_back("-resource-dir");
3715 CmdArgs.push_back(D.ResourceDir.c_str());
3716
3717 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3718
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00003719 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003720
3721 // Add preprocessing options like -I, -D, etc. if we are using the
3722 // preprocessor.
3723 //
3724 // FIXME: Support -fpreprocessed
3725 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3726 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3727
3728 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3729 // that "The compiler can only warn and ignore the option if not recognized".
3730 // When building with ccache, it will pass -D options to clang even on
3731 // preprocessed inputs and configure concludes that -fPIC is not supported.
3732 Args.ClaimAllArgs(options::OPT_D);
3733
3734 // Manually translate -O4 to -O3; let clang reject others.
3735 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3736 if (A->getOption().matches(options::OPT_O4)) {
3737 CmdArgs.push_back("-O3");
3738 D.Diag(diag::warn_O4_is_O3);
3739 } else {
3740 A->render(Args, CmdArgs);
3741 }
3742 }
3743
3744 // Warn about ignored options to clang.
3745 for (const Arg *A :
3746 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3747 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3748 A->claim();
3749 }
3750
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003751 for (const Arg *A :
3752 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3753 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3754 A->claim();
3755 }
3756
David L. Jonesf561aba2017-03-08 01:02:16 +00003757 claimNoWarnArgs(Args);
3758
3759 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3760
3761 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3762 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3763 CmdArgs.push_back("-pedantic");
3764 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3765 Args.AddLastArg(CmdArgs, options::OPT_w);
3766
3767 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3768 // (-ansi is equivalent to -std=c89 or -std=c++98).
3769 //
3770 // If a std is supplied, only add -trigraphs if it follows the
3771 // option.
3772 bool ImplyVCPPCXXVer = false;
3773 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3774 if (Std->getOption().matches(options::OPT_ansi))
3775 if (types::isCXX(InputType))
3776 CmdArgs.push_back("-std=c++98");
3777 else
3778 CmdArgs.push_back("-std=c89");
3779 else
3780 Std->render(Args, CmdArgs);
3781
3782 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3783 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3784 options::OPT_ftrigraphs,
3785 options::OPT_fno_trigraphs))
3786 if (A != Std)
3787 A->render(Args, CmdArgs);
3788 } else {
3789 // Honor -std-default.
3790 //
3791 // FIXME: Clang doesn't correctly handle -std= when the input language
3792 // doesn't match. For the time being just ignore this for C++ inputs;
3793 // eventually we want to do all the standard defaulting here instead of
3794 // splitting it between the driver and clang -cc1.
3795 if (!types::isCXX(InputType))
3796 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3797 /*Joined=*/true);
3798 else if (IsWindowsMSVC)
3799 ImplyVCPPCXXVer = true;
3800
3801 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3802 options::OPT_fno_trigraphs);
3803 }
3804
3805 // GCC's behavior for -Wwrite-strings is a bit strange:
3806 // * In C, this "warning flag" changes the types of string literals from
3807 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3808 // for the discarded qualifier.
3809 // * In C++, this is just a normal warning flag.
3810 //
3811 // Implementing this warning correctly in C is hard, so we follow GCC's
3812 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3813 // a non-const char* in C, rather than using this crude hack.
3814 if (!types::isCXX(InputType)) {
3815 // FIXME: This should behave just like a warning flag, and thus should also
3816 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3817 Arg *WriteStrings =
3818 Args.getLastArg(options::OPT_Wwrite_strings,
3819 options::OPT_Wno_write_strings, options::OPT_w);
3820 if (WriteStrings &&
3821 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3822 CmdArgs.push_back("-fconst-strings");
3823 }
3824
3825 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3826 // during C++ compilation, which it is by default. GCC keeps this define even
3827 // in the presence of '-w', match this behavior bug-for-bug.
3828 if (types::isCXX(InputType) &&
3829 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3830 true)) {
3831 CmdArgs.push_back("-fdeprecated-macro");
3832 }
3833
3834 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3835 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3836 if (Asm->getOption().matches(options::OPT_fasm))
3837 CmdArgs.push_back("-fgnu-keywords");
3838 else
3839 CmdArgs.push_back("-fno-gnu-keywords");
3840 }
3841
3842 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3843 CmdArgs.push_back("-fno-dwarf-directory-asm");
3844
3845 if (ShouldDisableAutolink(Args, getToolChain()))
3846 CmdArgs.push_back("-fno-autolink");
3847
3848 // Add in -fdebug-compilation-dir if necessary.
3849 addDebugCompDirArg(Args, CmdArgs);
3850
3851 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3852 StringRef Map = A->getValue();
3853 if (Map.find('=') == StringRef::npos)
3854 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3855 else
3856 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3857 A->claim();
3858 }
3859
3860 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3861 options::OPT_ftemplate_depth_EQ)) {
3862 CmdArgs.push_back("-ftemplate-depth");
3863 CmdArgs.push_back(A->getValue());
3864 }
3865
3866 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3867 CmdArgs.push_back("-foperator-arrow-depth");
3868 CmdArgs.push_back(A->getValue());
3869 }
3870
3871 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3872 CmdArgs.push_back("-fconstexpr-depth");
3873 CmdArgs.push_back(A->getValue());
3874 }
3875
3876 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3877 CmdArgs.push_back("-fconstexpr-steps");
3878 CmdArgs.push_back(A->getValue());
3879 }
3880
3881 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3882 CmdArgs.push_back("-fbracket-depth");
3883 CmdArgs.push_back(A->getValue());
3884 }
3885
3886 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3887 options::OPT_Wlarge_by_value_copy_def)) {
3888 if (A->getNumValues()) {
3889 StringRef bytes = A->getValue();
3890 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3891 } else
3892 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3893 }
3894
3895 if (Args.hasArg(options::OPT_relocatable_pch))
3896 CmdArgs.push_back("-relocatable-pch");
3897
3898 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3899 CmdArgs.push_back("-fconstant-string-class");
3900 CmdArgs.push_back(A->getValue());
3901 }
3902
3903 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3904 CmdArgs.push_back("-ftabstop");
3905 CmdArgs.push_back(A->getValue());
3906 }
3907
Sean Eveson5110d4f2018-01-08 13:42:26 +00003908 if (Args.hasFlag(options::OPT_fstack_size_section,
3909 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3910 CmdArgs.push_back("-fstack-size-section");
3911
David L. Jonesf561aba2017-03-08 01:02:16 +00003912 CmdArgs.push_back("-ferror-limit");
3913 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3914 CmdArgs.push_back(A->getValue());
3915 else
3916 CmdArgs.push_back("19");
3917
3918 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3919 CmdArgs.push_back("-fmacro-backtrace-limit");
3920 CmdArgs.push_back(A->getValue());
3921 }
3922
3923 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3924 CmdArgs.push_back("-ftemplate-backtrace-limit");
3925 CmdArgs.push_back(A->getValue());
3926 }
3927
3928 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3929 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3930 CmdArgs.push_back(A->getValue());
3931 }
3932
3933 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3934 CmdArgs.push_back("-fspell-checking-limit");
3935 CmdArgs.push_back(A->getValue());
3936 }
3937
3938 // Pass -fmessage-length=.
3939 CmdArgs.push_back("-fmessage-length");
3940 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3941 CmdArgs.push_back(A->getValue());
3942 } else {
3943 // If -fmessage-length=N was not specified, determine whether this is a
3944 // terminal and, if so, implicitly define -fmessage-length appropriately.
3945 unsigned N = llvm::sys::Process::StandardErrColumns();
3946 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3947 }
3948
3949 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3950 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3951 options::OPT_fvisibility_ms_compat)) {
3952 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3953 CmdArgs.push_back("-fvisibility");
3954 CmdArgs.push_back(A->getValue());
3955 } else {
3956 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3957 CmdArgs.push_back("-fvisibility");
3958 CmdArgs.push_back("hidden");
3959 CmdArgs.push_back("-ftype-visibility");
3960 CmdArgs.push_back("default");
3961 }
3962 }
3963
3964 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3965
3966 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3967
David L. Jonesf561aba2017-03-08 01:02:16 +00003968 // Forward -f (flag) options which we can pass directly.
3969 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3970 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3971 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00003972 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
3973 options::OPT_fno_emulated_tls);
3974
David L. Jonesf561aba2017-03-08 01:02:16 +00003975 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003976 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003977 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003978
David L. Jonesf561aba2017-03-08 01:02:16 +00003979 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3980 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3981
3982 // Forward flags for OpenMP. We don't do this if the current action is an
3983 // device offloading action other than OpenMP.
3984 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3985 options::OPT_fno_openmp, false) &&
3986 (JA.isDeviceOffloading(Action::OFK_None) ||
3987 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003988 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003989 case Driver::OMPRT_OMP:
3990 case Driver::OMPRT_IOMP5:
3991 // Clang can generate useful OpenMP code for these two runtime libraries.
3992 CmdArgs.push_back("-fopenmp");
3993
3994 // If no option regarding the use of TLS in OpenMP codegeneration is
3995 // given, decide a default based on the target. Otherwise rely on the
3996 // options and pass the right information to the frontend.
3997 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3998 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3999 CmdArgs.push_back("-fnoopenmp-use-tls");
4000 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Carlo Bertolli79712092018-02-28 20:48:35 +00004001
4002 // When in OpenMP offloading mode with NVPTX target, forward
4003 // cuda-mode flag
4004 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_cuda_mode,
4005 options::OPT_fno_openmp_cuda_mode);
David L. Jonesf561aba2017-03-08 01:02:16 +00004006 break;
4007 default:
4008 // By default, if Clang doesn't know how to generate useful OpenMP code
4009 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4010 // down to the actual compilation.
4011 // FIXME: It would be better to have a mode which *only* omits IR
4012 // generation based on the OpenMP support so that we get consistent
4013 // semantic analysis, etc.
4014 break;
4015 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004016 } else {
4017 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4018 options::OPT_fno_openmp_simd);
4019 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004020 }
4021
4022 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4023 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4024
Dean Michael Berris835832d2017-03-30 00:29:36 +00004025 const XRayArgs &XRay = getToolChain().getXRayArgs();
4026 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
4027
David L. Jonesf561aba2017-03-08 01:02:16 +00004028 if (getToolChain().SupportsProfiling())
4029 Args.AddLastArg(CmdArgs, options::OPT_pg);
4030
4031 if (getToolChain().SupportsProfiling())
4032 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4033
4034 // -flax-vector-conversions is default.
4035 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4036 options::OPT_fno_lax_vector_conversions))
4037 CmdArgs.push_back("-fno-lax-vector-conversions");
4038
4039 if (Args.getLastArg(options::OPT_fapple_kext) ||
4040 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4041 CmdArgs.push_back("-fapple-kext");
4042
4043 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4044 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4045 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4046 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4047 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4048
4049 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4050 CmdArgs.push_back("-ftrapv-handler");
4051 CmdArgs.push_back(A->getValue());
4052 }
4053
4054 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4055
4056 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4057 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4058 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4059 if (A->getOption().matches(options::OPT_fwrapv))
4060 CmdArgs.push_back("-fwrapv");
4061 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4062 options::OPT_fno_strict_overflow)) {
4063 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4064 CmdArgs.push_back("-fwrapv");
4065 }
4066
4067 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4068 options::OPT_fno_reroll_loops))
4069 if (A->getOption().matches(options::OPT_freroll_loops))
4070 CmdArgs.push_back("-freroll-loops");
4071
4072 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4073 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4074 options::OPT_fno_unroll_loops);
4075
4076 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4077
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00004078 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004079
4080 // Translate -mstackrealign
4081 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4082 false))
4083 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4084
4085 if (Args.hasArg(options::OPT_mstack_alignment)) {
4086 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4087 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4088 }
4089
4090 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4091 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4092
4093 if (!Size.empty())
4094 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4095 else
4096 CmdArgs.push_back("-mstack-probe-size=0");
4097 }
4098
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004099 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4100 options::OPT_mno_stack_arg_probe, true))
4101 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4102
David L. Jonesf561aba2017-03-08 01:02:16 +00004103 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4104 options::OPT_mno_restrict_it)) {
4105 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004106 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004107 CmdArgs.push_back("-arm-restrict-it");
4108 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004109 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004110 CmdArgs.push_back("-arm-no-restrict-it");
4111 }
4112 } else if (Triple.isOSWindows() &&
4113 (Triple.getArch() == llvm::Triple::arm ||
4114 Triple.getArch() == llvm::Triple::thumb)) {
4115 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004116 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004117 CmdArgs.push_back("-arm-restrict-it");
4118 }
4119
4120 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004121 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004122
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004123 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4124 CmdArgs.push_back(
4125 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4126 }
4127
David L. Jonesf561aba2017-03-08 01:02:16 +00004128 // Forward -f options with positive and negative forms; we translate
4129 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004130 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004131 StringRef fname = A->getValue();
4132 if (!llvm::sys::fs::exists(fname))
4133 D.Diag(diag::err_drv_no_such_file) << fname;
4134 else
4135 A->render(Args, CmdArgs);
4136 }
4137
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00004138 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004139
4140 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4141 options::OPT_fno_assume_sane_operator_new))
4142 CmdArgs.push_back("-fno-assume-sane-operator-new");
4143
4144 // -fblocks=0 is default.
4145 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4146 getToolChain().IsBlocksDefault()) ||
4147 (Args.hasArg(options::OPT_fgnu_runtime) &&
4148 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4149 !Args.hasArg(options::OPT_fno_blocks))) {
4150 CmdArgs.push_back("-fblocks");
4151
4152 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4153 !getToolChain().hasBlocksRuntime())
4154 CmdArgs.push_back("-fblocks-runtime-optional");
4155 }
4156
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004157 // -fencode-extended-block-signature=1 is default.
4158 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4159 CmdArgs.push_back("-fencode-extended-block-signature");
4160
David L. Jonesf561aba2017-03-08 01:02:16 +00004161 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4162 false) &&
4163 types::isCXX(InputType)) {
4164 CmdArgs.push_back("-fcoroutines-ts");
4165 }
4166
Aaron Ballman61736552017-10-21 20:28:58 +00004167 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4168 options::OPT_fno_double_square_bracket_attributes);
4169
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004170 bool HaveModules = false;
4171 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004172
4173 // -faccess-control is default.
4174 if (Args.hasFlag(options::OPT_fno_access_control,
4175 options::OPT_faccess_control, false))
4176 CmdArgs.push_back("-fno-access-control");
4177
4178 // -felide-constructors is the default.
4179 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4180 options::OPT_felide_constructors, false))
4181 CmdArgs.push_back("-fno-elide-constructors");
4182
4183 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4184
4185 if (KernelOrKext || (types::isCXX(InputType) &&
4186 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4187 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4188 CmdArgs.push_back("-fno-rtti");
4189
4190 // -fshort-enums=0 is default for all architectures except Hexagon.
4191 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4192 getToolChain().getArch() == llvm::Triple::hexagon))
4193 CmdArgs.push_back("-fshort-enums");
4194
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004195 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004196
4197 // -fuse-cxa-atexit is default.
4198 if (!Args.hasFlag(
4199 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004200 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004201 RawTriple.getOS() != llvm::Triple::Solaris &&
David L. Jonesf561aba2017-03-08 01:02:16 +00004202 getToolChain().getArch() != llvm::Triple::hexagon &&
4203 getToolChain().getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004204 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4205 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004206 KernelOrKext)
4207 CmdArgs.push_back("-fno-use-cxa-atexit");
4208
Akira Hatanaka617e2612018-04-17 18:41:52 +00004209 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4210 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004211 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004212 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4213
David L. Jonesf561aba2017-03-08 01:02:16 +00004214 // -fms-extensions=0 is default.
4215 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4216 IsWindowsMSVC))
4217 CmdArgs.push_back("-fms-extensions");
4218
Martin Storsjoc3363922018-05-07 20:26:09 +00004219 // -fno-use-line-directives is default, except for MSVC targets.
David L. Jonesf561aba2017-03-08 01:02:16 +00004220 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjoc3363922018-05-07 20:26:09 +00004221 options::OPT_fno_use_line_directives, IsWindowsMSVC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004222 CmdArgs.push_back("-fuse-line-directives");
4223
4224 // -fms-compatibility=0 is default.
4225 if (Args.hasFlag(options::OPT_fms_compatibility,
4226 options::OPT_fno_ms_compatibility,
4227 (IsWindowsMSVC &&
4228 Args.hasFlag(options::OPT_fms_extensions,
4229 options::OPT_fno_ms_extensions, true))))
4230 CmdArgs.push_back("-fms-compatibility");
4231
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004232 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004233 if (!MSVT.empty())
4234 CmdArgs.push_back(
4235 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4236
4237 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4238 if (ImplyVCPPCXXVer) {
4239 StringRef LanguageStandard;
4240 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4241 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4242 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004243 .Case("c++17", "-std=c++17")
4244 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004245 .Default("");
4246 if (LanguageStandard.empty())
4247 D.Diag(clang::diag::warn_drv_unused_argument)
4248 << StdArg->getAsString(Args);
4249 }
4250
4251 if (LanguageStandard.empty()) {
4252 if (IsMSVC2015Compatible)
4253 LanguageStandard = "-std=c++14";
4254 else
4255 LanguageStandard = "-std=c++11";
4256 }
4257
4258 CmdArgs.push_back(LanguageStandard.data());
4259 }
4260
4261 // -fno-borland-extensions is default.
4262 if (Args.hasFlag(options::OPT_fborland_extensions,
4263 options::OPT_fno_borland_extensions, false))
4264 CmdArgs.push_back("-fborland-extensions");
4265
4266 // -fno-declspec is default, except for PS4.
4267 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004268 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004269 CmdArgs.push_back("-fdeclspec");
4270 else if (Args.hasArg(options::OPT_fno_declspec))
4271 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4272
4273 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4274 // than 19.
4275 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4276 options::OPT_fno_threadsafe_statics,
4277 !IsWindowsMSVC || IsMSVC2015Compatible))
4278 CmdArgs.push_back("-fno-threadsafe-statics");
4279
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004280 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004281 // Many old Windows SDK versions require this to parse.
4282 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4283 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004284 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4285 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4286 CmdArgs.push_back("-fdelayed-template-parsing");
4287
4288 // -fgnu-keywords default varies depending on language; only pass if
4289 // specified.
4290 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4291 options::OPT_fno_gnu_keywords))
4292 A->render(Args, CmdArgs);
4293
4294 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4295 false))
4296 CmdArgs.push_back("-fgnu89-inline");
4297
4298 if (Args.hasArg(options::OPT_fno_inline))
4299 CmdArgs.push_back("-fno-inline");
4300
4301 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4302 options::OPT_finline_hint_functions,
4303 options::OPT_fno_inline_functions))
4304 InlineArg->render(Args, CmdArgs);
4305
4306 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4307 options::OPT_fno_experimental_new_pass_manager);
4308
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004309 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4310 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4311 rewriteKind != RK_None, Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004312
4313 if (Args.hasFlag(options::OPT_fapplication_extension,
4314 options::OPT_fno_application_extension, false))
4315 CmdArgs.push_back("-fapplication-extension");
4316
4317 // Handle GCC-style exception args.
4318 if (!C.getDriver().IsCLMode())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004319 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
David L. Jonesf561aba2017-03-08 01:02:16 +00004320 CmdArgs);
4321
Martell Malonec950c652017-11-29 07:25:12 +00004322 // Handle exception personalities
4323 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4324 options::OPT_fseh_exceptions,
4325 options::OPT_fdwarf_exceptions);
4326 if (A) {
4327 const Option &Opt = A->getOption();
4328 if (Opt.matches(options::OPT_fsjlj_exceptions))
4329 CmdArgs.push_back("-fsjlj-exceptions");
4330 if (Opt.matches(options::OPT_fseh_exceptions))
4331 CmdArgs.push_back("-fseh-exceptions");
4332 if (Opt.matches(options::OPT_fdwarf_exceptions))
4333 CmdArgs.push_back("-fdwarf-exceptions");
4334 } else {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004335 switch (getToolChain().GetExceptionModel(Args)) {
4336 default:
4337 break;
4338 case llvm::ExceptionHandling::DwarfCFI:
4339 CmdArgs.push_back("-fdwarf-exceptions");
4340 break;
4341 case llvm::ExceptionHandling::SjLj:
4342 CmdArgs.push_back("-fsjlj-exceptions");
4343 break;
4344 case llvm::ExceptionHandling::WinEH:
4345 CmdArgs.push_back("-fseh-exceptions");
4346 break;
Martell Malonec950c652017-11-29 07:25:12 +00004347 }
4348 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004349
4350 // C++ "sane" operator new.
4351 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4352 options::OPT_fno_assume_sane_operator_new))
4353 CmdArgs.push_back("-fno-assume-sane-operator-new");
4354
4355 // -frelaxed-template-template-args is off by default, as it is a severe
4356 // breaking change until a corresponding change to template partial ordering
4357 // is provided.
4358 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4359 options::OPT_fno_relaxed_template_template_args, false))
4360 CmdArgs.push_back("-frelaxed-template-template-args");
4361
4362 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4363 // most platforms.
4364 if (Args.hasFlag(options::OPT_fsized_deallocation,
4365 options::OPT_fno_sized_deallocation, false))
4366 CmdArgs.push_back("-fsized-deallocation");
4367
4368 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4369 // by default.
4370 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4371 options::OPT_fno_aligned_allocation,
4372 options::OPT_faligned_new_EQ)) {
4373 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4374 CmdArgs.push_back("-fno-aligned-allocation");
4375 else
4376 CmdArgs.push_back("-faligned-allocation");
4377 }
4378
4379 // The default new alignment can be specified using a dedicated option or via
4380 // a GCC-compatible option that also turns on aligned allocation.
4381 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4382 options::OPT_faligned_new_EQ))
4383 CmdArgs.push_back(
4384 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4385
4386 // -fconstant-cfstrings is default, and may be subject to argument translation
4387 // on Darwin.
4388 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4389 options::OPT_fno_constant_cfstrings) ||
4390 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4391 options::OPT_mno_constant_cfstrings))
4392 CmdArgs.push_back("-fno-constant-cfstrings");
4393
David L. Jonesf561aba2017-03-08 01:02:16 +00004394 // -fno-pascal-strings is default, only pass non-default.
4395 if (Args.hasFlag(options::OPT_fpascal_strings,
4396 options::OPT_fno_pascal_strings, false))
4397 CmdArgs.push_back("-fpascal-strings");
4398
4399 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4400 // -fno-pack-struct doesn't apply to -fpack-struct=.
4401 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4402 std::string PackStructStr = "-fpack-struct=";
4403 PackStructStr += A->getValue();
4404 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4405 } else if (Args.hasFlag(options::OPT_fpack_struct,
4406 options::OPT_fno_pack_struct, false)) {
4407 CmdArgs.push_back("-fpack-struct=1");
4408 }
4409
4410 // Handle -fmax-type-align=N and -fno-type-align
4411 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4412 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4413 if (!SkipMaxTypeAlign) {
4414 std::string MaxTypeAlignStr = "-fmax-type-align=";
4415 MaxTypeAlignStr += A->getValue();
4416 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4417 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004418 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004419 if (!SkipMaxTypeAlign) {
4420 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4421 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4422 }
4423 }
4424
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004425 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4426 CmdArgs.push_back("-Qn");
4427
David L. Jonesf561aba2017-03-08 01:02:16 +00004428 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004429 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004430 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4431 !NoCommonDefault))
4432 CmdArgs.push_back("-fno-common");
4433
4434 // -fsigned-bitfields is default, and clang doesn't yet support
4435 // -funsigned-bitfields.
4436 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4437 options::OPT_funsigned_bitfields))
4438 D.Diag(diag::warn_drv_clang_unsupported)
4439 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4440
4441 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4442 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4443 D.Diag(diag::err_drv_clang_unsupported)
4444 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4445
4446 // -finput_charset=UTF-8 is default. Reject others
4447 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4448 StringRef value = inputCharset->getValue();
4449 if (!value.equals_lower("utf-8"))
4450 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4451 << value;
4452 }
4453
4454 // -fexec_charset=UTF-8 is default. Reject others
4455 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4456 StringRef value = execCharset->getValue();
4457 if (!value.equals_lower("utf-8"))
4458 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4459 << value;
4460 }
4461
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004462 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004463
4464 // -fno-asm-blocks is default.
4465 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4466 false))
4467 CmdArgs.push_back("-fasm-blocks");
4468
4469 // -fgnu-inline-asm is default.
4470 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4471 options::OPT_fno_gnu_inline_asm, true))
4472 CmdArgs.push_back("-fno-gnu-inline-asm");
4473
4474 // Enable vectorization per default according to the optimization level
4475 // selected. For optimization levels that want vectorization we use the alias
4476 // option to simplify the hasFlag logic.
4477 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4478 OptSpecifier VectorizeAliasOption =
4479 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4480 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4481 options::OPT_fno_vectorize, EnableVec))
4482 CmdArgs.push_back("-vectorize-loops");
4483
4484 // -fslp-vectorize is enabled based on the optimization level selected.
4485 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4486 OptSpecifier SLPVectAliasOption =
4487 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4488 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4489 options::OPT_fno_slp_vectorize, EnableSLPVec))
4490 CmdArgs.push_back("-vectorize-slp");
4491
Craig Topper9a724aa2017-12-11 21:09:19 +00004492 ParseMPreferVectorWidth(D, Args, CmdArgs);
4493
David L. Jonesf561aba2017-03-08 01:02:16 +00004494 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4495 A->render(Args, CmdArgs);
4496
4497 if (Arg *A = Args.getLastArg(
4498 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4499 A->render(Args, CmdArgs);
4500
4501 // -fdollars-in-identifiers default varies depending on platform and
4502 // language; only pass if specified.
4503 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4504 options::OPT_fno_dollars_in_identifiers)) {
4505 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4506 CmdArgs.push_back("-fdollars-in-identifiers");
4507 else
4508 CmdArgs.push_back("-fno-dollars-in-identifiers");
4509 }
4510
4511 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4512 // practical purposes.
4513 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4514 options::OPT_fno_unit_at_a_time)) {
4515 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4516 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4517 }
4518
4519 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4520 options::OPT_fno_apple_pragma_pack, false))
4521 CmdArgs.push_back("-fapple-pragma-pack");
4522
David L. Jonesf561aba2017-03-08 01:02:16 +00004523 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004524 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004525 options::OPT_fno_save_optimization_record, false)) {
4526 CmdArgs.push_back("-opt-record-file");
4527
4528 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4529 if (A) {
4530 CmdArgs.push_back(A->getValue());
4531 } else {
4532 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004533
4534 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4535 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4536 F = FinalOutput->getValue();
4537 }
4538
4539 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004540 // Use the input filename.
4541 F = llvm::sys::path::stem(Input.getBaseInput());
4542
4543 // If we're compiling for an offload architecture (i.e. a CUDA device),
4544 // we need to make the file name for the device compilation different
4545 // from the host compilation.
4546 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4547 !JA.isDeviceOffloading(Action::OFK_Host)) {
4548 llvm::sys::path::replace_extension(F, "");
4549 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4550 Triple.normalize());
4551 F += "-";
4552 F += JA.getOffloadingArch();
4553 }
4554 }
4555
4556 llvm::sys::path::replace_extension(F, "opt.yaml");
4557 CmdArgs.push_back(Args.MakeArgString(F));
4558 }
4559 }
4560
Richard Smith86a3ef52017-06-09 21:24:02 +00004561 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4562 options::OPT_fno_rewrite_imports, false);
4563 if (RewriteImports)
4564 CmdArgs.push_back("-frewrite-imports");
4565
David L. Jonesf561aba2017-03-08 01:02:16 +00004566 // Enable rewrite includes if the user's asked for it or if we're generating
4567 // diagnostics.
4568 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4569 // nice to enable this when doing a crashdump for modules as well.
4570 if (Args.hasFlag(options::OPT_frewrite_includes,
4571 options::OPT_fno_rewrite_includes, false) ||
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004572 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004573 CmdArgs.push_back("-frewrite-includes");
4574
4575 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4576 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4577 options::OPT_traditional_cpp)) {
4578 if (isa<PreprocessJobAction>(JA))
4579 CmdArgs.push_back("-traditional-cpp");
4580 else
4581 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4582 }
4583
4584 Args.AddLastArg(CmdArgs, options::OPT_dM);
4585 Args.AddLastArg(CmdArgs, options::OPT_dD);
4586
4587 // Handle serialized diagnostics.
4588 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4589 CmdArgs.push_back("-serialize-diagnostic-file");
4590 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4591 }
4592
4593 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4594 CmdArgs.push_back("-fretain-comments-from-system-headers");
4595
4596 // Forward -fcomment-block-commands to -cc1.
4597 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4598 // Forward -fparse-all-comments to -cc1.
4599 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4600
4601 // Turn -fplugin=name.so into -load name.so
4602 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4603 CmdArgs.push_back("-load");
4604 CmdArgs.push_back(A->getValue());
4605 A->claim();
4606 }
4607
4608 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00004609 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4610 if (!StatsFile.empty())
4611 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00004612
4613 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4614 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004615 // -finclude-default-header flag is for preprocessor,
4616 // do not pass it to other cc1 commands when save-temps is enabled
4617 if (C.getDriver().isSaveTempsEnabled() &&
4618 !isa<PreprocessJobAction>(JA)) {
4619 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4620 Arg->claim();
4621 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4622 CmdArgs.push_back(Arg->getValue());
4623 }
4624 }
4625 else {
4626 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4627 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004628 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4629 A->claim();
4630
4631 // We translate this by hand to the -cc1 argument, since nightly test uses
4632 // it and developers have been trained to spell it with -mllvm. Both
4633 // spellings are now deprecated and should be removed.
4634 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4635 CmdArgs.push_back("-disable-llvm-optzns");
4636 } else {
4637 A->render(Args, CmdArgs);
4638 }
4639 }
4640
4641 // With -save-temps, we want to save the unoptimized bitcode output from the
4642 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4643 // by the frontend.
4644 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4645 // has slightly different breakdown between stages.
4646 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4647 // pristine IR generated by the frontend. Ideally, a new compile action should
4648 // be added so both IR can be captured.
4649 if (C.getDriver().isSaveTempsEnabled() &&
4650 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4651 isa<CompileJobAction>(JA))
4652 CmdArgs.push_back("-disable-llvm-passes");
4653
4654 if (Output.getType() == types::TY_Dependencies) {
4655 // Handled with other dependency code.
4656 } else if (Output.isFilename()) {
4657 CmdArgs.push_back("-o");
4658 CmdArgs.push_back(Output.getFilename());
4659 } else {
4660 assert(Output.isNothing() && "Invalid output.");
4661 }
4662
4663 addDashXForInput(Args, Input, CmdArgs);
4664
4665 if (Input.isFilename())
4666 CmdArgs.push_back(Input.getFilename());
4667 else
4668 Input.getInputArg().renderAsInput(Args, CmdArgs);
4669
4670 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4671
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004672 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00004673
4674 // Optionally embed the -cc1 level arguments into the debug info, for build
4675 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004676 // Also record command line arguments into the debug info if
4677 // -grecord-gcc-switches options is set on.
4678 // By default, -gno-record-gcc-switches is set on and no recording.
4679 if (getToolChain().UseDwarfDebugFlags() ||
4680 Args.hasFlag(options::OPT_grecord_gcc_switches,
4681 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004682 ArgStringList OriginalArgs;
4683 for (const auto &Arg : Args)
4684 Arg->render(Args, OriginalArgs);
4685
4686 SmallString<256> Flags;
4687 Flags += Exec;
4688 for (const char *OriginalArg : OriginalArgs) {
4689 SmallString<128> EscapedArg;
4690 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4691 Flags += " ";
4692 Flags += EscapedArg;
4693 }
4694 CmdArgs.push_back("-dwarf-debug-flags");
4695 CmdArgs.push_back(Args.MakeArgString(Flags));
4696 }
4697
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004698 if (IsCuda) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004699 // Host-side cuda compilation receives all device-side outputs in a single
4700 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004701 if (Inputs.size() > 1) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004702 assert(Inputs.size() == 2 && "More than one GPU binary!");
4703 CmdArgs.push_back("-fcuda-include-gpubinary");
4704 CmdArgs.push_back(Inputs[1].getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00004705 }
4706
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004707 if (Args.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc, false))
4708 CmdArgs.push_back("-fcuda-rdc");
4709 }
4710
David L. Jonesf561aba2017-03-08 01:02:16 +00004711 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4712 // to specify the result of the compile phase on the host, so the meaningful
4713 // device declarations can be identified. Also, -fopenmp-is-device is passed
4714 // along to tell the frontend that it is generating code for a device, so that
4715 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004716 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004717 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004718 if (Inputs.size() == 2) {
4719 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4720 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4721 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004722 }
4723
4724 // For all the host OpenMP offloading compile jobs we need to pass the targets
4725 // information using -fopenmp-targets= option.
4726 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4727 SmallString<128> TargetInfo("-fopenmp-targets=");
4728
4729 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4730 assert(Tgts && Tgts->getNumValues() &&
4731 "OpenMP offloading has to have targets specified.");
4732 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4733 if (i)
4734 TargetInfo += ',';
4735 // We need to get the string from the triple because it may be not exactly
4736 // the same as the one we get directly from the arguments.
4737 llvm::Triple T(Tgts->getValue(i));
4738 TargetInfo += T.getTriple();
4739 }
4740 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4741 }
4742
4743 bool WholeProgramVTables =
4744 Args.hasFlag(options::OPT_fwhole_program_vtables,
4745 options::OPT_fno_whole_program_vtables, false);
4746 if (WholeProgramVTables) {
4747 if (!D.isUsingLTO())
4748 D.Diag(diag::err_drv_argument_only_allowed_with)
4749 << "-fwhole-program-vtables"
4750 << "-flto";
4751 CmdArgs.push_back("-fwhole-program-vtables");
4752 }
4753
Amara Emerson4ee9f822018-01-26 00:27:22 +00004754 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4755 options::OPT_fno_experimental_isel)) {
4756 CmdArgs.push_back("-mllvm");
4757 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4758 CmdArgs.push_back("-global-isel=1");
4759
4760 // GISel is on by default on AArch64 -O0, so don't bother adding
4761 // the fallback remarks for it. Other combinations will add a warning of
4762 // some kind.
4763 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4764 bool IsOptLevelSupported = false;
4765
4766 Arg *A = Args.getLastArg(options::OPT_O_Group);
4767 if (Triple.getArch() == llvm::Triple::aarch64) {
4768 if (!A || A->getOption().matches(options::OPT_O0))
4769 IsOptLevelSupported = true;
4770 }
4771 if (!IsArchSupported || !IsOptLevelSupported) {
4772 CmdArgs.push_back("-mllvm");
4773 CmdArgs.push_back("-global-isel-abort=2");
4774
4775 if (!IsArchSupported)
4776 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4777 else
4778 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4779 }
4780 } else {
4781 CmdArgs.push_back("-global-isel=0");
4782 }
4783 }
4784
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00004785 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
4786 options::OPT_fno_force_enable_int128)) {
4787 if (A->getOption().matches(options::OPT_fforce_enable_int128))
4788 CmdArgs.push_back("-fforce-enable-int128");
4789 }
4790
David L. Jonesf561aba2017-03-08 01:02:16 +00004791 // Finally add the compile command to the compilation.
4792 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4793 Output.getType() == types::TY_Object &&
4794 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4795 auto CLCommand =
4796 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4797 C.addCommand(llvm::make_unique<FallbackCommand>(
4798 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4799 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4800 isa<PrecompileJobAction>(JA)) {
4801 // In /fallback builds, run the main compilation even if the pch generation
4802 // fails, so that the main compilation's fallback to cl.exe runs.
4803 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4804 CmdArgs, Inputs));
4805 } else {
4806 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4807 }
4808
4809 // Handle the debug info splitting at object creation time if we're
4810 // creating an object.
4811 // TODO: Currently only works on linux with newer objcopy.
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004812 if (SplitDWARF && Output.getType() == types::TY_Object)
4813 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDWARFOut);
David L. Jonesf561aba2017-03-08 01:02:16 +00004814
4815 if (Arg *A = Args.getLastArg(options::OPT_pg))
4816 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4817 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4818 << A->getAsString(Args);
4819
4820 // Claim some arguments which clang supports automatically.
4821
4822 // -fpch-preprocess is used with gcc to add a special marker in the output to
4823 // include the PCH file. Clang's PTH solution is completely transparent, so we
4824 // do not need to deal with it at all.
4825 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4826
4827 // Claim some arguments which clang doesn't support, but we don't
4828 // care to warn the user about.
4829 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4830 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4831
4832 // Disable warnings for clang -E -emit-llvm foo.c
4833 Args.ClaimAllArgs(options::OPT_emit_llvm);
4834}
4835
4836Clang::Clang(const ToolChain &TC)
4837 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4838 // as it is for other tools. Some operations on a Tool actually test
4839 // whether that tool is Clang based on the Tool's Name as a string.
4840 : Tool("clang", "clang frontend", TC, RF_Full) {}
4841
4842Clang::~Clang() {}
4843
4844/// Add options related to the Objective-C runtime/ABI.
4845///
4846/// Returns true if the runtime is non-fragile.
4847ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4848 ArgStringList &cmdArgs,
4849 RewriteKind rewriteKind) const {
4850 // Look for the controlling runtime option.
4851 Arg *runtimeArg =
4852 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4853 options::OPT_fobjc_runtime_EQ);
4854
4855 // Just forward -fobjc-runtime= to the frontend. This supercedes
4856 // options about fragility.
4857 if (runtimeArg &&
4858 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4859 ObjCRuntime runtime;
4860 StringRef value = runtimeArg->getValue();
4861 if (runtime.tryParse(value)) {
4862 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4863 << value;
4864 }
4865
4866 runtimeArg->render(args, cmdArgs);
4867 return runtime;
4868 }
4869
4870 // Otherwise, we'll need the ABI "version". Version numbers are
4871 // slightly confusing for historical reasons:
4872 // 1 - Traditional "fragile" ABI
4873 // 2 - Non-fragile ABI, version 1
4874 // 3 - Non-fragile ABI, version 2
4875 unsigned objcABIVersion = 1;
4876 // If -fobjc-abi-version= is present, use that to set the version.
4877 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4878 StringRef value = abiArg->getValue();
4879 if (value == "1")
4880 objcABIVersion = 1;
4881 else if (value == "2")
4882 objcABIVersion = 2;
4883 else if (value == "3")
4884 objcABIVersion = 3;
4885 else
4886 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4887 } else {
4888 // Otherwise, determine if we are using the non-fragile ABI.
4889 bool nonFragileABIIsDefault =
4890 (rewriteKind == RK_NonFragile ||
4891 (rewriteKind == RK_None &&
4892 getToolChain().IsObjCNonFragileABIDefault()));
4893 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4894 options::OPT_fno_objc_nonfragile_abi,
4895 nonFragileABIIsDefault)) {
4896// Determine the non-fragile ABI version to use.
4897#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4898 unsigned nonFragileABIVersion = 1;
4899#else
4900 unsigned nonFragileABIVersion = 2;
4901#endif
4902
4903 if (Arg *abiArg =
4904 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4905 StringRef value = abiArg->getValue();
4906 if (value == "1")
4907 nonFragileABIVersion = 1;
4908 else if (value == "2")
4909 nonFragileABIVersion = 2;
4910 else
4911 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4912 << value;
4913 }
4914
4915 objcABIVersion = 1 + nonFragileABIVersion;
4916 } else {
4917 objcABIVersion = 1;
4918 }
4919 }
4920
4921 // We don't actually care about the ABI version other than whether
4922 // it's non-fragile.
4923 bool isNonFragile = objcABIVersion != 1;
4924
4925 // If we have no runtime argument, ask the toolchain for its default runtime.
4926 // However, the rewriter only really supports the Mac runtime, so assume that.
4927 ObjCRuntime runtime;
4928 if (!runtimeArg) {
4929 switch (rewriteKind) {
4930 case RK_None:
4931 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4932 break;
4933 case RK_Fragile:
4934 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4935 break;
4936 case RK_NonFragile:
4937 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4938 break;
4939 }
4940
4941 // -fnext-runtime
4942 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4943 // On Darwin, make this use the default behavior for the toolchain.
4944 if (getToolChain().getTriple().isOSDarwin()) {
4945 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4946
4947 // Otherwise, build for a generic macosx port.
4948 } else {
4949 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4950 }
4951
4952 // -fgnu-runtime
4953 } else {
4954 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4955 // Legacy behaviour is to target the gnustep runtime if we are in
4956 // non-fragile mode or the GCC runtime in fragile mode.
4957 if (isNonFragile)
4958 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4959 else
4960 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4961 }
4962
4963 cmdArgs.push_back(
4964 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4965 return runtime;
4966}
4967
4968static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4969 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4970 I += HaveDash;
4971 return !HaveDash;
4972}
4973
4974namespace {
4975struct EHFlags {
4976 bool Synch = false;
4977 bool Asynch = false;
4978 bool NoUnwindC = false;
4979};
4980} // end anonymous namespace
4981
4982/// /EH controls whether to run destructor cleanups when exceptions are
4983/// thrown. There are three modifiers:
4984/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4985/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4986/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4987/// - c: Assume that extern "C" functions are implicitly nounwind.
4988/// The default is /EHs-c-, meaning cleanups are disabled.
4989static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4990 EHFlags EH;
4991
4992 std::vector<std::string> EHArgs =
4993 Args.getAllArgValues(options::OPT__SLASH_EH);
4994 for (auto EHVal : EHArgs) {
4995 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4996 switch (EHVal[I]) {
4997 case 'a':
4998 EH.Asynch = maybeConsumeDash(EHVal, I);
4999 if (EH.Asynch)
5000 EH.Synch = false;
5001 continue;
5002 case 'c':
5003 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5004 continue;
5005 case 's':
5006 EH.Synch = maybeConsumeDash(EHVal, I);
5007 if (EH.Synch)
5008 EH.Asynch = false;
5009 continue;
5010 default:
5011 break;
5012 }
5013 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5014 break;
5015 }
5016 }
5017 // The /GX, /GX- flags are only processed if there are not /EH flags.
5018 // The default is that /GX is not specified.
5019 if (EHArgs.empty() &&
5020 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5021 /*default=*/false)) {
5022 EH.Synch = true;
5023 EH.NoUnwindC = true;
5024 }
5025
5026 return EH;
5027}
5028
5029void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5030 ArgStringList &CmdArgs,
5031 codegenoptions::DebugInfoKind *DebugInfoKind,
5032 bool *EmitCodeView) const {
5033 unsigned RTOptionID = options::OPT__SLASH_MT;
5034
5035 if (Args.hasArg(options::OPT__SLASH_LDd))
5036 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5037 // but defining _DEBUG is sticky.
5038 RTOptionID = options::OPT__SLASH_MTd;
5039
5040 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5041 RTOptionID = A->getOption().getID();
5042
5043 StringRef FlagForCRT;
5044 switch (RTOptionID) {
5045 case options::OPT__SLASH_MD:
5046 if (Args.hasArg(options::OPT__SLASH_LDd))
5047 CmdArgs.push_back("-D_DEBUG");
5048 CmdArgs.push_back("-D_MT");
5049 CmdArgs.push_back("-D_DLL");
5050 FlagForCRT = "--dependent-lib=msvcrt";
5051 break;
5052 case options::OPT__SLASH_MDd:
5053 CmdArgs.push_back("-D_DEBUG");
5054 CmdArgs.push_back("-D_MT");
5055 CmdArgs.push_back("-D_DLL");
5056 FlagForCRT = "--dependent-lib=msvcrtd";
5057 break;
5058 case options::OPT__SLASH_MT:
5059 if (Args.hasArg(options::OPT__SLASH_LDd))
5060 CmdArgs.push_back("-D_DEBUG");
5061 CmdArgs.push_back("-D_MT");
5062 CmdArgs.push_back("-flto-visibility-public-std");
5063 FlagForCRT = "--dependent-lib=libcmt";
5064 break;
5065 case options::OPT__SLASH_MTd:
5066 CmdArgs.push_back("-D_DEBUG");
5067 CmdArgs.push_back("-D_MT");
5068 CmdArgs.push_back("-flto-visibility-public-std");
5069 FlagForCRT = "--dependent-lib=libcmtd";
5070 break;
5071 default:
5072 llvm_unreachable("Unexpected option ID.");
5073 }
5074
5075 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5076 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5077 } else {
5078 CmdArgs.push_back(FlagForCRT.data());
5079
5080 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5081 // users want. The /Za flag to cl.exe turns this off, but it's not
5082 // implemented in clang.
5083 CmdArgs.push_back("--dependent-lib=oldnames");
5084 }
5085
Erich Keane425f48d2018-05-04 15:58:31 +00005086 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5087 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005088
5089 // This controls whether or not we emit RTTI data for polymorphic types.
5090 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5091 /*default=*/false))
5092 CmdArgs.push_back("-fno-rtti-data");
5093
5094 // This controls whether or not we emit stack-protector instrumentation.
5095 // In MSVC, Buffer Security Check (/GS) is on by default.
5096 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5097 /*default=*/true)) {
5098 CmdArgs.push_back("-stack-protector");
5099 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5100 }
5101
5102 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5103 if (Arg *DebugInfoArg =
5104 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5105 options::OPT_gline_tables_only)) {
5106 *EmitCodeView = true;
5107 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5108 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5109 else
5110 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5111 CmdArgs.push_back("-gcodeview");
5112 } else {
5113 *EmitCodeView = false;
5114 }
5115
5116 const Driver &D = getToolChain().getDriver();
5117 EHFlags EH = parseClangCLEHFlags(D, Args);
5118 if (EH.Synch || EH.Asynch) {
5119 if (types::isCXX(InputType))
5120 CmdArgs.push_back("-fcxx-exceptions");
5121 CmdArgs.push_back("-fexceptions");
5122 }
5123 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5124 CmdArgs.push_back("-fexternc-nounwind");
5125
5126 // /EP should expand to -E -P.
5127 if (Args.hasArg(options::OPT__SLASH_EP)) {
5128 CmdArgs.push_back("-E");
5129 CmdArgs.push_back("-P");
5130 }
5131
5132 unsigned VolatileOptionID;
5133 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5134 getToolChain().getArch() == llvm::Triple::x86)
5135 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5136 else
5137 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5138
5139 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5140 VolatileOptionID = A->getOption().getID();
5141
5142 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5143 CmdArgs.push_back("-fms-volatile");
5144
5145 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5146 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5147 if (MostGeneralArg && BestCaseArg)
5148 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5149 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5150
5151 if (MostGeneralArg) {
5152 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5153 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5154 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5155
5156 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5157 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5158 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5159 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5160 << FirstConflict->getAsString(Args)
5161 << SecondConflict->getAsString(Args);
5162
5163 if (SingleArg)
5164 CmdArgs.push_back("-fms-memptr-rep=single");
5165 else if (MultipleArg)
5166 CmdArgs.push_back("-fms-memptr-rep=multiple");
5167 else
5168 CmdArgs.push_back("-fms-memptr-rep=virtual");
5169 }
5170
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005171 // Parse the default calling convention options.
5172 if (Arg *CCArg =
5173 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005174 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5175 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005176 unsigned DCCOptId = CCArg->getOption().getID();
5177 const char *DCCFlag = nullptr;
5178 bool ArchSupported = true;
5179 llvm::Triple::ArchType Arch = getToolChain().getArch();
5180 switch (DCCOptId) {
5181 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005182 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005183 break;
5184 case options::OPT__SLASH_Gr:
5185 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005186 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005187 break;
5188 case options::OPT__SLASH_Gz:
5189 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005190 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005191 break;
5192 case options::OPT__SLASH_Gv:
5193 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005194 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005195 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005196 case options::OPT__SLASH_Gregcall:
5197 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5198 DCCFlag = "-fdefault-calling-conv=regcall";
5199 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005200 }
5201
5202 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5203 if (ArchSupported && DCCFlag)
5204 CmdArgs.push_back(DCCFlag);
5205 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005206
5207 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5208 A->render(Args, CmdArgs);
5209
5210 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5211 CmdArgs.push_back("-fdiagnostics-format");
5212 if (Args.hasArg(options::OPT__SLASH_fallback))
5213 CmdArgs.push_back("msvc-fallback");
5214 else
5215 CmdArgs.push_back("msvc");
5216 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005217
5218 if (Args.hasArg(options::OPT__SLASH_Guard) &&
5219 Args.getLastArgValue(options::OPT__SLASH_Guard).equals_lower("cf"))
5220 CmdArgs.push_back("-cfguard");
David L. Jonesf561aba2017-03-08 01:02:16 +00005221}
5222
5223visualstudio::Compiler *Clang::getCLFallback() const {
5224 if (!CLFallback)
5225 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5226 return CLFallback.get();
5227}
5228
5229
5230const char *Clang::getBaseInputName(const ArgList &Args,
5231 const InputInfo &Input) {
5232 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5233}
5234
5235const char *Clang::getBaseInputStem(const ArgList &Args,
5236 const InputInfoList &Inputs) {
5237 const char *Str = getBaseInputName(Args, Inputs[0]);
5238
5239 if (const char *End = strrchr(Str, '.'))
5240 return Args.MakeArgString(std::string(Str, End));
5241
5242 return Str;
5243}
5244
5245const char *Clang::getDependencyFileName(const ArgList &Args,
5246 const InputInfoList &Inputs) {
5247 // FIXME: Think about this more.
5248 std::string Res;
5249
5250 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5251 std::string Str(OutputOpt->getValue());
5252 Res = Str.substr(0, Str.rfind('.'));
5253 } else {
5254 Res = getBaseInputStem(Args, Inputs);
5255 }
5256 return Args.MakeArgString(Res + ".d");
5257}
5258
5259// Begin ClangAs
5260
5261void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5262 ArgStringList &CmdArgs) const {
5263 StringRef CPUName;
5264 StringRef ABIName;
5265 const llvm::Triple &Triple = getToolChain().getTriple();
5266 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5267
5268 CmdArgs.push_back("-target-abi");
5269 CmdArgs.push_back(ABIName.data());
5270}
5271
5272void ClangAs::AddX86TargetArgs(const ArgList &Args,
5273 ArgStringList &CmdArgs) const {
5274 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5275 StringRef Value = A->getValue();
5276 if (Value == "intel" || Value == "att") {
5277 CmdArgs.push_back("-mllvm");
5278 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5279 } else {
5280 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5281 << A->getOption().getName() << Value;
5282 }
5283 }
5284}
5285
5286void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5287 const InputInfo &Output, const InputInfoList &Inputs,
5288 const ArgList &Args,
5289 const char *LinkingOutput) const {
5290 ArgStringList CmdArgs;
5291
5292 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5293 const InputInfo &Input = Inputs[0];
5294
5295 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5296 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005297 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005298
5299 // Don't warn about "clang -w -c foo.s"
5300 Args.ClaimAllArgs(options::OPT_w);
5301 // and "clang -emit-llvm -c foo.s"
5302 Args.ClaimAllArgs(options::OPT_emit_llvm);
5303
5304 claimNoWarnArgs(Args);
5305
5306 // Invoke ourselves in -cc1as mode.
5307 //
5308 // FIXME: Implement custom jobs for internal actions.
5309 CmdArgs.push_back("-cc1as");
5310
5311 // Add the "effective" target triple.
5312 CmdArgs.push_back("-triple");
5313 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5314
5315 // Set the output mode, we currently only expect to be used as a real
5316 // assembler.
5317 CmdArgs.push_back("-filetype");
5318 CmdArgs.push_back("obj");
5319
5320 // Set the main file name, so that debug info works even with
5321 // -save-temps or preprocessed assembly.
5322 CmdArgs.push_back("-main-file-name");
5323 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5324
5325 // Add the target cpu
5326 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5327 if (!CPU.empty()) {
5328 CmdArgs.push_back("-target-cpu");
5329 CmdArgs.push_back(Args.MakeArgString(CPU));
5330 }
5331
5332 // Add the target features
5333 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5334
5335 // Ignore explicit -force_cpusubtype_ALL option.
5336 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5337
5338 // Pass along any -I options so we get proper .include search paths.
5339 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5340
5341 // Determine the original source input.
5342 const Action *SourceAction = &JA;
5343 while (SourceAction->getKind() != Action::InputClass) {
5344 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5345 SourceAction = SourceAction->getInputs()[0];
5346 }
5347
5348 // Forward -g and handle debug info related flags, assuming we are dealing
5349 // with an actual assembly file.
5350 bool WantDebug = false;
5351 unsigned DwarfVersion = 0;
5352 Args.ClaimAllArgs(options::OPT_g_Group);
5353 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5354 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5355 !A->getOption().matches(options::OPT_ggdb0);
5356 if (WantDebug)
5357 DwarfVersion = DwarfVersionNum(A->getSpelling());
5358 }
5359 if (DwarfVersion == 0)
5360 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5361
5362 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5363
5364 if (SourceAction->getType() == types::TY_Asm ||
5365 SourceAction->getType() == types::TY_PP_Asm) {
5366 // You might think that it would be ok to set DebugInfoKind outside of
5367 // the guard for source type, however there is a test which asserts
5368 // that some assembler invocation receives no -debug-info-kind,
5369 // and it's not clear whether that test is just overly restrictive.
5370 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5371 : codegenoptions::NoDebugInfo);
5372 // Add the -fdebug-compilation-dir flag if needed.
5373 addDebugCompDirArg(Args, CmdArgs);
5374
5375 // Set the AT_producer to the clang version when using the integrated
5376 // assembler on assembly source files.
5377 CmdArgs.push_back("-dwarf-debug-producer");
5378 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5379
5380 // And pass along -I options
5381 Args.AddAllArgs(CmdArgs, options::OPT_I);
5382 }
5383 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5384 llvm::DebuggerKind::Default);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005385 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5386
David L. Jonesf561aba2017-03-08 01:02:16 +00005387
5388 // Handle -fPIC et al -- the relocation-model affects the assembler
5389 // for some targets.
5390 llvm::Reloc::Model RelocationModel;
5391 unsigned PICLevel;
5392 bool IsPIE;
5393 std::tie(RelocationModel, PICLevel, IsPIE) =
5394 ParsePICArgs(getToolChain(), Args);
5395
5396 const char *RMName = RelocationModelName(RelocationModel);
5397 if (RMName) {
5398 CmdArgs.push_back("-mrelocation-model");
5399 CmdArgs.push_back(RMName);
5400 }
5401
5402 // Optionally embed the -cc1as level arguments into the debug info, for build
5403 // analysis.
5404 if (getToolChain().UseDwarfDebugFlags()) {
5405 ArgStringList OriginalArgs;
5406 for (const auto &Arg : Args)
5407 Arg->render(Args, OriginalArgs);
5408
5409 SmallString<256> Flags;
5410 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5411 Flags += Exec;
5412 for (const char *OriginalArg : OriginalArgs) {
5413 SmallString<128> EscapedArg;
5414 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5415 Flags += " ";
5416 Flags += EscapedArg;
5417 }
5418 CmdArgs.push_back("-dwarf-debug-flags");
5419 CmdArgs.push_back(Args.MakeArgString(Flags));
5420 }
5421
5422 // FIXME: Add -static support, once we have it.
5423
5424 // Add target specific flags.
5425 switch (getToolChain().getArch()) {
5426 default:
5427 break;
5428
5429 case llvm::Triple::mips:
5430 case llvm::Triple::mipsel:
5431 case llvm::Triple::mips64:
5432 case llvm::Triple::mips64el:
5433 AddMIPSTargetArgs(Args, CmdArgs);
5434 break;
5435
5436 case llvm::Triple::x86:
5437 case llvm::Triple::x86_64:
5438 AddX86TargetArgs(Args, CmdArgs);
5439 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005440
5441 case llvm::Triple::arm:
5442 case llvm::Triple::armeb:
5443 case llvm::Triple::thumb:
5444 case llvm::Triple::thumbeb:
5445 // This isn't in AddARMTargetArgs because we want to do this for assembly
5446 // only, not C/C++.
5447 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5448 options::OPT_mno_default_build_attributes, true)) {
5449 CmdArgs.push_back("-mllvm");
5450 CmdArgs.push_back("-arm-add-build-attributes");
5451 }
5452 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005453 }
5454
5455 // Consume all the warning flags. Usually this would be handled more
5456 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5457 // doesn't handle that so rather than warning about unused flags that are
5458 // actually used, we'll lie by omission instead.
5459 // FIXME: Stop lying and consume only the appropriate driver flags
5460 Args.ClaimAllArgs(options::OPT_W_Group);
5461
5462 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5463 getToolChain().getDriver());
5464
5465 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5466
5467 assert(Output.isFilename() && "Unexpected lipo output.");
5468 CmdArgs.push_back("-o");
5469 CmdArgs.push_back(Output.getFilename());
5470
5471 assert(Input.isFilename() && "Invalid input.");
5472 CmdArgs.push_back(Input.getFilename());
5473
5474 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5475 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5476
5477 // Handle the debug info splitting at object creation time if we're
5478 // creating an object.
5479 // TODO: Currently only works on linux with newer objcopy.
5480 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5481 getToolChain().getTriple().isOSLinux())
5482 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5483 SplitDebugName(Args, Input));
5484}
5485
5486// Begin OffloadBundler
5487
5488void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5489 const InputInfo &Output,
5490 const InputInfoList &Inputs,
5491 const llvm::opt::ArgList &TCArgs,
5492 const char *LinkingOutput) const {
5493 // The version with only one output is expected to refer to a bundling job.
5494 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5495
5496 // The bundling command looks like this:
5497 // clang-offload-bundler -type=bc
5498 // -targets=host-triple,openmp-triple1,openmp-triple2
5499 // -outputs=input_file
5500 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5501
5502 ArgStringList CmdArgs;
5503
5504 // Get the type.
5505 CmdArgs.push_back(TCArgs.MakeArgString(
5506 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5507
5508 assert(JA.getInputs().size() == Inputs.size() &&
5509 "Not have inputs for all dependence actions??");
5510
5511 // Get the targets.
5512 SmallString<128> Triples;
5513 Triples += "-targets=";
5514 for (unsigned I = 0; I < Inputs.size(); ++I) {
5515 if (I)
5516 Triples += ',';
5517
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005518 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005519 Action::OffloadKind CurKind = Action::OFK_Host;
5520 const ToolChain *CurTC = &getToolChain();
5521 const Action *CurDep = JA.getInputs()[I];
5522
5523 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005524 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00005525 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005526 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00005527 CurKind = A->getOffloadingDeviceKind();
5528 CurTC = TC;
5529 });
5530 }
5531 Triples += Action::GetOffloadKindName(CurKind);
5532 Triples += '-';
5533 Triples += CurTC->getTriple().normalize();
5534 }
5535 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5536
5537 // Get bundled file command.
5538 CmdArgs.push_back(
5539 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5540
5541 // Get unbundled files command.
5542 SmallString<128> UB;
5543 UB += "-inputs=";
5544 for (unsigned I = 0; I < Inputs.size(); ++I) {
5545 if (I)
5546 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005547
5548 // Find ToolChain for this input.
5549 const ToolChain *CurTC = &getToolChain();
5550 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5551 CurTC = nullptr;
5552 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5553 assert(CurTC == nullptr && "Expected one dependence!");
5554 CurTC = TC;
5555 });
5556 }
5557 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005558 }
5559 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5560
5561 // All the inputs are encoded as commands.
5562 C.addCommand(llvm::make_unique<Command>(
5563 JA, *this,
5564 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5565 CmdArgs, None));
5566}
5567
5568void OffloadBundler::ConstructJobMultipleOutputs(
5569 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5570 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5571 const char *LinkingOutput) const {
5572 // The version with multiple outputs is expected to refer to a unbundling job.
5573 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5574
5575 // The unbundling command looks like this:
5576 // clang-offload-bundler -type=bc
5577 // -targets=host-triple,openmp-triple1,openmp-triple2
5578 // -inputs=input_file
5579 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5580 // -unbundle
5581
5582 ArgStringList CmdArgs;
5583
5584 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5585 InputInfo Input = Inputs.front();
5586
5587 // Get the type.
5588 CmdArgs.push_back(TCArgs.MakeArgString(
5589 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5590
5591 // Get the targets.
5592 SmallString<128> Triples;
5593 Triples += "-targets=";
5594 auto DepInfo = UA.getDependentActionsInfo();
5595 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5596 if (I)
5597 Triples += ',';
5598
5599 auto &Dep = DepInfo[I];
5600 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5601 Triples += '-';
5602 Triples += Dep.DependentToolChain->getTriple().normalize();
5603 }
5604
5605 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5606
5607 // Get bundled file command.
5608 CmdArgs.push_back(
5609 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5610
5611 // Get unbundled files command.
5612 SmallString<128> UB;
5613 UB += "-outputs=";
5614 for (unsigned I = 0; I < Outputs.size(); ++I) {
5615 if (I)
5616 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005617 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005618 }
5619 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5620 CmdArgs.push_back("-unbundle");
5621
5622 // All the inputs are encoded as commands.
5623 C.addCommand(llvm::make_unique<Command>(
5624 JA, *this,
5625 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5626 CmdArgs, None));
5627}