blob: 26e8bc60bfa4c8f24065f08297916cfcba56ea2b [file] [log] [blame]
Fangrui Song524b3c12019-03-01 06:49:51 +00001//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
David L. Jonesf561aba2017-03-08 01:02:16 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
David L. Jonesf561aba2017-03-08 01:02:16 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/Mips.h"
13#include "Arch/PPC.h"
Alex Bradbury71f45452018-01-11 13:36:56 +000014#include "Arch/RISCV.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000015#include "Arch/Sparc.h"
16#include "Arch/SystemZ.h"
17#include "Arch/X86.h"
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +000018#include "AMDGPU.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000019#include "CommonArgs.h"
20#include "Hexagon.h"
Anton Korobeynikov93165d62019-01-15 19:44:05 +000021#include "MSP430.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000022#include "InputInfo.h"
23#include "PS4CPU.h"
24#include "clang/Basic/CharInfo.h"
Yuanfang Chenff22ec32019-07-20 22:50:50 +000025#include "clang/Basic/CodeGenOptions.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000026#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/ObjCRuntime.h"
28#include "clang/Basic/Version.h"
Michal Gornydae01c32018-12-23 15:07:26 +000029#include "clang/Driver/Distro.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000030#include "clang/Driver/DriverDiagnostic.h"
31#include "clang/Driver/Options.h"
32#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000033#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000034#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000035#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000036#include "llvm/Option/ArgList.h"
37#include "llvm/Support/CodeGen.h"
38#include "llvm/Support/Compression.h"
39#include "llvm/Support/FileSystem.h"
40#include "llvm/Support/Path.h"
41#include "llvm/Support/Process.h"
Eric Christopher53b2cb72017-06-30 00:03:56 +000042#include "llvm/Support/TargetParser.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000043#include "llvm/Support/YAMLParser.h"
44
45#ifdef LLVM_ON_UNIX
46#include <unistd.h> // For getuid().
47#endif
48
49using namespace clang::driver;
50using namespace clang::driver::tools;
51using namespace clang;
52using namespace llvm::opt;
53
54static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
55 if (Arg *A =
56 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
57 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
58 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
59 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
60 << A->getBaseArg().getAsString(Args)
61 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
62 }
63 }
64}
65
66static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
67 // In gcc, only ARM checks this, but it seems reasonable to check universally.
68 if (Args.hasArg(options::OPT_static))
69 if (const Arg *A =
70 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
71 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
72 << "-static";
73}
74
75// Add backslashes to escape spaces and other backslashes.
76// This is used for the space-separated argument list specified with
77// the -dwarf-debug-flags option.
78static void EscapeSpacesAndBackslashes(const char *Arg,
79 SmallVectorImpl<char> &Res) {
80 for (; *Arg; ++Arg) {
81 switch (*Arg) {
82 default:
83 break;
84 case ' ':
85 case '\\':
86 Res.push_back('\\');
87 break;
88 }
89 Res.push_back(*Arg);
90 }
91}
92
93// Quote target names for inclusion in GNU Make dependency files.
94// Only the characters '$', '#', ' ', '\t' are quoted.
95static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
96 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
97 switch (Target[i]) {
98 case ' ':
99 case '\t':
100 // Escape the preceding backslashes
101 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
102 Res.push_back('\\');
103
104 // Escape the space/tab
105 Res.push_back('\\');
106 break;
107 case '$':
108 Res.push_back('$');
109 break;
110 case '#':
111 Res.push_back('\\');
112 break;
113 default:
114 break;
115 }
116
117 Res.push_back(Target[i]);
118 }
119}
120
121/// Apply \a Work on the current tool chain \a RegularToolChain and any other
122/// offloading tool chain that is associated with the current action \a JA.
123static void
124forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
125 const ToolChain &RegularToolChain,
126 llvm::function_ref<void(const ToolChain &)> Work) {
127 // Apply Work on the current/regular tool chain.
128 Work(RegularToolChain);
129
130 // Apply Work on all the offloading tool chains associated with the current
131 // action.
132 if (JA.isHostOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
134 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
Yaxun Liu398612b2018-05-08 21:02:12 +0000136 else if (JA.isHostOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
138 else if (JA.isDeviceOffloading(Action::OFK_HIP))
139 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
David L. Jonesf561aba2017-03-08 01:02:16 +0000140
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000141 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
142 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
143 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
144 Work(*II->second);
145 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
146 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
147
David L. Jonesf561aba2017-03-08 01:02:16 +0000148 //
149 // TODO: Add support for other offloading programming models here.
150 //
151}
152
153/// This is a helper function for validating the optional refinement step
154/// parameter in reciprocal argument strings. Return false if there is an error
155/// parsing the refinement step. Otherwise, return true and set the Position
156/// of the refinement step in the input string.
157static bool getRefinementStep(StringRef In, const Driver &D,
158 const Arg &A, size_t &Position) {
159 const char RefinementStepToken = ':';
160 Position = In.find(RefinementStepToken);
161 if (Position != StringRef::npos) {
162 StringRef Option = A.getOption().getName();
163 StringRef RefStep = In.substr(Position + 1);
164 // Allow exactly one numeric character for the additional refinement
165 // step parameter. This is reasonable for all currently-supported
166 // operations and architectures because we would expect that a larger value
167 // of refinement steps would cause the estimate "optimization" to
168 // under-perform the native operation. Also, if the estimate does not
169 // converge quickly, it probably will not ever converge, so further
170 // refinement steps will not produce a better answer.
171 if (RefStep.size() != 1) {
172 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
173 return false;
174 }
175 char RefStepChar = RefStep[0];
176 if (RefStepChar < '0' || RefStepChar > '9') {
177 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
178 return false;
179 }
180 }
181 return true;
182}
183
184/// The -mrecip flag requires processing of many optional parameters.
185static void ParseMRecip(const Driver &D, const ArgList &Args,
186 ArgStringList &OutStrings) {
187 StringRef DisabledPrefixIn = "!";
188 StringRef DisabledPrefixOut = "!";
189 StringRef EnabledPrefixOut = "";
190 StringRef Out = "-mrecip=";
191
192 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
193 if (!A)
194 return;
195
196 unsigned NumOptions = A->getNumValues();
197 if (NumOptions == 0) {
198 // No option is the same as "all".
199 OutStrings.push_back(Args.MakeArgString(Out + "all"));
200 return;
201 }
202
203 // Pass through "all", "none", or "default" with an optional refinement step.
204 if (NumOptions == 1) {
205 StringRef Val = A->getValue(0);
206 size_t RefStepLoc;
207 if (!getRefinementStep(Val, D, *A, RefStepLoc))
208 return;
209 StringRef ValBase = Val.slice(0, RefStepLoc);
210 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
211 OutStrings.push_back(Args.MakeArgString(Out + Val));
212 return;
213 }
214 }
215
216 // Each reciprocal type may be enabled or disabled individually.
217 // Check each input value for validity, concatenate them all back together,
218 // and pass through.
219
220 llvm::StringMap<bool> OptionStrings;
221 OptionStrings.insert(std::make_pair("divd", false));
222 OptionStrings.insert(std::make_pair("divf", false));
223 OptionStrings.insert(std::make_pair("vec-divd", false));
224 OptionStrings.insert(std::make_pair("vec-divf", false));
225 OptionStrings.insert(std::make_pair("sqrtd", false));
226 OptionStrings.insert(std::make_pair("sqrtf", false));
227 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
228 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
229
230 for (unsigned i = 0; i != NumOptions; ++i) {
231 StringRef Val = A->getValue(i);
232
233 bool IsDisabled = Val.startswith(DisabledPrefixIn);
234 // Ignore the disablement token for string matching.
235 if (IsDisabled)
236 Val = Val.substr(1);
237
238 size_t RefStep;
239 if (!getRefinementStep(Val, D, *A, RefStep))
240 return;
241
242 StringRef ValBase = Val.slice(0, RefStep);
243 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
244 if (OptionIter == OptionStrings.end()) {
245 // Try again specifying float suffix.
246 OptionIter = OptionStrings.find(ValBase.str() + 'f');
247 if (OptionIter == OptionStrings.end()) {
248 // The input name did not match any known option string.
249 D.Diag(diag::err_drv_unknown_argument) << Val;
250 return;
251 }
252 // The option was specified without a float or double suffix.
253 // Make sure that the double entry was not already specified.
254 // The float entry will be checked below.
255 if (OptionStrings[ValBase.str() + 'd']) {
256 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
257 return;
258 }
259 }
260
261 if (OptionIter->second == true) {
262 // Duplicate option specified.
263 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
264 return;
265 }
266
267 // Mark the matched option as found. Do not allow duplicate specifiers.
268 OptionIter->second = true;
269
270 // If the precision was not specified, also mark the double entry as found.
271 if (ValBase.back() != 'f' && ValBase.back() != 'd')
272 OptionStrings[ValBase.str() + 'd'] = true;
273
274 // Build the output string.
275 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
276 Out = Args.MakeArgString(Out + Prefix + Val);
277 if (i != NumOptions - 1)
278 Out = Args.MakeArgString(Out + ",");
279 }
280
281 OutStrings.push_back(Args.MakeArgString(Out));
282}
283
Craig Topper9a724aa2017-12-11 21:09:19 +0000284/// The -mprefer-vector-width option accepts either a positive integer
285/// or the string "none".
286static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
287 ArgStringList &CmdArgs) {
288 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
289 if (!A)
290 return;
291
292 StringRef Value = A->getValue();
293 if (Value == "none") {
294 CmdArgs.push_back("-mprefer-vector-width=none");
295 } else {
296 unsigned Width;
297 if (Value.getAsInteger(10, Width)) {
298 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
299 return;
300 }
301 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
302 }
303}
304
David L. Jonesf561aba2017-03-08 01:02:16 +0000305static void getWebAssemblyTargetFeatures(const ArgList &Args,
306 std::vector<StringRef> &Features) {
307 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
308}
309
David L. Jonesf561aba2017-03-08 01:02:16 +0000310static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
311 const ArgList &Args, ArgStringList &CmdArgs,
312 bool ForAS) {
313 const Driver &D = TC.getDriver();
314 std::vector<StringRef> Features;
315 switch (Triple.getArch()) {
316 default:
317 break;
318 case llvm::Triple::mips:
319 case llvm::Triple::mipsel:
320 case llvm::Triple::mips64:
321 case llvm::Triple::mips64el:
322 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
323 break;
324
325 case llvm::Triple::arm:
326 case llvm::Triple::armeb:
327 case llvm::Triple::thumb:
328 case llvm::Triple::thumbeb:
329 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
330 break;
331
332 case llvm::Triple::ppc:
333 case llvm::Triple::ppc64:
334 case llvm::Triple::ppc64le:
335 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
336 break;
Alex Bradbury71f45452018-01-11 13:36:56 +0000337 case llvm::Triple::riscv32:
338 case llvm::Triple::riscv64:
Roger Ferrer Ibanez93c4d532019-09-10 08:16:24 +0000339 riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
Alex Bradbury71f45452018-01-11 13:36:56 +0000340 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000341 case llvm::Triple::systemz:
342 systemz::getSystemZTargetFeatures(Args, Features);
343 break;
344 case llvm::Triple::aarch64:
345 case llvm::Triple::aarch64_be:
Alex Lorenz9b20a992018-12-17 19:30:46 +0000346 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000347 break;
348 case llvm::Triple::x86:
349 case llvm::Triple::x86_64:
350 x86::getX86TargetFeatures(D, Triple, Args, Features);
351 break;
352 case llvm::Triple::hexagon:
Sumanth Gundapaneni57098f52017-10-18 18:10:13 +0000353 hexagon::getHexagonTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000354 break;
355 case llvm::Triple::wasm32:
356 case llvm::Triple::wasm64:
357 getWebAssemblyTargetFeatures(Args, Features);
358 break;
359 case llvm::Triple::sparc:
360 case llvm::Triple::sparcel:
361 case llvm::Triple::sparcv9:
362 sparc::getSparcTargetFeatures(D, Args, Features);
363 break;
364 case llvm::Triple::r600:
365 case llvm::Triple::amdgcn:
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +0000366 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000367 break;
Anton Korobeynikov93165d62019-01-15 19:44:05 +0000368 case llvm::Triple::msp430:
369 msp430::getMSP430TargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000370 }
371
372 // Find the last of each feature.
373 llvm::StringMap<unsigned> LastOpt;
374 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
375 StringRef Name = Features[I];
376 assert(Name[0] == '-' || Name[0] == '+');
377 LastOpt[Name.drop_front(1)] = I;
378 }
379
380 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
381 // If this feature was overridden, ignore it.
382 StringRef Name = Features[I];
383 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
384 assert(LastI != LastOpt.end());
385 unsigned Last = LastI->second;
386 if (Last != I)
387 continue;
388
389 CmdArgs.push_back("-target-feature");
390 CmdArgs.push_back(Name.data());
391 }
392}
393
394static bool
395shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
396 const llvm::Triple &Triple) {
397 // We use the zero-cost exception tables for Objective-C if the non-fragile
398 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
399 // later.
400 if (runtime.isNonFragile())
401 return true;
402
403 if (!Triple.isMacOSX())
404 return false;
405
406 return (!Triple.isMacOSXVersionLT(10, 5) &&
407 (Triple.getArch() == llvm::Triple::x86_64 ||
408 Triple.getArch() == llvm::Triple::arm));
409}
410
411/// Adds exception related arguments to the driver command arguments. There's a
412/// master flag, -fexceptions and also language specific flags to enable/disable
413/// C++ and Objective-C exceptions. This makes it possible to for example
414/// disable C++ exceptions but enable Objective-C exceptions.
415static void addExceptionArgs(const ArgList &Args, types::ID InputType,
416 const ToolChain &TC, bool KernelOrKext,
417 const ObjCRuntime &objcRuntime,
418 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000419 const llvm::Triple &Triple = TC.getTriple();
420
421 if (KernelOrKext) {
422 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
423 // arguments now to avoid warnings about unused arguments.
424 Args.ClaimAllArgs(options::OPT_fexceptions);
425 Args.ClaimAllArgs(options::OPT_fno_exceptions);
426 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
427 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
428 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
429 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
430 return;
431 }
432
433 // See if the user explicitly enabled exceptions.
434 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
435 false);
436
437 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
438 // is not necessarily sensible, but follows GCC.
439 if (types::isObjC(InputType) &&
440 Args.hasFlag(options::OPT_fobjc_exceptions,
441 options::OPT_fno_objc_exceptions, true)) {
442 CmdArgs.push_back("-fobjc-exceptions");
443
444 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
445 }
446
447 if (types::isCXX(InputType)) {
448 // Disable C++ EH by default on XCore and PS4.
449 bool CXXExceptionsEnabled =
450 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
451 Arg *ExceptionArg = Args.getLastArg(
452 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
453 options::OPT_fexceptions, options::OPT_fno_exceptions);
454 if (ExceptionArg)
455 CXXExceptionsEnabled =
456 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
457 ExceptionArg->getOption().matches(options::OPT_fexceptions);
458
459 if (CXXExceptionsEnabled) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000460 CmdArgs.push_back("-fcxx-exceptions");
461
462 EH = true;
463 }
464 }
465
466 if (EH)
467 CmdArgs.push_back("-fexceptions");
468}
469
470static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
471 bool Default = true;
472 if (TC.getTriple().isOSDarwin()) {
473 // The native darwin assembler doesn't support the linker_option directives,
474 // so we disable them if we think the .s file will be passed to it.
475 Default = TC.useIntegratedAs();
476 }
477 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
478 Default);
479}
480
481static bool ShouldDisableDwarfDirectory(const ArgList &Args,
482 const ToolChain &TC) {
483 bool UseDwarfDirectory =
484 Args.hasFlag(options::OPT_fdwarf_directory_asm,
485 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
486 return !UseDwarfDirectory;
487}
488
489// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
490// to the corresponding DebugInfoKind.
491static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
492 assert(A.getOption().matches(options::OPT_gN_Group) &&
493 "Not a -g option that specifies a debug-info level");
494 if (A.getOption().matches(options::OPT_g0) ||
495 A.getOption().matches(options::OPT_ggdb0))
496 return codegenoptions::NoDebugInfo;
497 if (A.getOption().matches(options::OPT_gline_tables_only) ||
498 A.getOption().matches(options::OPT_ggdb1))
499 return codegenoptions::DebugLineTablesOnly;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000500 if (A.getOption().matches(options::OPT_gline_directives_only))
501 return codegenoptions::DebugDirectivesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +0000502 return codegenoptions::LimitedDebugInfo;
503}
504
505static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
506 switch (Triple.getArch()){
507 default:
508 return false;
509 case llvm::Triple::arm:
510 case llvm::Triple::thumb:
511 // ARM Darwin targets require a frame pointer to be always present to aid
512 // offline debugging via backtraces.
513 return Triple.isOSDarwin();
514 }
515}
516
517static bool useFramePointerForTargetByDefault(const ArgList &Args,
518 const llvm::Triple &Triple) {
Fangrui Songdc039662019-07-12 02:01:51 +0000519 if (Args.hasArg(options::OPT_pg))
520 return true;
521
David L. Jonesf561aba2017-03-08 01:02:16 +0000522 switch (Triple.getArch()) {
523 case llvm::Triple::xcore:
524 case llvm::Triple::wasm32:
525 case llvm::Triple::wasm64:
Anton Korobeynikovf1f897c2019-02-05 20:15:03 +0000526 case llvm::Triple::msp430:
David L. Jonesf561aba2017-03-08 01:02:16 +0000527 // XCore never wants frame pointers, regardless of OS.
528 // WebAssembly never wants frame pointers.
529 return false;
Fangrui Song8c0b58f2019-07-12 02:14:08 +0000530 case llvm::Triple::ppc:
531 case llvm::Triple::ppc64:
532 case llvm::Triple::ppc64le:
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000533 case llvm::Triple::riscv32:
534 case llvm::Triple::riscv64:
535 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000536 default:
537 break;
538 }
539
Michal Gorny5a409d02018-12-20 13:09:30 +0000540 if (Triple.isOSNetBSD()) {
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000541 return !areOptimizationsEnabled(Args);
542 }
543
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000544 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
545 Triple.isOSHurd()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000546 switch (Triple.getArch()) {
547 // Don't use a frame pointer on linux if optimizing for certain targets.
548 case llvm::Triple::mips64:
549 case llvm::Triple::mips64el:
550 case llvm::Triple::mips:
551 case llvm::Triple::mipsel:
David L. Jonesf561aba2017-03-08 01:02:16 +0000552 case llvm::Triple::systemz:
553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 return !areOptimizationsEnabled(Args);
556 default:
557 return true;
558 }
559 }
560
561 if (Triple.isOSWindows()) {
562 switch (Triple.getArch()) {
563 case llvm::Triple::x86:
564 return !areOptimizationsEnabled(Args);
565 case llvm::Triple::x86_64:
566 return Triple.isOSBinFormatMachO();
567 case llvm::Triple::arm:
568 case llvm::Triple::thumb:
569 // Windows on ARM builds with FPO disabled to aid fast stack walking
570 return true;
571 default:
572 // All other supported Windows ISAs use xdata unwind information, so frame
573 // pointers are not generally useful.
574 return false;
575 }
576 }
577
578 return true;
579}
580
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000581static CodeGenOptions::FramePointerKind
582getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
Nico Weber2346b922019-08-13 17:37:09 +0000583 // We have 4 states:
584 //
585 // 00) leaf retained, non-leaf retained
586 // 01) leaf retained, non-leaf omitted (this is invalid)
587 // 10) leaf omitted, non-leaf retained
588 // (what -momit-leaf-frame-pointer was designed for)
589 // 11) leaf omitted, non-leaf omitted
590 //
591 // "omit" options taking precedence over "no-omit" options is the only way
592 // to make 3 valid states representable
Fangrui Songdc039662019-07-12 02:01:51 +0000593 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
594 options::OPT_fno_omit_frame_pointer);
595 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
596 bool NoOmitFP =
597 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
Nico Weber2346b922019-08-13 17:37:09 +0000598 bool KeepLeaf =
599 Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
600 options::OPT_mno_omit_leaf_frame_pointer, Triple.isPS4CPU());
Fangrui Songdc039662019-07-12 02:01:51 +0000601 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
602 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
Nico Weber2346b922019-08-13 17:37:09 +0000603 if (KeepLeaf)
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000604 return CodeGenOptions::FramePointerKind::NonLeaf;
605 return CodeGenOptions::FramePointerKind::All;
Fangrui Songdc039662019-07-12 02:01:51 +0000606 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000607 return CodeGenOptions::FramePointerKind::None;
David L. Jonesf561aba2017-03-08 01:02:16 +0000608}
609
610/// Add a CC1 option to specify the debug compilation directory.
Hans Wennborg999f8a72019-09-05 08:43:00 +0000611static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
Nico Weber37b75332019-06-17 12:10:40 +0000612 if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
613 CmdArgs.push_back("-fdebug-compilation-dir");
614 CmdArgs.push_back(A->getValue());
Hans Wennborg999f8a72019-09-05 08:43:00 +0000615 } else {
616 SmallString<128> cwd;
617 if (!llvm::sys::fs::current_path(cwd)) {
618 CmdArgs.push_back("-fdebug-compilation-dir");
619 CmdArgs.push_back(Args.MakeArgString(cwd));
620 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000621 }
622}
623
Paul Robinson9b292b42018-07-10 15:15:24 +0000624/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
625static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
626 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
627 StringRef Map = A->getValue();
628 if (Map.find('=') == StringRef::npos)
629 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
630 else
631 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
632 A->claim();
633 }
634}
635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000636/// Vectorize at all optimization levels greater than 1 except for -Oz.
Nico Weber37b75332019-06-17 12:10:40 +0000637/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
638/// enabled.
David L. Jonesf561aba2017-03-08 01:02:16 +0000639static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
640 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
641 if (A->getOption().matches(options::OPT_O4) ||
642 A->getOption().matches(options::OPT_Ofast))
643 return true;
644
645 if (A->getOption().matches(options::OPT_O0))
646 return false;
647
648 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
649
650 // Vectorize -Os.
651 StringRef S(A->getValue());
652 if (S == "s")
653 return true;
654
655 // Don't vectorize -Oz, unless it's the slp vectorizer.
656 if (S == "z")
657 return isSlpVec;
658
659 unsigned OptLevel = 0;
660 if (S.getAsInteger(10, OptLevel))
661 return false;
662
663 return OptLevel > 1;
664 }
665
666 return false;
667}
668
669/// Add -x lang to \p CmdArgs for \p Input.
670static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
671 ArgStringList &CmdArgs) {
672 // When using -verify-pch, we don't want to provide the type
673 // 'precompiled-header' if it was inferred from the file extension
674 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
675 return;
676
677 CmdArgs.push_back("-x");
678 if (Args.hasArg(options::OPT_rewrite_objc))
679 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000680 else {
681 // Map the driver type to the frontend type. This is mostly an identity
682 // mapping, except that the distinction between module interface units
683 // and other source files does not exist at the frontend layer.
684 const char *ClangType;
685 switch (Input.getType()) {
686 case types::TY_CXXModule:
687 ClangType = "c++";
688 break;
689 case types::TY_PP_CXXModule:
690 ClangType = "c++-cpp-output";
691 break;
692 default:
693 ClangType = types::getTypeName(Input.getType());
694 break;
695 }
696 CmdArgs.push_back(ClangType);
697 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000698}
699
700static void appendUserToPath(SmallVectorImpl<char> &Result) {
701#ifdef LLVM_ON_UNIX
702 const char *Username = getenv("LOGNAME");
703#else
704 const char *Username = getenv("USERNAME");
705#endif
706 if (Username) {
707 // Validate that LoginName can be used in a path, and get its length.
708 size_t Len = 0;
709 for (const char *P = Username; *P; ++P, ++Len) {
710 if (!clang::isAlphanumeric(*P) && *P != '_') {
711 Username = nullptr;
712 break;
713 }
714 }
715
716 if (Username && Len > 0) {
717 Result.append(Username, Username + Len);
718 return;
719 }
720 }
721
722// Fallback to user id.
723#ifdef LLVM_ON_UNIX
724 std::string UID = llvm::utostr(getuid());
725#else
726 // FIXME: Windows seems to have an 'SID' that might work.
727 std::string UID = "9999";
728#endif
729 Result.append(UID.begin(), UID.end());
730}
731
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000732static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
733 const Driver &D, const InputInfo &Output,
734 const ArgList &Args,
David L. Jonesf561aba2017-03-08 01:02:16 +0000735 ArgStringList &CmdArgs) {
736
737 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
738 options::OPT_fprofile_generate_EQ,
739 options::OPT_fno_profile_generate);
740 if (PGOGenerateArg &&
741 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
742 PGOGenerateArg = nullptr;
743
Rong Xua4a09b22019-03-04 20:21:31 +0000744 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
745 options::OPT_fcs_profile_generate_EQ,
746 options::OPT_fno_profile_generate);
747 if (CSPGOGenerateArg &&
748 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
749 CSPGOGenerateArg = nullptr;
750
David L. Jonesf561aba2017-03-08 01:02:16 +0000751 auto *ProfileGenerateArg = Args.getLastArg(
752 options::OPT_fprofile_instr_generate,
753 options::OPT_fprofile_instr_generate_EQ,
754 options::OPT_fno_profile_instr_generate);
755 if (ProfileGenerateArg &&
756 ProfileGenerateArg->getOption().matches(
757 options::OPT_fno_profile_instr_generate))
758 ProfileGenerateArg = nullptr;
759
760 if (PGOGenerateArg && ProfileGenerateArg)
761 D.Diag(diag::err_drv_argument_not_allowed_with)
762 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
763
764 auto *ProfileUseArg = getLastProfileUseArg(Args);
765
766 if (PGOGenerateArg && ProfileUseArg)
767 D.Diag(diag::err_drv_argument_not_allowed_with)
768 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
769
770 if (ProfileGenerateArg && ProfileUseArg)
771 D.Diag(diag::err_drv_argument_not_allowed_with)
772 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
773
Rong Xua4a09b22019-03-04 20:21:31 +0000774 if (CSPGOGenerateArg && PGOGenerateArg)
775 D.Diag(diag::err_drv_argument_not_allowed_with)
776 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
777
David L. Jonesf561aba2017-03-08 01:02:16 +0000778 if (ProfileGenerateArg) {
779 if (ProfileGenerateArg->getOption().matches(
780 options::OPT_fprofile_instr_generate_EQ))
781 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
782 ProfileGenerateArg->getValue()));
783 // The default is to use Clang Instrumentation.
784 CmdArgs.push_back("-fprofile-instrument=clang");
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000785 if (TC.getTriple().isWindowsMSVCEnvironment()) {
786 // Add dependent lib for clang_rt.profile
787 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
788 TC.getCompilerRT(Args, "profile")));
789 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000790 }
791
Rong Xua4a09b22019-03-04 20:21:31 +0000792 Arg *PGOGenArg = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +0000793 if (PGOGenerateArg) {
Rong Xua4a09b22019-03-04 20:21:31 +0000794 assert(!CSPGOGenerateArg);
795 PGOGenArg = PGOGenerateArg;
David L. Jonesf561aba2017-03-08 01:02:16 +0000796 CmdArgs.push_back("-fprofile-instrument=llvm");
Rong Xua4a09b22019-03-04 20:21:31 +0000797 }
798 if (CSPGOGenerateArg) {
799 assert(!PGOGenerateArg);
800 PGOGenArg = CSPGOGenerateArg;
801 CmdArgs.push_back("-fprofile-instrument=csllvm");
802 }
803 if (PGOGenArg) {
Russell Gallop72fea1d2019-05-22 10:06:49 +0000804 if (TC.getTriple().isWindowsMSVCEnvironment()) {
805 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
806 TC.getCompilerRT(Args, "profile")));
807 }
Rong Xua4a09b22019-03-04 20:21:31 +0000808 if (PGOGenArg->getOption().matches(
809 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
810 : options::OPT_fcs_profile_generate_EQ)) {
811 SmallString<128> Path(PGOGenArg->getValue());
David L. Jonesf561aba2017-03-08 01:02:16 +0000812 llvm::sys::path::append(Path, "default_%m.profraw");
813 CmdArgs.push_back(
814 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
815 }
816 }
817
818 if (ProfileUseArg) {
819 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
820 CmdArgs.push_back(Args.MakeArgString(
821 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
822 else if ((ProfileUseArg->getOption().matches(
823 options::OPT_fprofile_use_EQ) ||
824 ProfileUseArg->getOption().matches(
825 options::OPT_fprofile_instr_use))) {
826 SmallString<128> Path(
827 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
828 if (Path.empty() || llvm::sys::fs::is_directory(Path))
829 llvm::sys::path::append(Path, "default.profdata");
830 CmdArgs.push_back(
831 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
832 }
833 }
834
Reid Klecknere440d232019-09-26 18:13:19 +0000835 bool EmitCovNotes = Args.hasArg(options::OPT_ftest_coverage) ||
836 Args.hasArg(options::OPT_coverage);
837 bool EmitCovData = Args.hasFlag(options::OPT_fprofile_arcs,
838 options::OPT_fno_profile_arcs, false) ||
839 Args.hasArg(options::OPT_coverage);
840 if (EmitCovNotes)
David L. Jonesf561aba2017-03-08 01:02:16 +0000841 CmdArgs.push_back("-femit-coverage-notes");
Reid Klecknere440d232019-09-26 18:13:19 +0000842 if (EmitCovData)
David L. Jonesf561aba2017-03-08 01:02:16 +0000843 CmdArgs.push_back("-femit-coverage-data");
844
845 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000846 options::OPT_fno_coverage_mapping, false)) {
847 if (!ProfileGenerateArg)
848 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
849 << "-fcoverage-mapping"
850 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000851
David L. Jonesf561aba2017-03-08 01:02:16 +0000852 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000853 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000854
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000855 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
856 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
857 if (!Args.hasArg(options::OPT_coverage))
858 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
859 << "-fprofile-exclude-files="
860 << "--coverage";
861
862 StringRef v = Arg->getValue();
863 CmdArgs.push_back(
864 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
865 }
866
867 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
868 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
869 if (!Args.hasArg(options::OPT_coverage))
870 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
871 << "-fprofile-filter-files="
872 << "--coverage";
873
874 StringRef v = Arg->getValue();
875 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
876 }
877
Reid Klecknere440d232019-09-26 18:13:19 +0000878 // Leave -fprofile-dir= an unused argument unless .gcda emission is
879 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
880 // the flag used. There is no -fno-profile-dir, so the user has no
881 // targeted way to suppress the warning.
882 Arg *FProfileDir = nullptr;
883 if (Args.hasArg(options::OPT_fprofile_arcs) ||
884 Args.hasArg(options::OPT_coverage))
885 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
David L. Jonesf561aba2017-03-08 01:02:16 +0000886
Reid Klecknere440d232019-09-26 18:13:19 +0000887 // Put the .gcno and .gcda files (if needed) next to the object file or
888 // bitcode file in the case of LTO.
889 // FIXME: There should be a simpler way to find the object file for this
890 // input, and this code probably does the wrong thing for commands that
891 // compile and link all at once.
892 if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
893 (EmitCovNotes || EmitCovData) && Output.isFilename()) {
894 SmallString<128> OutputFilename;
895 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
896 OutputFilename = FinalOutput->getValue();
897 else
898 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
899 SmallString<128> CoverageFilename = OutputFilename;
900 if (llvm::sys::path::is_relative(CoverageFilename)) {
901 SmallString<128> Pwd;
902 if (!llvm::sys::fs::current_path(Pwd)) {
903 llvm::sys::path::append(Pwd, CoverageFilename);
904 CoverageFilename.swap(Pwd);
David L. Jonesf561aba2017-03-08 01:02:16 +0000905 }
906 }
Reid Klecknere440d232019-09-26 18:13:19 +0000907 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
908
909 CmdArgs.push_back("-coverage-notes-file");
910 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
911
912 if (EmitCovData) {
913 if (FProfileDir) {
914 CoverageFilename = FProfileDir->getValue();
915 llvm::sys::path::append(CoverageFilename, OutputFilename);
916 }
917 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
918 CmdArgs.push_back("-coverage-data-file");
919 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
920 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000921 }
922}
923
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000924/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000925static bool ContainsCompileAction(const Action *A) {
926 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
927 return true;
928
929 for (const auto &AI : A->inputs())
930 if (ContainsCompileAction(AI))
931 return true;
932
933 return false;
934}
935
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000936/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000937/// This is done by default when compiling non-assembler source with -O0.
938static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
939 bool RelaxDefault = true;
940
941 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
942 RelaxDefault = A->getOption().matches(options::OPT_O0);
943
944 if (RelaxDefault) {
945 RelaxDefault = false;
946 for (const auto &Act : C.getActions()) {
947 if (ContainsCompileAction(Act)) {
948 RelaxDefault = true;
949 break;
950 }
951 }
952 }
953
954 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
955 RelaxDefault);
956}
957
958// Extract the integer N from a string spelled "-dwarf-N", returning 0
959// on mismatch. The StringRef input (rather than an Arg) allows
960// for use by the "-Xassembler" option parser.
961static unsigned DwarfVersionNum(StringRef ArgValue) {
962 return llvm::StringSwitch<unsigned>(ArgValue)
963 .Case("-gdwarf-2", 2)
964 .Case("-gdwarf-3", 3)
965 .Case("-gdwarf-4", 4)
966 .Case("-gdwarf-5", 5)
967 .Default(0);
968}
969
970static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
971 codegenoptions::DebugInfoKind DebugInfoKind,
972 unsigned DwarfVersion,
973 llvm::DebuggerKind DebuggerTuning) {
974 switch (DebugInfoKind) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000975 case codegenoptions::DebugDirectivesOnly:
976 CmdArgs.push_back("-debug-info-kind=line-directives-only");
977 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000978 case codegenoptions::DebugLineTablesOnly:
979 CmdArgs.push_back("-debug-info-kind=line-tables-only");
980 break;
981 case codegenoptions::LimitedDebugInfo:
982 CmdArgs.push_back("-debug-info-kind=limited");
983 break;
984 case codegenoptions::FullDebugInfo:
985 CmdArgs.push_back("-debug-info-kind=standalone");
986 break;
987 default:
988 break;
989 }
990 if (DwarfVersion > 0)
991 CmdArgs.push_back(
992 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
993 switch (DebuggerTuning) {
994 case llvm::DebuggerKind::GDB:
995 CmdArgs.push_back("-debugger-tuning=gdb");
996 break;
997 case llvm::DebuggerKind::LLDB:
998 CmdArgs.push_back("-debugger-tuning=lldb");
999 break;
1000 case llvm::DebuggerKind::SCE:
1001 CmdArgs.push_back("-debugger-tuning=sce");
1002 break;
1003 default:
1004 break;
1005 }
1006}
1007
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001008static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1009 const Driver &D, const ToolChain &TC) {
1010 assert(A && "Expected non-nullptr argument.");
1011 if (TC.supportsDebugInfoOption(A))
1012 return true;
1013 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1014 << A->getAsString(Args) << TC.getTripleString();
1015 return false;
1016}
1017
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001018static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1019 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001020 const Driver &D,
1021 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001022 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
1023 if (!A)
1024 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001025 if (checkDebugInfoOption(A, Args, D, TC)) {
1026 if (A->getOption().getID() == options::OPT_gz) {
1027 if (llvm::zlib::isAvailable())
Fangrui Songbaabc872019-05-11 01:14:50 +00001028 CmdArgs.push_back("--compress-debug-sections");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001029 else
1030 D.Diag(diag::warn_debug_compression_unavailable);
1031 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001032 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001033
1034 StringRef Value = A->getValue();
1035 if (Value == "none") {
Fangrui Songbaabc872019-05-11 01:14:50 +00001036 CmdArgs.push_back("--compress-debug-sections=none");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001037 } else if (Value == "zlib" || Value == "zlib-gnu") {
1038 if (llvm::zlib::isAvailable()) {
1039 CmdArgs.push_back(
Fangrui Songbaabc872019-05-11 01:14:50 +00001040 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001041 } else {
1042 D.Diag(diag::warn_debug_compression_unavailable);
1043 }
1044 } else {
1045 D.Diag(diag::err_drv_unsupported_option_argument)
1046 << A->getOption().getName() << Value;
1047 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001048 }
1049}
1050
David L. Jonesf561aba2017-03-08 01:02:16 +00001051static const char *RelocationModelName(llvm::Reloc::Model Model) {
1052 switch (Model) {
1053 case llvm::Reloc::Static:
1054 return "static";
1055 case llvm::Reloc::PIC_:
1056 return "pic";
1057 case llvm::Reloc::DynamicNoPIC:
1058 return "dynamic-no-pic";
1059 case llvm::Reloc::ROPI:
1060 return "ropi";
1061 case llvm::Reloc::RWPI:
1062 return "rwpi";
1063 case llvm::Reloc::ROPI_RWPI:
1064 return "ropi-rwpi";
1065 }
1066 llvm_unreachable("Unknown Reloc::Model kind");
1067}
1068
1069void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1070 const Driver &D, const ArgList &Args,
1071 ArgStringList &CmdArgs,
1072 const InputInfo &Output,
1073 const InputInfoList &Inputs) const {
David L. Jonesf561aba2017-03-08 01:02:16 +00001074 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1075
1076 CheckPreprocessingOptions(D, Args);
1077
1078 Args.AddLastArg(CmdArgs, options::OPT_C);
1079 Args.AddLastArg(CmdArgs, options::OPT_CC);
1080
1081 // Handle dependency file generation.
Fangrui Song55abd2b2019-09-14 06:01:22 +00001082 Arg *ArgM = Args.getLastArg(options::OPT_MM);
1083 if (!ArgM)
1084 ArgM = Args.getLastArg(options::OPT_M);
1085 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1086 if (!ArgMD)
1087 ArgMD = Args.getLastArg(options::OPT_MD);
1088
1089 // -M and -MM imply -w.
1090 if (ArgM)
1091 CmdArgs.push_back("-w");
1092 else
1093 ArgM = ArgMD;
1094
1095 if (ArgM) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001096 // Determine the output location.
1097 const char *DepFile;
1098 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1099 DepFile = MF->getValue();
1100 C.addFailureResultFile(DepFile, &JA);
1101 } else if (Output.getType() == types::TY_Dependencies) {
1102 DepFile = Output.getFilename();
Fangrui Song55abd2b2019-09-14 06:01:22 +00001103 } else if (!ArgMD) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001104 DepFile = "-";
1105 } else {
1106 DepFile = getDependencyFileName(Args, Inputs);
1107 C.addFailureResultFile(DepFile, &JA);
1108 }
1109 CmdArgs.push_back("-dependency-file");
1110 CmdArgs.push_back(DepFile);
1111
Fangrui Song55abd2b2019-09-14 06:01:22 +00001112 bool HasTarget = false;
1113 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1114 HasTarget = true;
1115 A->claim();
1116 if (A->getOption().matches(options::OPT_MT)) {
1117 A->render(Args, CmdArgs);
1118 } else {
1119 CmdArgs.push_back("-MT");
1120 SmallString<128> Quoted;
1121 QuoteTarget(A->getValue(), Quoted);
1122 CmdArgs.push_back(Args.MakeArgString(Quoted));
1123 }
1124 }
1125
David L. Jonesf561aba2017-03-08 01:02:16 +00001126 // Add a default target if one wasn't specified.
Fangrui Song55abd2b2019-09-14 06:01:22 +00001127 if (!HasTarget) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001128 const char *DepTarget;
1129
1130 // If user provided -o, that is the dependency target, except
1131 // when we are only generating a dependency file.
1132 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1133 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1134 DepTarget = OutputOpt->getValue();
1135 } else {
1136 // Otherwise derive from the base input.
1137 //
1138 // FIXME: This should use the computed output file location.
1139 SmallString<128> P(Inputs[0].getBaseInput());
1140 llvm::sys::path::replace_extension(P, "o");
1141 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1142 }
1143
1144 CmdArgs.push_back("-MT");
1145 SmallString<128> Quoted;
1146 QuoteTarget(DepTarget, Quoted);
1147 CmdArgs.push_back(Args.MakeArgString(Quoted));
1148 }
1149
Fangrui Song55abd2b2019-09-14 06:01:22 +00001150 if (ArgM->getOption().matches(options::OPT_M) ||
1151 ArgM->getOption().matches(options::OPT_MD))
David L. Jonesf561aba2017-03-08 01:02:16 +00001152 CmdArgs.push_back("-sys-header-deps");
1153 if ((isa<PrecompileJobAction>(JA) &&
1154 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1155 Args.hasArg(options::OPT_fmodule_file_deps))
1156 CmdArgs.push_back("-module-file-deps");
1157 }
1158
1159 if (Args.hasArg(options::OPT_MG)) {
Fangrui Song55abd2b2019-09-14 06:01:22 +00001160 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1161 ArgM->getOption().matches(options::OPT_MMD))
David L. Jonesf561aba2017-03-08 01:02:16 +00001162 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1163 CmdArgs.push_back("-MG");
1164 }
1165
1166 Args.AddLastArg(CmdArgs, options::OPT_MP);
1167 Args.AddLastArg(CmdArgs, options::OPT_MV);
1168
David L. Jonesf561aba2017-03-08 01:02:16 +00001169 // Add offload include arguments specific for CUDA. This must happen before
1170 // we -I or -include anything else, because we must pick up the CUDA headers
1171 // from the particular CUDA installation, rather than from e.g.
1172 // /usr/local/include.
1173 if (JA.isOffloading(Action::OFK_Cuda))
1174 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1175
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001176 // If we are offloading to a target via OpenMP we need to include the
1177 // openmp_wrappers folder which contains alternative system headers.
1178 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1179 getToolChain().getTriple().isNVPTX()){
1180 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1181 // Add openmp_wrappers/* to our system include path. This lets us wrap
1182 // standard library headers.
1183 SmallString<128> P(D.ResourceDir);
1184 llvm::sys::path::append(P, "include");
1185 llvm::sys::path::append(P, "openmp_wrappers");
1186 CmdArgs.push_back("-internal-isystem");
1187 CmdArgs.push_back(Args.MakeArgString(P));
1188 }
1189
1190 CmdArgs.push_back("-include");
Gheorghe-Teodor Bercea94695712019-05-13 22:11:44 +00001191 CmdArgs.push_back("__clang_openmp_math_declares.h");
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001192 }
1193
David L. Jonesf561aba2017-03-08 01:02:16 +00001194 // Add -i* options, and automatically translate to
1195 // -include-pch/-include-pth for transparent PCH support. It's
1196 // wonky, but we include looking for .gch so we can support seamless
1197 // replacement into a build system already set up to be generating
1198 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001199
1200 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001201 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1202 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001203 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1204 JA.getKind() <= Action::AssembleJobClass) {
1205 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001206 }
Erich Keane76675de2018-07-05 17:22:13 +00001207 if (YcArg || YuArg) {
1208 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1209 if (!isa<PrecompileJobAction>(JA)) {
1210 CmdArgs.push_back("-include-pch");
Mike Rice58df1af2018-09-11 17:10:44 +00001211 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1212 C, !ThroughHeader.empty()
1213 ? ThroughHeader
1214 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
Erich Keane76675de2018-07-05 17:22:13 +00001215 }
Mike Rice58df1af2018-09-11 17:10:44 +00001216
1217 if (ThroughHeader.empty()) {
1218 CmdArgs.push_back(Args.MakeArgString(
1219 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1220 } else {
1221 CmdArgs.push_back(
1222 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1223 }
Erich Keane76675de2018-07-05 17:22:13 +00001224 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001225 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001226
1227 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001228 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001229 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001230 // Handling of gcc-style gch precompiled headers.
1231 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1232 RenderedImplicitInclude = true;
1233
David L. Jonesf561aba2017-03-08 01:02:16 +00001234 bool FoundPCH = false;
1235 SmallString<128> P(A->getValue());
1236 // We want the files to have a name like foo.h.pch. Add a dummy extension
1237 // so that replace_extension does the right thing.
1238 P += ".dummy";
Erich Keane0a6b5b62018-12-04 14:34:09 +00001239 llvm::sys::path::replace_extension(P, "pch");
1240 if (llvm::sys::fs::exists(P))
1241 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001242
1243 if (!FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001244 llvm::sys::path::replace_extension(P, "gch");
1245 if (llvm::sys::fs::exists(P)) {
Erich Keane0a6b5b62018-12-04 14:34:09 +00001246 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001247 }
1248 }
1249
Erich Keane0a6b5b62018-12-04 14:34:09 +00001250 if (FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001251 if (IsFirstImplicitInclude) {
1252 A->claim();
Erich Keane0a6b5b62018-12-04 14:34:09 +00001253 CmdArgs.push_back("-include-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00001254 CmdArgs.push_back(Args.MakeArgString(P));
1255 continue;
1256 } else {
1257 // Ignore the PCH if not first on command line and emit warning.
1258 D.Diag(diag::warn_drv_pch_not_first_include) << P
1259 << A->getAsString(Args);
1260 }
1261 }
1262 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1263 // Handling of paths which must come late. These entries are handled by
1264 // the toolchain itself after the resource dir is inserted in the right
1265 // search order.
1266 // Do not claim the argument so that the use of the argument does not
1267 // silently go unnoticed on toolchains which do not honour the option.
1268 continue;
Shoaib Meenaib50e8c52019-08-06 06:48:43 +00001269 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1270 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1271 continue;
David L. Jonesf561aba2017-03-08 01:02:16 +00001272 }
1273
1274 // Not translated, render as usual.
1275 A->claim();
1276 A->render(Args, CmdArgs);
1277 }
1278
1279 Args.AddAllArgs(CmdArgs,
1280 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1281 options::OPT_F, options::OPT_index_header_map});
1282
1283 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1284
1285 // FIXME: There is a very unfortunate problem here, some troubled
1286 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1287 // really support that we would have to parse and then translate
1288 // those options. :(
1289 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1290 options::OPT_Xpreprocessor);
1291
1292 // -I- is a deprecated GCC feature, reject it.
1293 if (Arg *A = Args.getLastArg(options::OPT_I_))
1294 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1295
1296 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1297 // -isysroot to the CC1 invocation.
1298 StringRef sysroot = C.getSysRoot();
1299 if (sysroot != "") {
1300 if (!Args.hasArg(options::OPT_isysroot)) {
1301 CmdArgs.push_back("-isysroot");
1302 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1303 }
1304 }
1305
1306 // Parse additional include paths from environment variables.
1307 // FIXME: We should probably sink the logic for handling these from the
1308 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1309 // CPATH - included following the user specified includes (but prior to
1310 // builtin and standard includes).
1311 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1312 // C_INCLUDE_PATH - system includes enabled when compiling C.
1313 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1314 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1315 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1316 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1317 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1318 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1319 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1320
1321 // While adding the include arguments, we also attempt to retrieve the
1322 // arguments of related offloading toolchains or arguments that are specific
1323 // of an offloading programming model.
1324
1325 // Add C++ include arguments, if needed.
Shoaib Meenaib50e8c52019-08-06 06:48:43 +00001326 if (types::isCXX(Inputs[0].getType())) {
1327 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1328 forAllAssociatedToolChains(
1329 C, JA, getToolChain(),
1330 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1331 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1332 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1333 });
1334 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001335
1336 // Add system include arguments for all targets but IAMCU.
1337 if (!IsIAMCU)
1338 forAllAssociatedToolChains(C, JA, getToolChain(),
1339 [&Args, &CmdArgs](const ToolChain &TC) {
1340 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1341 });
1342 else {
1343 // For IAMCU add special include arguments.
1344 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1345 }
1346}
1347
1348// FIXME: Move to target hook.
1349static bool isSignedCharDefault(const llvm::Triple &Triple) {
1350 switch (Triple.getArch()) {
1351 default:
1352 return true;
1353
1354 case llvm::Triple::aarch64:
1355 case llvm::Triple::aarch64_be:
1356 case llvm::Triple::arm:
1357 case llvm::Triple::armeb:
1358 case llvm::Triple::thumb:
1359 case llvm::Triple::thumbeb:
1360 if (Triple.isOSDarwin() || Triple.isOSWindows())
1361 return true;
1362 return false;
1363
1364 case llvm::Triple::ppc:
1365 case llvm::Triple::ppc64:
1366 if (Triple.isOSDarwin())
1367 return true;
1368 return false;
1369
1370 case llvm::Triple::hexagon:
1371 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001372 case llvm::Triple::riscv32:
1373 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001374 case llvm::Triple::systemz:
1375 case llvm::Triple::xcore:
1376 return false;
1377 }
1378}
1379
1380static bool isNoCommonDefault(const llvm::Triple &Triple) {
1381 switch (Triple.getArch()) {
1382 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001383 if (Triple.isOSFuchsia())
1384 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001385 return false;
1386
1387 case llvm::Triple::xcore:
1388 case llvm::Triple::wasm32:
1389 case llvm::Triple::wasm64:
1390 return true;
1391 }
1392}
1393
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001394namespace {
1395void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1396 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001397 // Select the ABI to use.
1398 // FIXME: Support -meabi.
1399 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1400 const char *ABIName = nullptr;
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001401 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001402 ABIName = A->getValue();
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001403 } else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001404 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001405 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001406 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001407
David L. Jonesf561aba2017-03-08 01:02:16 +00001408 CmdArgs.push_back("-target-abi");
1409 CmdArgs.push_back(ABIName);
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001410}
1411}
1412
1413void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1414 ArgStringList &CmdArgs, bool KernelOrKext) const {
1415 RenderARMABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001416
1417 // Determine floating point ABI from the options & target defaults.
1418 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1419 if (ABI == arm::FloatABI::Soft) {
1420 // Floating point operations and argument passing are soft.
1421 // FIXME: This changes CPP defines, we need -target-soft-float.
1422 CmdArgs.push_back("-msoft-float");
1423 CmdArgs.push_back("-mfloat-abi");
1424 CmdArgs.push_back("soft");
1425 } else if (ABI == arm::FloatABI::SoftFP) {
1426 // Floating point operations are hard, but argument passing is soft.
1427 CmdArgs.push_back("-mfloat-abi");
1428 CmdArgs.push_back("soft");
1429 } else {
1430 // Floating point operations and argument passing are hard.
1431 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1432 CmdArgs.push_back("-mfloat-abi");
1433 CmdArgs.push_back("hard");
1434 }
1435
1436 // Forward the -mglobal-merge option for explicit control over the pass.
1437 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1438 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001439 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001440 if (A->getOption().matches(options::OPT_mno_global_merge))
1441 CmdArgs.push_back("-arm-global-merge=false");
1442 else
1443 CmdArgs.push_back("-arm-global-merge=true");
1444 }
1445
1446 if (!Args.hasFlag(options::OPT_mimplicit_float,
1447 options::OPT_mno_implicit_float, true))
1448 CmdArgs.push_back("-no-implicit-float");
Javed Absar603a2ba2019-05-21 14:21:26 +00001449
1450 if (Args.getLastArg(options::OPT_mcmse))
1451 CmdArgs.push_back("-mcmse");
David L. Jonesf561aba2017-03-08 01:02:16 +00001452}
1453
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001454void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1455 const ArgList &Args, bool KernelOrKext,
1456 ArgStringList &CmdArgs) const {
1457 const ToolChain &TC = getToolChain();
1458
1459 // Add the target features
1460 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1461
1462 // Add target specific flags.
1463 switch (TC.getArch()) {
1464 default:
1465 break;
1466
1467 case llvm::Triple::arm:
1468 case llvm::Triple::armeb:
1469 case llvm::Triple::thumb:
1470 case llvm::Triple::thumbeb:
1471 // Use the effective triple, which takes into account the deployment target.
1472 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1473 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1474 break;
1475
1476 case llvm::Triple::aarch64:
1477 case llvm::Triple::aarch64_be:
1478 AddAArch64TargetArgs(Args, CmdArgs);
1479 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1480 break;
1481
1482 case llvm::Triple::mips:
1483 case llvm::Triple::mipsel:
1484 case llvm::Triple::mips64:
1485 case llvm::Triple::mips64el:
1486 AddMIPSTargetArgs(Args, CmdArgs);
1487 break;
1488
1489 case llvm::Triple::ppc:
1490 case llvm::Triple::ppc64:
1491 case llvm::Triple::ppc64le:
1492 AddPPCTargetArgs(Args, CmdArgs);
1493 break;
1494
Alex Bradbury71f45452018-01-11 13:36:56 +00001495 case llvm::Triple::riscv32:
1496 case llvm::Triple::riscv64:
1497 AddRISCVTargetArgs(Args, CmdArgs);
1498 break;
1499
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001500 case llvm::Triple::sparc:
1501 case llvm::Triple::sparcel:
1502 case llvm::Triple::sparcv9:
1503 AddSparcTargetArgs(Args, CmdArgs);
1504 break;
1505
1506 case llvm::Triple::systemz:
1507 AddSystemZTargetArgs(Args, CmdArgs);
1508 break;
1509
1510 case llvm::Triple::x86:
1511 case llvm::Triple::x86_64:
1512 AddX86TargetArgs(Args, CmdArgs);
1513 break;
1514
1515 case llvm::Triple::lanai:
1516 AddLanaiTargetArgs(Args, CmdArgs);
1517 break;
1518
1519 case llvm::Triple::hexagon:
1520 AddHexagonTargetArgs(Args, CmdArgs);
1521 break;
1522
1523 case llvm::Triple::wasm32:
1524 case llvm::Triple::wasm64:
1525 AddWebAssemblyTargetArgs(Args, CmdArgs);
1526 break;
1527 }
1528}
1529
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001530// Parse -mbranch-protection=<protection>[+<protection>]* where
1531// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1532// Returns a triple of (return address signing Scope, signing key, require
1533// landing pads)
1534static std::tuple<StringRef, StringRef, bool>
1535ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1536 const Arg *A) {
1537 StringRef Scope = "none";
1538 StringRef Key = "a_key";
1539 bool IndirectBranches = false;
1540
1541 StringRef Value = A->getValue();
1542 // This maps onto -mbranch-protection=<scope>+<key>
1543
1544 if (Value.equals("standard")) {
1545 Scope = "non-leaf";
1546 Key = "a_key";
1547 IndirectBranches = true;
1548
1549 } else if (!Value.equals("none")) {
1550 SmallVector<StringRef, 4> BranchProtection;
1551 StringRef(A->getValue()).split(BranchProtection, '+');
1552
1553 auto Protection = BranchProtection.begin();
1554 while (Protection != BranchProtection.end()) {
1555 if (Protection->equals("bti"))
1556 IndirectBranches = true;
1557 else if (Protection->equals("pac-ret")) {
1558 Scope = "non-leaf";
1559 while (++Protection != BranchProtection.end()) {
1560 // Inner loop as "leaf" and "b-key" options must only appear attached
1561 // to pac-ret.
1562 if (Protection->equals("leaf"))
1563 Scope = "all";
1564 else if (Protection->equals("b-key"))
1565 Key = "b_key";
1566 else
1567 break;
1568 }
1569 Protection--;
1570 } else
1571 D.Diag(diag::err_invalid_branch_protection)
1572 << *Protection << A->getAsString(Args);
1573 Protection++;
1574 }
1575 }
1576
1577 return std::make_tuple(Scope, Key, IndirectBranches);
1578}
1579
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001580namespace {
1581void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1582 ArgStringList &CmdArgs) {
1583 const char *ABIName = nullptr;
1584 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1585 ABIName = A->getValue();
1586 else if (Triple.isOSDarwin())
1587 ABIName = "darwinpcs";
1588 else
1589 ABIName = "aapcs";
1590
1591 CmdArgs.push_back("-target-abi");
1592 CmdArgs.push_back(ABIName);
1593}
1594}
1595
David L. Jonesf561aba2017-03-08 01:02:16 +00001596void Clang::AddAArch64TargetArgs(const ArgList &Args,
1597 ArgStringList &CmdArgs) const {
1598 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1599
1600 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1601 Args.hasArg(options::OPT_mkernel) ||
1602 Args.hasArg(options::OPT_fapple_kext))
1603 CmdArgs.push_back("-disable-red-zone");
1604
1605 if (!Args.hasFlag(options::OPT_mimplicit_float,
1606 options::OPT_mno_implicit_float, true))
1607 CmdArgs.push_back("-no-implicit-float");
1608
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001609 RenderAArch64ABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001610
1611 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1612 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001613 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001614 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1615 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1616 else
1617 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1618 } else if (Triple.isAndroid()) {
1619 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001620 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001621 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1622 }
1623
1624 // Forward the -mglobal-merge option for explicit control over the pass.
1625 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1626 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001627 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001628 if (A->getOption().matches(options::OPT_mno_global_merge))
1629 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1630 else
1631 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1632 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001633
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001634 // Enable/disable return address signing and indirect branch targets.
1635 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1636 options::OPT_mbranch_protection_EQ)) {
1637
1638 const Driver &D = getToolChain().getDriver();
1639
1640 StringRef Scope, Key;
1641 bool IndirectBranches;
1642
1643 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1644 Scope = A->getValue();
1645 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1646 !Scope.equals("all"))
1647 D.Diag(diag::err_invalid_branch_protection)
1648 << Scope << A->getAsString(Args);
1649 Key = "a_key";
1650 IndirectBranches = false;
1651 } else
1652 std::tie(Scope, Key, IndirectBranches) =
1653 ParseAArch64BranchProtection(D, Args, A);
1654
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001655 CmdArgs.push_back(
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001656 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1657 CmdArgs.push_back(
1658 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1659 if (IndirectBranches)
1660 CmdArgs.push_back("-mbranch-target-enforce");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001661 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001662}
1663
1664void Clang::AddMIPSTargetArgs(const ArgList &Args,
1665 ArgStringList &CmdArgs) const {
1666 const Driver &D = getToolChain().getDriver();
1667 StringRef CPUName;
1668 StringRef ABIName;
1669 const llvm::Triple &Triple = getToolChain().getTriple();
1670 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1671
1672 CmdArgs.push_back("-target-abi");
1673 CmdArgs.push_back(ABIName.data());
1674
1675 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1676 if (ABI == mips::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(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1684 CmdArgs.push_back("-mfloat-abi");
1685 CmdArgs.push_back("hard");
1686 }
1687
David L. Jonesf561aba2017-03-08 01:02:16 +00001688 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1689 options::OPT_mno_ldc1_sdc1)) {
1690 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1691 CmdArgs.push_back("-mllvm");
1692 CmdArgs.push_back("-mno-ldc1-sdc1");
1693 }
1694 }
1695
1696 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1697 options::OPT_mno_check_zero_division)) {
1698 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1699 CmdArgs.push_back("-mllvm");
1700 CmdArgs.push_back("-mno-check-zero-division");
1701 }
1702 }
1703
1704 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1705 StringRef v = A->getValue();
1706 CmdArgs.push_back("-mllvm");
1707 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1708 A->claim();
1709 }
1710
Simon Dardis31636a12017-07-20 14:04:12 +00001711 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1712 Arg *ABICalls =
1713 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1714
1715 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1716 // -mgpopt is the default for static, -fno-pic environments but these two
1717 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1718 // the only case where -mllvm -mgpopt is passed.
1719 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1720 // passed explicitly when compiling something with -mabicalls
1721 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001722 //
1723 // When the ABI in use is N64, we also need to determine the PIC mode that
1724 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001725 bool NoABICalls =
1726 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001727
1728 llvm::Reloc::Model RelocationModel;
1729 unsigned PICLevel;
1730 bool IsPIE;
1731 std::tie(RelocationModel, PICLevel, IsPIE) =
1732 ParsePICArgs(getToolChain(), Args);
1733
1734 NoABICalls = NoABICalls ||
1735 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1736
Simon Dardis31636a12017-07-20 14:04:12 +00001737 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1738 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1739 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1740 CmdArgs.push_back("-mllvm");
1741 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001742
1743 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1744 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001745 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001746 options::OPT_mno_extern_sdata);
1747 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1748 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001749 if (LocalSData) {
1750 CmdArgs.push_back("-mllvm");
1751 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1752 CmdArgs.push_back("-mlocal-sdata=1");
1753 } else {
1754 CmdArgs.push_back("-mlocal-sdata=0");
1755 }
1756 LocalSData->claim();
1757 }
1758
Simon Dardis7d318782017-07-24 14:02:09 +00001759 if (ExternSData) {
1760 CmdArgs.push_back("-mllvm");
1761 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1762 CmdArgs.push_back("-mextern-sdata=1");
1763 } else {
1764 CmdArgs.push_back("-mextern-sdata=0");
1765 }
1766 ExternSData->claim();
1767 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001768
1769 if (EmbeddedData) {
1770 CmdArgs.push_back("-mllvm");
1771 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1772 CmdArgs.push_back("-membedded-data=1");
1773 } else {
1774 CmdArgs.push_back("-membedded-data=0");
1775 }
1776 EmbeddedData->claim();
1777 }
1778
Simon Dardis31636a12017-07-20 14:04:12 +00001779 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1780 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1781
1782 if (GPOpt)
1783 GPOpt->claim();
1784
David L. Jonesf561aba2017-03-08 01:02:16 +00001785 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1786 StringRef Val = StringRef(A->getValue());
1787 if (mips::hasCompactBranches(CPUName)) {
1788 if (Val == "never" || Val == "always" || Val == "optimal") {
1789 CmdArgs.push_back("-mllvm");
1790 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1791 } else
1792 D.Diag(diag::err_drv_unsupported_option_argument)
1793 << A->getOption().getName() << Val;
1794 } else
1795 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1796 }
Vladimir Stefanovic99113a02019-01-18 19:54:51 +00001797
1798 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1799 options::OPT_mno_relax_pic_calls)) {
1800 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1801 CmdArgs.push_back("-mllvm");
1802 CmdArgs.push_back("-mips-jalr-reloc=0");
1803 }
1804 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001805}
1806
1807void Clang::AddPPCTargetArgs(const ArgList &Args,
1808 ArgStringList &CmdArgs) const {
1809 // Select the ABI to use.
1810 const char *ABIName = nullptr;
1811 if (getToolChain().getTriple().isOSLinux())
1812 switch (getToolChain().getArch()) {
1813 case llvm::Triple::ppc64: {
1814 // When targeting a processor that supports QPX, or if QPX is
1815 // specifically enabled, default to using the ABI that supports QPX (so
1816 // long as it is not specifically disabled).
1817 bool HasQPX = false;
1818 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1819 HasQPX = A->getValue() == StringRef("a2q");
1820 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1821 if (HasQPX) {
1822 ABIName = "elfv1-qpx";
1823 break;
1824 }
1825
1826 ABIName = "elfv1";
1827 break;
1828 }
1829 case llvm::Triple::ppc64le:
1830 ABIName = "elfv2";
1831 break;
1832 default:
1833 break;
1834 }
1835
Fangrui Song6bd02a42019-07-15 07:25:11 +00001836 bool IEEELongDouble = false;
1837 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1838 StringRef V = A->getValue();
1839 if (V == "ieeelongdouble")
1840 IEEELongDouble = true;
1841 else if (V == "ibmlongdouble")
1842 IEEELongDouble = false;
1843 else if (V != "altivec")
1844 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1845 // the option if given as we don't have backend support for any targets
1846 // that don't use the altivec abi.
David L. Jonesf561aba2017-03-08 01:02:16 +00001847 ABIName = A->getValue();
Fangrui Song6bd02a42019-07-15 07:25:11 +00001848 }
1849 if (IEEELongDouble)
1850 CmdArgs.push_back("-mabi=ieeelongdouble");
David L. Jonesf561aba2017-03-08 01:02:16 +00001851
1852 ppc::FloatABI FloatABI =
1853 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1854
1855 if (FloatABI == ppc::FloatABI::Soft) {
1856 // Floating point operations and argument passing are soft.
1857 CmdArgs.push_back("-msoft-float");
1858 CmdArgs.push_back("-mfloat-abi");
1859 CmdArgs.push_back("soft");
1860 } else {
1861 // Floating point operations and argument passing are hard.
1862 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1863 CmdArgs.push_back("-mfloat-abi");
1864 CmdArgs.push_back("hard");
1865 }
1866
1867 if (ABIName) {
1868 CmdArgs.push_back("-target-abi");
1869 CmdArgs.push_back(ABIName);
1870 }
1871}
1872
Alex Bradbury71f45452018-01-11 13:36:56 +00001873void Clang::AddRISCVTargetArgs(const ArgList &Args,
1874 ArgStringList &CmdArgs) const {
Alex Bradbury71f45452018-01-11 13:36:56 +00001875 const llvm::Triple &Triple = getToolChain().getTriple();
Roger Ferrer Ibanez371bdc92019-08-07 07:08:00 +00001876 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
Alex Bradbury71f45452018-01-11 13:36:56 +00001877
1878 CmdArgs.push_back("-target-abi");
Roger Ferrer Ibanez371bdc92019-08-07 07:08:00 +00001879 CmdArgs.push_back(ABIName.data());
Alex Bradbury71f45452018-01-11 13:36:56 +00001880}
1881
David L. Jonesf561aba2017-03-08 01:02:16 +00001882void Clang::AddSparcTargetArgs(const ArgList &Args,
1883 ArgStringList &CmdArgs) const {
1884 sparc::FloatABI FloatABI =
1885 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1886
1887 if (FloatABI == sparc::FloatABI::Soft) {
1888 // Floating point operations and argument passing are soft.
1889 CmdArgs.push_back("-msoft-float");
1890 CmdArgs.push_back("-mfloat-abi");
1891 CmdArgs.push_back("soft");
1892 } else {
1893 // Floating point operations and argument passing are hard.
1894 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1895 CmdArgs.push_back("-mfloat-abi");
1896 CmdArgs.push_back("hard");
1897 }
1898}
1899
1900void Clang::AddSystemZTargetArgs(const ArgList &Args,
1901 ArgStringList &CmdArgs) const {
1902 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1903 CmdArgs.push_back("-mbackchain");
1904}
1905
1906void Clang::AddX86TargetArgs(const ArgList &Args,
1907 ArgStringList &CmdArgs) const {
1908 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1909 Args.hasArg(options::OPT_mkernel) ||
1910 Args.hasArg(options::OPT_fapple_kext))
1911 CmdArgs.push_back("-disable-red-zone");
1912
Kristina Brooks7f569b72018-10-18 14:07:02 +00001913 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1914 options::OPT_mno_tls_direct_seg_refs, true))
1915 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1916
David L. Jonesf561aba2017-03-08 01:02:16 +00001917 // Default to avoid implicit floating-point for kernel/kext code, but allow
1918 // that to be overridden with -mno-soft-float.
1919 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1920 Args.hasArg(options::OPT_fapple_kext));
1921 if (Arg *A = Args.getLastArg(
1922 options::OPT_msoft_float, options::OPT_mno_soft_float,
1923 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1924 const Option &O = A->getOption();
1925 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1926 O.matches(options::OPT_msoft_float));
1927 }
1928 if (NoImplicitFloat)
1929 CmdArgs.push_back("-no-implicit-float");
1930
1931 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1932 StringRef Value = A->getValue();
1933 if (Value == "intel" || Value == "att") {
1934 CmdArgs.push_back("-mllvm");
1935 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1936 } else {
1937 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1938 << A->getOption().getName() << Value;
1939 }
Nico Webere3712cf2018-01-17 13:34:20 +00001940 } else if (getToolChain().getDriver().IsCLMode()) {
1941 CmdArgs.push_back("-mllvm");
1942 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001943 }
1944
1945 // Set flags to support MCU ABI.
1946 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1947 CmdArgs.push_back("-mfloat-abi");
1948 CmdArgs.push_back("soft");
1949 CmdArgs.push_back("-mstack-alignment=4");
1950 }
1951}
1952
1953void Clang::AddHexagonTargetArgs(const ArgList &Args,
1954 ArgStringList &CmdArgs) const {
1955 CmdArgs.push_back("-mqdsp6-compat");
1956 CmdArgs.push_back("-Wreturn-type");
1957
1958 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001959 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001960 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1961 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001962 }
1963
1964 if (!Args.hasArg(options::OPT_fno_short_enums))
1965 CmdArgs.push_back("-fshort-enums");
1966 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1967 CmdArgs.push_back("-mllvm");
1968 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1969 }
1970 CmdArgs.push_back("-mllvm");
1971 CmdArgs.push_back("-machine-sink-split=0");
1972}
1973
1974void Clang::AddLanaiTargetArgs(const ArgList &Args,
1975 ArgStringList &CmdArgs) const {
1976 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1977 StringRef CPUName = A->getValue();
1978
1979 CmdArgs.push_back("-target-cpu");
1980 CmdArgs.push_back(Args.MakeArgString(CPUName));
1981 }
1982 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1983 StringRef Value = A->getValue();
1984 // Only support mregparm=4 to support old usage. Report error for all other
1985 // cases.
1986 int Mregparm;
1987 if (Value.getAsInteger(10, Mregparm)) {
1988 if (Mregparm != 4) {
1989 getToolChain().getDriver().Diag(
1990 diag::err_drv_unsupported_option_argument)
1991 << A->getOption().getName() << Value;
1992 }
1993 }
1994 }
1995}
1996
1997void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1998 ArgStringList &CmdArgs) const {
1999 // Default to "hidden" visibility.
2000 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2001 options::OPT_fvisibility_ms_compat)) {
2002 CmdArgs.push_back("-fvisibility");
2003 CmdArgs.push_back("hidden");
2004 }
2005}
2006
2007void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2008 StringRef Target, const InputInfo &Output,
2009 const InputInfo &Input, const ArgList &Args) const {
2010 // If this is a dry run, do not create the compilation database file.
2011 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2012 return;
2013
2014 using llvm::yaml::escape;
2015 const Driver &D = getToolChain().getDriver();
2016
2017 if (!CompilationDatabase) {
2018 std::error_code EC;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002019 auto File = std::make_unique<llvm::raw_fd_ostream>(Filename, EC,
Fangrui Songd9b948b2019-08-05 05:43:48 +00002020 llvm::sys::fs::OF_Text);
David L. Jonesf561aba2017-03-08 01:02:16 +00002021 if (EC) {
2022 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2023 << EC.message();
2024 return;
2025 }
2026 CompilationDatabase = std::move(File);
2027 }
2028 auto &CDB = *CompilationDatabase;
Hans Wennborg999f8a72019-09-05 08:43:00 +00002029 SmallString<128> Buf;
Hans Wennborg36234572019-09-27 08:14:45 +00002030 if (llvm::sys::fs::current_path(Buf))
Hans Wennborg999f8a72019-09-05 08:43:00 +00002031 Buf = ".";
2032 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
David L. Jonesf561aba2017-03-08 01:02:16 +00002033 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2034 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2035 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2036 Buf = "-x";
2037 Buf += types::getTypeName(Input.getType());
2038 CDB << ", \"" << escape(Buf) << "\"";
2039 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2040 Buf = "--sysroot=";
2041 Buf += D.SysRoot;
2042 CDB << ", \"" << escape(Buf) << "\"";
2043 }
2044 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2045 for (auto &A: Args) {
2046 auto &O = A->getOption();
2047 // Skip language selection, which is positional.
2048 if (O.getID() == options::OPT_x)
2049 continue;
2050 // Skip writing dependency output and the compilation database itself.
2051 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2052 continue;
Alex Lorenz8679ef42019-08-26 17:59:41 +00002053 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2054 continue;
David L. Jonesf561aba2017-03-08 01:02:16 +00002055 // Skip inputs.
2056 if (O.getKind() == Option::InputClass)
2057 continue;
2058 // All other arguments are quoted and appended.
2059 ArgStringList ASL;
2060 A->render(Args, ASL);
2061 for (auto &it: ASL)
2062 CDB << ", \"" << escape(it) << "\"";
2063 }
2064 Buf = "--target=";
2065 Buf += Target;
2066 CDB << ", \"" << escape(Buf) << "\"]},\n";
2067}
2068
Alex Lorenz8679ef42019-08-26 17:59:41 +00002069void Clang::DumpCompilationDatabaseFragmentToDir(
2070 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2071 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2072 // If this is a dry run, do not create the compilation database file.
2073 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2074 return;
2075
2076 if (CompilationDatabase)
2077 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2078
2079 SmallString<256> Path = Dir;
2080 const auto &Driver = C.getDriver();
2081 Driver.getVFS().makeAbsolute(Path);
2082 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2083 if (Err) {
2084 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2085 return;
2086 }
2087
2088 llvm::sys::path::append(
2089 Path,
2090 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2091 int FD;
2092 SmallString<256> TempPath;
2093 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath);
2094 if (Err) {
2095 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2096 return;
2097 }
2098 CompilationDatabase =
2099 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2100 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2101}
2102
David L. Jonesf561aba2017-03-08 01:02:16 +00002103static void CollectArgsForIntegratedAssembler(Compilation &C,
2104 const ArgList &Args,
2105 ArgStringList &CmdArgs,
2106 const Driver &D) {
2107 if (UseRelaxAll(C, Args))
2108 CmdArgs.push_back("-mrelax-all");
2109
2110 // Only default to -mincremental-linker-compatible if we think we are
2111 // targeting the MSVC linker.
2112 bool DefaultIncrementalLinkerCompatible =
2113 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2114 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2115 options::OPT_mno_incremental_linker_compatible,
2116 DefaultIncrementalLinkerCompatible))
2117 CmdArgs.push_back("-mincremental-linker-compatible");
2118
2119 switch (C.getDefaultToolChain().getArch()) {
2120 case llvm::Triple::arm:
2121 case llvm::Triple::armeb:
2122 case llvm::Triple::thumb:
2123 case llvm::Triple::thumbeb:
2124 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2125 StringRef Value = A->getValue();
2126 if (Value == "always" || Value == "never" || Value == "arm" ||
2127 Value == "thumb") {
2128 CmdArgs.push_back("-mllvm");
2129 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2130 } else {
2131 D.Diag(diag::err_drv_unsupported_option_argument)
2132 << A->getOption().getName() << Value;
2133 }
2134 }
2135 break;
2136 default:
2137 break;
2138 }
2139
Nico Weberb28ffd82019-07-27 01:13:00 +00002140 // If you add more args here, also add them to the block below that
2141 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2142
David L. Jonesf561aba2017-03-08 01:02:16 +00002143 // When passing -I arguments to the assembler we sometimes need to
2144 // unconditionally take the next argument. For example, when parsing
2145 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2146 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2147 // arg after parsing the '-I' arg.
2148 bool TakeNextArg = false;
2149
Petr Hosek5668d832017-11-22 01:38:31 +00002150 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
Dan Albert2715b282019-03-28 18:08:28 +00002151 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00002152 const char *MipsTargetFeature = nullptr;
2153 for (const Arg *A :
2154 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2155 A->claim();
2156
2157 for (StringRef Value : A->getValues()) {
2158 if (TakeNextArg) {
2159 CmdArgs.push_back(Value.data());
2160 TakeNextArg = false;
2161 continue;
2162 }
2163
2164 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2165 Value == "-mbig-obj")
2166 continue; // LLVM handles bigobj automatically
2167
2168 switch (C.getDefaultToolChain().getArch()) {
2169 default:
2170 break;
Peter Smith3947cb32017-11-20 13:43:55 +00002171 case llvm::Triple::thumb:
2172 case llvm::Triple::thumbeb:
2173 case llvm::Triple::arm:
2174 case llvm::Triple::armeb:
2175 if (Value == "-mthumb")
2176 // -mthumb has already been processed in ComputeLLVMTriple()
2177 // recognize but skip over here.
2178 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00002179 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00002180 case llvm::Triple::mips:
2181 case llvm::Triple::mipsel:
2182 case llvm::Triple::mips64:
2183 case llvm::Triple::mips64el:
2184 if (Value == "--trap") {
2185 CmdArgs.push_back("-target-feature");
2186 CmdArgs.push_back("+use-tcc-in-div");
2187 continue;
2188 }
2189 if (Value == "--break") {
2190 CmdArgs.push_back("-target-feature");
2191 CmdArgs.push_back("-use-tcc-in-div");
2192 continue;
2193 }
2194 if (Value.startswith("-msoft-float")) {
2195 CmdArgs.push_back("-target-feature");
2196 CmdArgs.push_back("+soft-float");
2197 continue;
2198 }
2199 if (Value.startswith("-mhard-float")) {
2200 CmdArgs.push_back("-target-feature");
2201 CmdArgs.push_back("-soft-float");
2202 continue;
2203 }
2204
2205 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2206 .Case("-mips1", "+mips1")
2207 .Case("-mips2", "+mips2")
2208 .Case("-mips3", "+mips3")
2209 .Case("-mips4", "+mips4")
2210 .Case("-mips5", "+mips5")
2211 .Case("-mips32", "+mips32")
2212 .Case("-mips32r2", "+mips32r2")
2213 .Case("-mips32r3", "+mips32r3")
2214 .Case("-mips32r5", "+mips32r5")
2215 .Case("-mips32r6", "+mips32r6")
2216 .Case("-mips64", "+mips64")
2217 .Case("-mips64r2", "+mips64r2")
2218 .Case("-mips64r3", "+mips64r3")
2219 .Case("-mips64r5", "+mips64r5")
2220 .Case("-mips64r6", "+mips64r6")
2221 .Default(nullptr);
2222 if (MipsTargetFeature)
2223 continue;
2224 }
2225
2226 if (Value == "-force_cpusubtype_ALL") {
2227 // Do nothing, this is the default and we don't support anything else.
2228 } else if (Value == "-L") {
2229 CmdArgs.push_back("-msave-temp-labels");
2230 } else if (Value == "--fatal-warnings") {
2231 CmdArgs.push_back("-massembler-fatal-warnings");
Brian Cain7b953b62019-08-08 19:19:20 +00002232 } else if (Value == "--no-warn") {
2233 CmdArgs.push_back("-massembler-no-warn");
David L. Jonesf561aba2017-03-08 01:02:16 +00002234 } else if (Value == "--noexecstack") {
Dan Albert2715b282019-03-28 18:08:28 +00002235 UseNoExecStack = true;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002236 } else if (Value.startswith("-compress-debug-sections") ||
2237 Value.startswith("--compress-debug-sections") ||
2238 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002239 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002240 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002241 } else if (Value == "-mrelax-relocations=yes" ||
2242 Value == "--mrelax-relocations=yes") {
2243 UseRelaxRelocations = true;
2244 } else if (Value == "-mrelax-relocations=no" ||
2245 Value == "--mrelax-relocations=no") {
2246 UseRelaxRelocations = false;
2247 } else if (Value.startswith("-I")) {
2248 CmdArgs.push_back(Value.data());
2249 // We need to consume the next argument if the current arg is a plain
2250 // -I. The next arg will be the include directory.
2251 if (Value == "-I")
2252 TakeNextArg = true;
2253 } else if (Value.startswith("-gdwarf-")) {
2254 // "-gdwarf-N" options are not cc1as options.
2255 unsigned DwarfVersion = DwarfVersionNum(Value);
2256 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2257 CmdArgs.push_back(Value.data());
2258 } else {
2259 RenderDebugEnablingArgs(Args, CmdArgs,
2260 codegenoptions::LimitedDebugInfo,
2261 DwarfVersion, llvm::DebuggerKind::Default);
2262 }
2263 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2264 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2265 // Do nothing, we'll validate it later.
2266 } else if (Value == "-defsym") {
2267 if (A->getNumValues() != 2) {
2268 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2269 break;
2270 }
2271 const char *S = A->getValue(1);
2272 auto Pair = StringRef(S).split('=');
2273 auto Sym = Pair.first;
2274 auto SVal = Pair.second;
2275
2276 if (Sym.empty() || SVal.empty()) {
2277 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2278 break;
2279 }
2280 int64_t IVal;
2281 if (SVal.getAsInteger(0, IVal)) {
2282 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2283 break;
2284 }
2285 CmdArgs.push_back(Value.data());
2286 TakeNextArg = true;
Nico Weber4c9fa4a2018-12-06 18:50:39 +00002287 } else if (Value == "-fdebug-compilation-dir") {
2288 CmdArgs.push_back("-fdebug-compilation-dir");
2289 TakeNextArg = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002290 } else {
2291 D.Diag(diag::err_drv_unsupported_option_argument)
2292 << A->getOption().getName() << Value;
2293 }
2294 }
2295 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002296 if (UseRelaxRelocations)
2297 CmdArgs.push_back("--mrelax-relocations");
Dan Albert2715b282019-03-28 18:08:28 +00002298 if (UseNoExecStack)
2299 CmdArgs.push_back("-mnoexecstack");
David L. Jonesf561aba2017-03-08 01:02:16 +00002300 if (MipsTargetFeature != nullptr) {
2301 CmdArgs.push_back("-target-feature");
2302 CmdArgs.push_back(MipsTargetFeature);
2303 }
Steven Wu098742f2018-12-12 17:30:16 +00002304
2305 // forward -fembed-bitcode to assmebler
2306 if (C.getDriver().embedBitcodeEnabled() ||
2307 C.getDriver().embedBitcodeMarkerOnly())
2308 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00002309}
2310
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002311static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2312 bool OFastEnabled, const ArgList &Args,
2313 ArgStringList &CmdArgs) {
2314 // Handle various floating point optimization flags, mapping them to the
2315 // appropriate LLVM code generation flags. This is complicated by several
2316 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002317 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002318 // LLVM flags based on the final state.
2319 bool HonorINFs = true;
2320 bool HonorNaNs = true;
2321 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2322 bool MathErrno = TC.IsMathErrnoDefault();
2323 bool AssociativeMath = false;
2324 bool ReciprocalMath = false;
2325 bool SignedZeros = true;
2326 bool TrappingMath = true;
2327 StringRef DenormalFPMath = "";
2328 StringRef FPContract = "";
2329
Saleem Abdulrasool258e4f62018-09-18 21:12:39 +00002330 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2331 CmdArgs.push_back("-mlimit-float-precision");
2332 CmdArgs.push_back(A->getValue());
2333 }
2334
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002335 for (const Arg *A : Args) {
2336 switch (A->getOption().getID()) {
2337 // If this isn't an FP option skip the claim below
2338 default: continue;
2339
2340 // Options controlling individual features
2341 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2342 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2343 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2344 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2345 case options::OPT_fmath_errno: MathErrno = true; break;
2346 case options::OPT_fno_math_errno: MathErrno = false; break;
2347 case options::OPT_fassociative_math: AssociativeMath = true; break;
2348 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2349 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2350 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2351 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2352 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2353 case options::OPT_ftrapping_math: TrappingMath = true; break;
2354 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2355
2356 case options::OPT_fdenormal_fp_math_EQ:
2357 DenormalFPMath = A->getValue();
2358 break;
2359
2360 // Validate and pass through -fp-contract option.
2361 case options::OPT_ffp_contract: {
2362 StringRef Val = A->getValue();
2363 if (Val == "fast" || Val == "on" || Val == "off")
2364 FPContract = Val;
2365 else
2366 D.Diag(diag::err_drv_unsupported_option_argument)
2367 << A->getOption().getName() << Val;
2368 break;
2369 }
2370
2371 case options::OPT_ffinite_math_only:
2372 HonorINFs = false;
2373 HonorNaNs = false;
2374 break;
2375 case options::OPT_fno_finite_math_only:
2376 HonorINFs = true;
2377 HonorNaNs = true;
2378 break;
2379
2380 case options::OPT_funsafe_math_optimizations:
2381 AssociativeMath = true;
2382 ReciprocalMath = true;
2383 SignedZeros = false;
2384 TrappingMath = false;
2385 break;
2386 case options::OPT_fno_unsafe_math_optimizations:
2387 AssociativeMath = false;
2388 ReciprocalMath = false;
2389 SignedZeros = true;
2390 TrappingMath = true;
2391 // -fno_unsafe_math_optimizations restores default denormal handling
2392 DenormalFPMath = "";
2393 break;
2394
2395 case options::OPT_Ofast:
2396 // If -Ofast is the optimization level, then -ffast-math should be enabled
2397 if (!OFastEnabled)
2398 continue;
2399 LLVM_FALLTHROUGH;
2400 case options::OPT_ffast_math:
2401 HonorINFs = false;
2402 HonorNaNs = false;
2403 MathErrno = false;
2404 AssociativeMath = true;
2405 ReciprocalMath = true;
2406 SignedZeros = false;
2407 TrappingMath = false;
2408 // If fast-math is set then set the fp-contract mode to fast.
2409 FPContract = "fast";
2410 break;
2411 case options::OPT_fno_fast_math:
2412 HonorINFs = true;
2413 HonorNaNs = true;
2414 // Turning on -ffast-math (with either flag) removes the need for
2415 // MathErrno. However, turning *off* -ffast-math merely restores the
2416 // toolchain default (which may be false).
2417 MathErrno = TC.IsMathErrnoDefault();
2418 AssociativeMath = false;
2419 ReciprocalMath = false;
2420 SignedZeros = true;
2421 TrappingMath = true;
2422 // -fno_fast_math restores default denormal and fpcontract handling
2423 DenormalFPMath = "";
2424 FPContract = "";
2425 break;
2426 }
2427
2428 // If we handled this option claim it
2429 A->claim();
2430 }
2431
2432 if (!HonorINFs)
2433 CmdArgs.push_back("-menable-no-infs");
2434
2435 if (!HonorNaNs)
2436 CmdArgs.push_back("-menable-no-nans");
2437
2438 if (MathErrno)
2439 CmdArgs.push_back("-fmath-errno");
2440
2441 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2442 !TrappingMath)
2443 CmdArgs.push_back("-menable-unsafe-fp-math");
2444
2445 if (!SignedZeros)
2446 CmdArgs.push_back("-fno-signed-zeros");
2447
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002448 if (AssociativeMath && !SignedZeros && !TrappingMath)
2449 CmdArgs.push_back("-mreassociate");
2450
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002451 if (ReciprocalMath)
2452 CmdArgs.push_back("-freciprocal-math");
2453
2454 if (!TrappingMath)
2455 CmdArgs.push_back("-fno-trapping-math");
2456
2457 if (!DenormalFPMath.empty())
2458 CmdArgs.push_back(
2459 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2460
2461 if (!FPContract.empty())
2462 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2463
2464 ParseMRecip(D, Args, CmdArgs);
2465
2466 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2467 // individual features enabled by -ffast-math instead of the option itself as
2468 // that's consistent with gcc's behaviour.
2469 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2470 ReciprocalMath && !SignedZeros && !TrappingMath)
2471 CmdArgs.push_back("-ffast-math");
2472
2473 // Handle __FINITE_MATH_ONLY__ similarly.
2474 if (!HonorINFs && !HonorNaNs)
2475 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002476
2477 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2478 CmdArgs.push_back("-mfpmath");
2479 CmdArgs.push_back(A->getValue());
2480 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002481
2482 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002483 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2484 options::OPT_fstrict_float_cast_overflow, false))
2485 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002486}
2487
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002488static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2489 const llvm::Triple &Triple,
2490 const InputInfo &Input) {
2491 // Enable region store model by default.
2492 CmdArgs.push_back("-analyzer-store=region");
2493
2494 // Treat blocks as analysis entry points.
2495 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2496
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002497 // Add default argument set.
2498 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2499 CmdArgs.push_back("-analyzer-checker=core");
2500 CmdArgs.push_back("-analyzer-checker=apiModeling");
2501
2502 if (!Triple.isWindowsMSVCEnvironment()) {
2503 CmdArgs.push_back("-analyzer-checker=unix");
2504 } else {
2505 // Enable "unix" checkers that also work on Windows.
2506 CmdArgs.push_back("-analyzer-checker=unix.API");
2507 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2508 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2509 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2510 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2511 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2512 }
2513
2514 // Disable some unix checkers for PS4.
2515 if (Triple.isPS4CPU()) {
2516 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2517 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2518 }
2519
2520 if (Triple.isOSDarwin())
2521 CmdArgs.push_back("-analyzer-checker=osx");
2522
2523 CmdArgs.push_back("-analyzer-checker=deadcode");
2524
2525 if (types::isCXX(Input.getType()))
2526 CmdArgs.push_back("-analyzer-checker=cplusplus");
2527
2528 if (!Triple.isPS4CPU()) {
2529 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2530 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2531 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2532 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2533 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2534 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2535 }
2536
2537 // Default nullability checks.
2538 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2539 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2540 }
2541
2542 // Set the output format. The default is plist, for (lame) historical reasons.
2543 CmdArgs.push_back("-analyzer-output");
2544 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2545 CmdArgs.push_back(A->getValue());
2546 else
2547 CmdArgs.push_back("plist");
2548
2549 // Disable the presentation of standard compiler warnings when using
2550 // --analyze. We only want to show static analyzer diagnostics or frontend
2551 // errors.
2552 CmdArgs.push_back("-w");
2553
2554 // Add -Xanalyzer arguments when running as analyzer.
2555 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2556}
2557
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002558static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002559 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002560 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2561
2562 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2563 // doesn't even have a stack!
2564 if (EffectiveTriple.isNVPTX())
2565 return;
2566
2567 // -stack-protector=0 is default.
2568 unsigned StackProtectorLevel = 0;
2569 unsigned DefaultStackProtectorLevel =
2570 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2571
2572 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2573 options::OPT_fstack_protector_all,
2574 options::OPT_fstack_protector_strong,
2575 options::OPT_fstack_protector)) {
2576 if (A->getOption().matches(options::OPT_fstack_protector))
2577 StackProtectorLevel =
2578 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2579 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2580 StackProtectorLevel = LangOptions::SSPStrong;
2581 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2582 StackProtectorLevel = LangOptions::SSPReq;
2583 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002584 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002585 }
2586
2587 if (StackProtectorLevel) {
2588 CmdArgs.push_back("-stack-protector");
2589 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2590 }
2591
2592 // --param ssp-buffer-size=
2593 for (const Arg *A : Args.filtered(options::OPT__param)) {
2594 StringRef Str(A->getValue());
2595 if (Str.startswith("ssp-buffer-size=")) {
2596 if (StackProtectorLevel) {
2597 CmdArgs.push_back("-stack-protector-buffer-size");
2598 // FIXME: Verify the argument is a valid integer.
2599 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2600 }
2601 A->claim();
2602 }
2603 }
2604}
2605
JF Bastien14daa202018-12-18 05:12:21 +00002606static void RenderTrivialAutoVarInitOptions(const Driver &D,
2607 const ToolChain &TC,
2608 const ArgList &Args,
2609 ArgStringList &CmdArgs) {
2610 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2611 StringRef TrivialAutoVarInit = "";
2612
2613 for (const Arg *A : Args) {
2614 switch (A->getOption().getID()) {
2615 default:
2616 continue;
2617 case options::OPT_ftrivial_auto_var_init: {
2618 A->claim();
2619 StringRef Val = A->getValue();
2620 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2621 TrivialAutoVarInit = Val;
2622 else
2623 D.Diag(diag::err_drv_unsupported_option_argument)
2624 << A->getOption().getName() << Val;
2625 break;
2626 }
2627 }
2628 }
2629
2630 if (TrivialAutoVarInit.empty())
2631 switch (DefaultTrivialAutoVarInit) {
2632 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2633 break;
2634 case LangOptions::TrivialAutoVarInitKind::Pattern:
2635 TrivialAutoVarInit = "pattern";
2636 break;
2637 case LangOptions::TrivialAutoVarInitKind::Zero:
2638 TrivialAutoVarInit = "zero";
2639 break;
2640 }
2641
2642 if (!TrivialAutoVarInit.empty()) {
2643 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2644 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2645 CmdArgs.push_back(
2646 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2647 }
2648}
2649
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002650static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2651 const unsigned ForwardedArguments[] = {
2652 options::OPT_cl_opt_disable,
2653 options::OPT_cl_strict_aliasing,
2654 options::OPT_cl_single_precision_constant,
2655 options::OPT_cl_finite_math_only,
2656 options::OPT_cl_kernel_arg_info,
2657 options::OPT_cl_unsafe_math_optimizations,
2658 options::OPT_cl_fast_relaxed_math,
2659 options::OPT_cl_mad_enable,
2660 options::OPT_cl_no_signed_zeros,
2661 options::OPT_cl_denorms_are_zero,
2662 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002663 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002664 };
2665
2666 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2667 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2668 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2669 }
2670
2671 for (const auto &Arg : ForwardedArguments)
2672 if (const auto *A = Args.getLastArg(Arg))
2673 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2674}
2675
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002676static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2677 ArgStringList &CmdArgs) {
2678 bool ARCMTEnabled = false;
2679 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2680 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2681 options::OPT_ccc_arcmt_modify,
2682 options::OPT_ccc_arcmt_migrate)) {
2683 ARCMTEnabled = true;
2684 switch (A->getOption().getID()) {
2685 default: llvm_unreachable("missed a case");
2686 case options::OPT_ccc_arcmt_check:
2687 CmdArgs.push_back("-arcmt-check");
2688 break;
2689 case options::OPT_ccc_arcmt_modify:
2690 CmdArgs.push_back("-arcmt-modify");
2691 break;
2692 case options::OPT_ccc_arcmt_migrate:
2693 CmdArgs.push_back("-arcmt-migrate");
2694 CmdArgs.push_back("-mt-migrate-directory");
2695 CmdArgs.push_back(A->getValue());
2696
2697 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2698 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2699 break;
2700 }
2701 }
2702 } else {
2703 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2704 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2705 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2706 }
2707
2708 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2709 if (ARCMTEnabled)
2710 D.Diag(diag::err_drv_argument_not_allowed_with)
2711 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2712
2713 CmdArgs.push_back("-mt-migrate-directory");
2714 CmdArgs.push_back(A->getValue());
2715
2716 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2717 options::OPT_objcmt_migrate_subscripting,
2718 options::OPT_objcmt_migrate_property)) {
2719 // None specified, means enable them all.
2720 CmdArgs.push_back("-objcmt-migrate-literals");
2721 CmdArgs.push_back("-objcmt-migrate-subscripting");
2722 CmdArgs.push_back("-objcmt-migrate-property");
2723 } else {
2724 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2725 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2726 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2727 }
2728 } else {
2729 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2730 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2731 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2732 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2733 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2734 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2735 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2736 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2737 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2738 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2739 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2740 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2741 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2742 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2743 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2744 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2745 }
2746}
2747
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002748static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2749 const ArgList &Args, ArgStringList &CmdArgs) {
2750 // -fbuiltin is default unless -mkernel is used.
2751 bool UseBuiltins =
2752 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2753 !Args.hasArg(options::OPT_mkernel));
2754 if (!UseBuiltins)
2755 CmdArgs.push_back("-fno-builtin");
2756
2757 // -ffreestanding implies -fno-builtin.
2758 if (Args.hasArg(options::OPT_ffreestanding))
2759 UseBuiltins = false;
2760
2761 // Process the -fno-builtin-* options.
2762 for (const auto &Arg : Args) {
2763 const Option &O = Arg->getOption();
2764 if (!O.matches(options::OPT_fno_builtin_))
2765 continue;
2766
2767 Arg->claim();
2768
2769 // If -fno-builtin is specified, then there's no need to pass the option to
2770 // the frontend.
2771 if (!UseBuiltins)
2772 continue;
2773
2774 StringRef FuncName = Arg->getValue();
2775 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2776 }
2777
2778 // le32-specific flags:
2779 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2780 // by default.
2781 if (TC.getArch() == llvm::Triple::le32)
2782 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002783}
2784
Adrian Prantl70599032018-02-09 18:43:10 +00002785void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2786 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2787 llvm::sys::path::append(Result, "org.llvm.clang.");
2788 appendUserToPath(Result);
2789 llvm::sys::path::append(Result, "ModuleCache");
2790}
2791
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002792static void RenderModulesOptions(Compilation &C, const Driver &D,
2793 const ArgList &Args, const InputInfo &Input,
2794 const InputInfo &Output,
2795 ArgStringList &CmdArgs, bool &HaveModules) {
2796 // -fmodules enables the use of precompiled modules (off by default).
2797 // Users can pass -fno-cxx-modules to turn off modules support for
2798 // C++/Objective-C++ programs.
2799 bool HaveClangModules = false;
2800 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2801 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2802 options::OPT_fno_cxx_modules, true);
2803 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2804 CmdArgs.push_back("-fmodules");
2805 HaveClangModules = true;
2806 }
2807 }
2808
Richard Smithb1b580e2019-04-14 11:11:37 +00002809 HaveModules |= HaveClangModules;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002810 if (Args.hasArg(options::OPT_fmodules_ts)) {
2811 CmdArgs.push_back("-fmodules-ts");
2812 HaveModules = true;
2813 }
2814
2815 // -fmodule-maps enables implicit reading of module map files. By default,
2816 // this is enabled if we are using Clang's flavor of precompiled modules.
2817 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2818 options::OPT_fno_implicit_module_maps, HaveClangModules))
2819 CmdArgs.push_back("-fimplicit-module-maps");
2820
2821 // -fmodules-decluse checks that modules used are declared so (off by default)
2822 if (Args.hasFlag(options::OPT_fmodules_decluse,
2823 options::OPT_fno_modules_decluse, false))
2824 CmdArgs.push_back("-fmodules-decluse");
2825
2826 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2827 // all #included headers are part of modules.
2828 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2829 options::OPT_fno_modules_strict_decluse, false))
2830 CmdArgs.push_back("-fmodules-strict-decluse");
2831
2832 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002833 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002834 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2835 options::OPT_fno_implicit_modules, HaveClangModules)) {
2836 if (HaveModules)
2837 CmdArgs.push_back("-fno-implicit-modules");
2838 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002839 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002840 // -fmodule-cache-path specifies where our implicitly-built module files
2841 // should be written.
2842 SmallString<128> Path;
2843 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2844 Path = A->getValue();
2845
2846 if (C.isForDiagnostics()) {
2847 // When generating crash reports, we want to emit the modules along with
2848 // the reproduction sources, so we ignore any provided module path.
2849 Path = Output.getFilename();
2850 llvm::sys::path::replace_extension(Path, ".cache");
2851 llvm::sys::path::append(Path, "modules");
2852 } else if (Path.empty()) {
2853 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002854 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002855 }
2856
2857 const char Arg[] = "-fmodules-cache-path=";
2858 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2859 CmdArgs.push_back(Args.MakeArgString(Path));
2860 }
2861
2862 if (HaveModules) {
2863 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2864 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2865 CmdArgs.push_back(Args.MakeArgString(
2866 std::string("-fprebuilt-module-path=") + A->getValue()));
2867 A->claim();
2868 }
2869 }
2870
2871 // -fmodule-name specifies the module that is currently being built (or
2872 // used for header checking by -fmodule-maps).
2873 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2874
2875 // -fmodule-map-file can be used to specify files containing module
2876 // definitions.
2877 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2878
2879 // -fbuiltin-module-map can be used to load the clang
2880 // builtin headers modulemap file.
2881 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2882 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2883 llvm::sys::path::append(BuiltinModuleMap, "include");
2884 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2885 if (llvm::sys::fs::exists(BuiltinModuleMap))
2886 CmdArgs.push_back(
2887 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2888 }
2889
2890 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2891 // names to precompiled module files (the module is loaded only if used).
2892 // The -fmodule-file=<file> form can be used to unconditionally load
2893 // precompiled module files (whether used or not).
2894 if (HaveModules)
2895 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2896 else
2897 Args.ClaimAllArgs(options::OPT_fmodule_file);
2898
2899 // When building modules and generating crashdumps, we need to dump a module
2900 // dependency VFS alongside the output.
2901 if (HaveClangModules && C.isForDiagnostics()) {
2902 SmallString<128> VFSDir(Output.getFilename());
2903 llvm::sys::path::replace_extension(VFSDir, ".cache");
2904 // Add the cache directory as a temp so the crash diagnostics pick it up.
2905 C.addTempFile(Args.MakeArgString(VFSDir));
2906
2907 llvm::sys::path::append(VFSDir, "vfs");
2908 CmdArgs.push_back("-module-dependency-dir");
2909 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2910 }
2911
2912 if (HaveClangModules)
2913 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2914
2915 // Pass through all -fmodules-ignore-macro arguments.
2916 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2917 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2918 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2919
2920 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2921
2922 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2923 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2924 D.Diag(diag::err_drv_argument_not_allowed_with)
2925 << A->getAsString(Args) << "-fbuild-session-timestamp";
2926
2927 llvm::sys::fs::file_status Status;
2928 if (llvm::sys::fs::status(A->getValue(), Status))
2929 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2930 CmdArgs.push_back(
2931 Args.MakeArgString("-fbuild-session-timestamp=" +
2932 Twine((uint64_t)Status.getLastModificationTime()
2933 .time_since_epoch()
2934 .count())));
2935 }
2936
2937 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2938 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2939 options::OPT_fbuild_session_file))
2940 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2941
2942 Args.AddLastArg(CmdArgs,
2943 options::OPT_fmodules_validate_once_per_build_session);
2944 }
2945
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002946 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2947 options::OPT_fno_modules_validate_system_headers,
2948 ImplicitModules))
2949 CmdArgs.push_back("-fmodules-validate-system-headers");
2950
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002951 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2952}
2953
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002954static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2955 ArgStringList &CmdArgs) {
2956 // -fsigned-char is default.
2957 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2958 options::OPT_fno_signed_char,
2959 options::OPT_funsigned_char,
2960 options::OPT_fno_unsigned_char)) {
2961 if (A->getOption().matches(options::OPT_funsigned_char) ||
2962 A->getOption().matches(options::OPT_fno_signed_char)) {
2963 CmdArgs.push_back("-fno-signed-char");
2964 }
2965 } else if (!isSignedCharDefault(T)) {
2966 CmdArgs.push_back("-fno-signed-char");
2967 }
2968
Richard Smith28ddb912018-11-14 21:04:34 +00002969 // The default depends on the language standard.
Nico Weber908b6972019-06-26 17:51:47 +00002970 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
Richard Smith3a8244d2018-05-01 05:02:45 +00002971
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002972 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2973 options::OPT_fno_short_wchar)) {
2974 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2975 CmdArgs.push_back("-fwchar-type=short");
2976 CmdArgs.push_back("-fno-signed-wchar");
2977 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002978 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002979 CmdArgs.push_back("-fwchar-type=int");
Michal Gorny5a409d02018-12-20 13:09:30 +00002980 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2981 T.isOSOpenBSD()))
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002982 CmdArgs.push_back("-fno-signed-wchar");
2983 else
2984 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002985 }
2986 }
2987}
2988
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002989static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2990 const llvm::Triple &T, const ArgList &Args,
2991 ObjCRuntime &Runtime, bool InferCovariantReturns,
2992 const InputInfo &Input, ArgStringList &CmdArgs) {
2993 const llvm::Triple::ArchType Arch = TC.getArch();
2994
2995 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2996 // is the default. Except for deployment target of 10.5, next runtime is
2997 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2998 if (Runtime.isNonFragile()) {
2999 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3000 options::OPT_fno_objc_legacy_dispatch,
3001 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3002 if (TC.UseObjCMixedDispatch())
3003 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3004 else
3005 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3006 }
3007 }
3008
3009 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3010 // to do Array/Dictionary subscripting by default.
3011 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00003012 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3013 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3014
3015 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3016 // NOTE: This logic is duplicated in ToolChains.cpp.
3017 if (isObjCAutoRefCount(Args)) {
3018 TC.CheckObjCARC();
3019
3020 CmdArgs.push_back("-fobjc-arc");
3021
3022 // FIXME: It seems like this entire block, and several around it should be
3023 // wrapped in isObjC, but for now we just use it here as this is where it
3024 // was being used previously.
3025 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3026 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3027 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3028 else
3029 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3030 }
3031
3032 // Allow the user to enable full exceptions code emission.
3033 // We default off for Objective-C, on for Objective-C++.
3034 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3035 options::OPT_fno_objc_arc_exceptions,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003036 /*Default=*/types::isCXX(Input.getType())))
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00003037 CmdArgs.push_back("-fobjc-arc-exceptions");
3038 }
3039
3040 // Silence warning for full exception code emission options when explicitly
3041 // set to use no ARC.
3042 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3043 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3044 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3045 }
3046
Pete Coopere3886802018-12-08 05:13:50 +00003047 // Allow the user to control whether messages can be converted to runtime
3048 // functions.
3049 if (types::isObjC(Input.getType())) {
3050 auto *Arg = Args.getLastArg(
3051 options::OPT_fobjc_convert_messages_to_runtime_calls,
3052 options::OPT_fno_objc_convert_messages_to_runtime_calls);
3053 if (Arg &&
3054 Arg->getOption().matches(
3055 options::OPT_fno_objc_convert_messages_to_runtime_calls))
3056 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3057 }
3058
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00003059 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3060 // rewriter.
3061 if (InferCovariantReturns)
3062 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3063
3064 // Pass down -fobjc-weak or -fno-objc-weak if present.
3065 if (types::isObjC(Input.getType())) {
3066 auto WeakArg =
3067 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3068 if (!WeakArg) {
3069 // nothing to do
3070 } else if (!Runtime.allowsWeak()) {
3071 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3072 D.Diag(diag::err_objc_weak_unsupported);
3073 } else {
3074 WeakArg->render(Args, CmdArgs);
3075 }
3076 }
3077}
3078
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00003079static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3080 ArgStringList &CmdArgs) {
3081 bool CaretDefault = true;
3082 bool ColumnDefault = true;
3083
3084 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3085 options::OPT__SLASH_diagnostics_column,
3086 options::OPT__SLASH_diagnostics_caret)) {
3087 switch (A->getOption().getID()) {
3088 case options::OPT__SLASH_diagnostics_caret:
3089 CaretDefault = true;
3090 ColumnDefault = true;
3091 break;
3092 case options::OPT__SLASH_diagnostics_column:
3093 CaretDefault = false;
3094 ColumnDefault = true;
3095 break;
3096 case options::OPT__SLASH_diagnostics_classic:
3097 CaretDefault = false;
3098 ColumnDefault = false;
3099 break;
3100 }
3101 }
3102
3103 // -fcaret-diagnostics is default.
3104 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3105 options::OPT_fno_caret_diagnostics, CaretDefault))
3106 CmdArgs.push_back("-fno-caret-diagnostics");
3107
3108 // -fdiagnostics-fixit-info is default, only pass non-default.
3109 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3110 options::OPT_fno_diagnostics_fixit_info))
3111 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3112
3113 // Enable -fdiagnostics-show-option by default.
3114 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3115 options::OPT_fno_diagnostics_show_option))
3116 CmdArgs.push_back("-fdiagnostics-show-option");
3117
3118 if (const Arg *A =
3119 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3120 CmdArgs.push_back("-fdiagnostics-show-category");
3121 CmdArgs.push_back(A->getValue());
3122 }
3123
3124 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3125 options::OPT_fno_diagnostics_show_hotness, false))
3126 CmdArgs.push_back("-fdiagnostics-show-hotness");
3127
3128 if (const Arg *A =
3129 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3130 std::string Opt =
3131 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3132 CmdArgs.push_back(Args.MakeArgString(Opt));
3133 }
3134
3135 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3136 CmdArgs.push_back("-fdiagnostics-format");
3137 CmdArgs.push_back(A->getValue());
3138 }
3139
3140 if (const Arg *A = Args.getLastArg(
3141 options::OPT_fdiagnostics_show_note_include_stack,
3142 options::OPT_fno_diagnostics_show_note_include_stack)) {
3143 const Option &O = A->getOption();
3144 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3145 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3146 else
3147 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3148 }
3149
3150 // Color diagnostics are parsed by the driver directly from argv and later
3151 // re-parsed to construct this job; claim any possible color diagnostic here
3152 // to avoid warn_drv_unused_argument and diagnose bad
3153 // OPT_fdiagnostics_color_EQ values.
3154 for (const Arg *A : Args) {
3155 const Option &O = A->getOption();
3156 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3157 !O.matches(options::OPT_fdiagnostics_color) &&
3158 !O.matches(options::OPT_fno_color_diagnostics) &&
3159 !O.matches(options::OPT_fno_diagnostics_color) &&
3160 !O.matches(options::OPT_fdiagnostics_color_EQ))
3161 continue;
3162
3163 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3164 StringRef Value(A->getValue());
3165 if (Value != "always" && Value != "never" && Value != "auto")
3166 D.Diag(diag::err_drv_clang_unsupported)
3167 << ("-fdiagnostics-color=" + Value).str();
3168 }
3169 A->claim();
3170 }
3171
3172 if (D.getDiags().getDiagnosticOptions().ShowColors)
3173 CmdArgs.push_back("-fcolor-diagnostics");
3174
3175 if (Args.hasArg(options::OPT_fansi_escape_codes))
3176 CmdArgs.push_back("-fansi-escape-codes");
3177
3178 if (!Args.hasFlag(options::OPT_fshow_source_location,
3179 options::OPT_fno_show_source_location))
3180 CmdArgs.push_back("-fno-show-source-location");
3181
3182 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3183 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3184
3185 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3186 ColumnDefault))
3187 CmdArgs.push_back("-fno-show-column");
3188
3189 if (!Args.hasFlag(options::OPT_fspell_checking,
3190 options::OPT_fno_spell_checking))
3191 CmdArgs.push_back("-fno-spell-checking");
3192}
3193
George Rimar91829ee2018-11-14 09:22:16 +00003194enum class DwarfFissionKind { None, Split, Single };
3195
3196static DwarfFissionKind getDebugFissionKind(const Driver &D,
3197 const ArgList &Args, Arg *&Arg) {
3198 Arg =
3199 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3200 if (!Arg)
3201 return DwarfFissionKind::None;
3202
3203 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3204 return DwarfFissionKind::Split;
3205
3206 StringRef Value = Arg->getValue();
3207 if (Value == "split")
3208 return DwarfFissionKind::Split;
3209 if (Value == "single")
3210 return DwarfFissionKind::Single;
3211
3212 D.Diag(diag::err_drv_unsupported_option_argument)
3213 << Arg->getOption().getName() << Arg->getValue();
3214 return DwarfFissionKind::None;
3215}
3216
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003217static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3218 const llvm::Triple &T, const ArgList &Args,
3219 bool EmitCodeView, bool IsWindowsMSVC,
3220 ArgStringList &CmdArgs,
3221 codegenoptions::DebugInfoKind &DebugInfoKind,
George Rimar91829ee2018-11-14 09:22:16 +00003222 DwarfFissionKind &DwarfFission) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003223 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003224 options::OPT_fno_debug_info_for_profiling, false) &&
3225 checkDebugInfoOption(
3226 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003227 CmdArgs.push_back("-fdebug-info-for-profiling");
3228
3229 // The 'g' groups options involve a somewhat intricate sequence of decisions
3230 // about what to pass from the driver to the frontend, but by the time they
3231 // reach cc1 they've been factored into three well-defined orthogonal choices:
3232 // * what level of debug info to generate
3233 // * what dwarf version to write
3234 // * what debugger tuning to use
3235 // This avoids having to monkey around further in cc1 other than to disable
3236 // codeview if not running in a Windows environment. Perhaps even that
3237 // decision should be made in the driver as well though.
3238 unsigned DWARFVersion = 0;
3239 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3240
3241 bool SplitDWARFInlining =
3242 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3243 options::OPT_fno_split_dwarf_inlining, true);
3244
3245 Args.ClaimAllArgs(options::OPT_g_Group);
3246
George Rimar91829ee2018-11-14 09:22:16 +00003247 Arg* SplitDWARFArg;
3248 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003249
George Rimar91829ee2018-11-14 09:22:16 +00003250 if (DwarfFission != DwarfFissionKind::None &&
3251 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3252 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003253 SplitDWARFInlining = false;
3254 }
3255
Fangrui Songe3576b02019-04-17 01:46:27 +00003256 if (const Arg *A =
3257 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3258 options::OPT_gsplit_dwarf_EQ)) {
3259 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3260
3261 // If the last option explicitly specified a debug-info level, use it.
3262 if (checkDebugInfoOption(A, Args, D, TC) &&
3263 A->getOption().matches(options::OPT_gN_Group)) {
3264 DebugInfoKind = DebugLevelToInfoKind(*A);
3265 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3266 // complicated if you've disabled inline info in the skeleton CUs
3267 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3268 // line-tables-only, so let those compose naturally in that case.
3269 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3270 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3271 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3272 SplitDWARFInlining))
3273 DwarfFission = DwarfFissionKind::None;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003274 }
3275 }
3276
3277 // If a debugger tuning argument appeared, remember it.
3278 if (const Arg *A =
3279 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003280 if (checkDebugInfoOption(A, Args, D, TC)) {
3281 if (A->getOption().matches(options::OPT_glldb))
3282 DebuggerTuning = llvm::DebuggerKind::LLDB;
3283 else if (A->getOption().matches(options::OPT_gsce))
3284 DebuggerTuning = llvm::DebuggerKind::SCE;
3285 else
3286 DebuggerTuning = llvm::DebuggerKind::GDB;
3287 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003288 }
3289
3290 // If a -gdwarf argument appeared, remember it.
3291 if (const Arg *A =
3292 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3293 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003294 if (checkDebugInfoOption(A, Args, D, TC))
3295 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003296
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003297 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3298 if (checkDebugInfoOption(A, Args, D, TC))
3299 EmitCodeView = true;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003300 }
3301
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003302 // If the user asked for debug info but did not explicitly specify -gcodeview
3303 // or -gdwarf, ask the toolchain for the default format.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003304 if (!EmitCodeView && DWARFVersion == 0 &&
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003305 DebugInfoKind != codegenoptions::NoDebugInfo) {
3306 switch (TC.getDefaultDebugFormat()) {
3307 case codegenoptions::DIF_CodeView:
3308 EmitCodeView = true;
3309 break;
3310 case codegenoptions::DIF_DWARF:
3311 DWARFVersion = TC.GetDefaultDwarfVersion();
3312 break;
3313 }
3314 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003315
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003316 // -gline-directives-only supported only for the DWARF debug info.
3317 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3318 DebugInfoKind = codegenoptions::NoDebugInfo;
3319
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003320 // We ignore flag -gstrict-dwarf for now.
3321 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3322 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3323
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003324 // Column info is included by default for everything except SCE and
3325 // CodeView. Clang doesn't track end columns, just starting columns, which,
3326 // in theory, is fine for CodeView (and PDB). In practice, however, the
3327 // Microsoft debuggers don't handle missing end columns well, so it's better
3328 // not to include any column info.
3329 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3330 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003331 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003332 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003333 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003334 CmdArgs.push_back("-dwarf-column-info");
3335
3336 // FIXME: Move backend command line options to the module.
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003337 // If -gline-tables-only or -gline-directives-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003338 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3339 if (checkDebugInfoOption(A, Args, D, TC)) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003340 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3341 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003342 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3343 CmdArgs.push_back("-dwarf-ext-refs");
3344 CmdArgs.push_back("-fmodule-format=obj");
3345 }
3346 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003347
Aaron Puchertb207bae2019-06-26 21:36:35 +00003348 if (T.isOSBinFormatELF() && !SplitDWARFInlining)
3349 CmdArgs.push_back("-fno-split-dwarf-inlining");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003350
3351 // After we've dealt with all combinations of things that could
3352 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3353 // figure out if we need to "upgrade" it to standalone debug info.
3354 // We parse these two '-f' options whether or not they will be used,
3355 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
David Blaikieb068f922019-04-16 00:16:29 +00003356 bool NeedFullDebug = Args.hasFlag(
3357 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3358 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3359 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003360 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3361 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003362 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3363 DebugInfoKind = codegenoptions::FullDebugInfo;
3364
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003365 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3366 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003367 // Source embedding is a vendor extension to DWARF v5. By now we have
3368 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003369 // fallen back to the target default, so if this is still not at least 5
3370 // we emit an error.
3371 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003372 if (DWARFVersion < 5)
3373 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003374 << A->getAsString(Args) << "-gdwarf-5";
3375 else if (checkDebugInfoOption(A, Args, D, TC))
3376 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003377 }
3378
Reid Kleckner75557712018-11-16 18:47:41 +00003379 if (EmitCodeView) {
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003380 CmdArgs.push_back("-gcodeview");
3381
Reid Kleckner75557712018-11-16 18:47:41 +00003382 // Emit codeview type hashes if requested.
3383 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3384 options::OPT_gno_codeview_ghash, false)) {
3385 CmdArgs.push_back("-gcodeview-ghash");
3386 }
3387 }
3388
Alexey Bataevc92fc3c2018-12-12 14:52:27 +00003389 // Adjust the debug info kind for the given toolchain.
3390 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3391
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003392 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3393 DebuggerTuning);
3394
3395 // -fdebug-macro turns on macro debug info generation.
3396 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3397 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003398 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3399 D, TC))
3400 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003401
3402 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003403 const auto *PubnamesArg =
3404 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3405 options::OPT_gpubnames, options::OPT_gno_pubnames);
George Rimar91829ee2018-11-14 09:22:16 +00003406 if (DwarfFission != DwarfFissionKind::None ||
David Blaikie65864522018-08-20 20:14:08 +00003407 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3408 if (!PubnamesArg ||
3409 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3410 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3411 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3412 options::OPT_gpubnames)
3413 ? "-gpubnames"
3414 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003415
David Blaikie27692de2018-11-13 20:08:13 +00003416 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3417 options::OPT_fno_debug_ranges_base_address, false)) {
3418 CmdArgs.push_back("-fdebug-ranges-base-address");
3419 }
3420
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003421 // -gdwarf-aranges turns on the emission of the aranges section in the
3422 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003423 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003424 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3425 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3426 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3427 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003428 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003429 CmdArgs.push_back("-generate-arange-section");
3430 }
3431
3432 if (Args.hasFlag(options::OPT_fdebug_types_section,
3433 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003434 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003435 D.Diag(diag::err_drv_unsupported_opt_for_target)
3436 << Args.getLastArg(options::OPT_fdebug_types_section)
3437 ->getAsString(Args)
3438 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003439 } else if (checkDebugInfoOption(
3440 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3441 TC)) {
3442 CmdArgs.push_back("-mllvm");
3443 CmdArgs.push_back("-generate-type-units");
3444 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003445 }
3446
Paul Robinson1787f812017-09-28 18:37:02 +00003447 // Decide how to render forward declarations of template instantiations.
3448 // SCE wants full descriptions, others just get them in the name.
3449 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3450 CmdArgs.push_back("-debug-forward-template-params");
3451
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003452 // Do we need to explicitly import anonymous namespaces into the parent
3453 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003454 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3455 CmdArgs.push_back("-dwarf-explicit-import");
3456
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003457 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003458}
3459
David L. Jonesf561aba2017-03-08 01:02:16 +00003460void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3461 const InputInfo &Output, const InputInfoList &Inputs,
3462 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003463 const auto &TC = getToolChain();
3464 const llvm::Triple &RawTriple = TC.getTriple();
3465 const llvm::Triple &Triple = TC.getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003466 const std::string &TripleStr = Triple.getTriple();
3467
3468 bool KernelOrKext =
3469 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003470 const Driver &D = TC.getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00003471 ArgStringList CmdArgs;
3472
3473 // Check number of inputs for sanity. We need at least one input.
3474 assert(Inputs.size() >= 1 && "Must have at least one input.");
Yaxun Liu398612b2018-05-08 21:02:12 +00003475 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003476 // device-side compilations). OpenMP device jobs also take the host IR as a
Richard Smithcd35eff2018-09-15 01:21:16 +00003477 // second input. Module precompilation accepts a list of header files to
3478 // include as part of the module. All other jobs are expected to have exactly
3479 // one input.
David L. Jonesf561aba2017-03-08 01:02:16 +00003480 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003481 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003482 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Richard Smithcd35eff2018-09-15 01:21:16 +00003483 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3484
3485 // A header module compilation doesn't have a main input file, so invent a
3486 // fake one as a placeholder.
Richard Smithcd35eff2018-09-15 01:21:16 +00003487 const char *ModuleName = [&]{
3488 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3489 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3490 }();
Benjamin Kramer5904c412018-11-05 12:46:02 +00003491 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
Richard Smithcd35eff2018-09-15 01:21:16 +00003492
3493 const InputInfo &Input =
3494 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3495
3496 InputInfoList ModuleHeaderInputs;
3497 const InputInfo *CudaDeviceInput = nullptr;
3498 const InputInfo *OpenMPDeviceInput = nullptr;
3499 for (const InputInfo &I : Inputs) {
3500 if (&I == &Input) {
3501 // This is the primary input.
Benjamin Kramer5904c412018-11-05 12:46:02 +00003502 } else if (IsHeaderModulePrecompile &&
Richard Smithcd35eff2018-09-15 01:21:16 +00003503 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
Benjamin Kramer5904c412018-11-05 12:46:02 +00003504 types::ID Expected = HeaderModuleInput.getType();
Richard Smithcd35eff2018-09-15 01:21:16 +00003505 if (I.getType() != Expected) {
3506 D.Diag(diag::err_drv_module_header_wrong_kind)
3507 << I.getFilename() << types::getTypeName(I.getType())
3508 << types::getTypeName(Expected);
3509 }
3510 ModuleHeaderInputs.push_back(I);
3511 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3512 CudaDeviceInput = &I;
3513 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3514 OpenMPDeviceInput = &I;
3515 } else {
3516 llvm_unreachable("unexpectedly given multiple inputs");
3517 }
3518 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003519
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003520 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003521 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003522 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003523
Yaxun Liu398612b2018-05-08 21:02:12 +00003524 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3525 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3526 // Windows), we need to pass Windows-specific flags to cc1.
Fangrui Songe6e09562019-07-12 13:21:58 +00003527 if (IsCuda || IsHIP)
David L. Jonesf561aba2017-03-08 01:02:16 +00003528 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
David L. Jonesf561aba2017-03-08 01:02:16 +00003529
3530 // C++ is not supported for IAMCU.
3531 if (IsIAMCU && types::isCXX(Input.getType()))
3532 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3533
3534 // Invoke ourselves in -cc1 mode.
3535 //
3536 // FIXME: Implement custom jobs for internal actions.
3537 CmdArgs.push_back("-cc1");
3538
3539 // Add the "effective" target triple.
3540 CmdArgs.push_back("-triple");
3541 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3542
3543 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3544 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3545 Args.ClaimAllArgs(options::OPT_MJ);
Alex Lorenz8679ef42019-08-26 17:59:41 +00003546 } else if (const Arg *GenCDBFragment =
3547 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
3548 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
3549 TripleStr, Output, Input, Args);
3550 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
David L. Jonesf561aba2017-03-08 01:02:16 +00003551 }
3552
Yaxun Liu398612b2018-05-08 21:02:12 +00003553 if (IsCuda || IsHIP) {
3554 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3555 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003556 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003557 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3558 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003559 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3560 ->getTriple()
3561 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003562 else {
3563 // Host-side compilation.
Yaxun Liu398612b2018-05-08 21:02:12 +00003564 NormalizedTriple =
3565 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3566 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3567 ->getTriple()
3568 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003569 if (IsCuda) {
3570 // We need to figure out which CUDA version we're compiling for, as that
3571 // determines how we load and launch GPU kernels.
3572 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3573 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3574 assert(CTC && "Expected valid CUDA Toolchain.");
3575 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3576 CmdArgs.push_back(Args.MakeArgString(
3577 Twine("-target-sdk-version=") +
3578 CudaVersionToString(CTC->CudaInstallation.version())));
3579 }
3580 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003581 CmdArgs.push_back("-aux-triple");
3582 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3583 }
3584
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003585 if (IsOpenMPDevice) {
3586 // We have to pass the triple of the host if compiling for an OpenMP device.
3587 std::string NormalizedTriple =
3588 C.getSingleOffloadToolChain<Action::OFK_Host>()
3589 ->getTriple()
3590 .normalize();
3591 CmdArgs.push_back("-aux-triple");
3592 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3593 }
3594
David L. Jonesf561aba2017-03-08 01:02:16 +00003595 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3596 Triple.getArch() == llvm::Triple::thumb)) {
3597 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3598 unsigned Version;
3599 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3600 if (Version < 7)
3601 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3602 << TripleStr;
3603 }
3604
3605 // Push all default warning arguments that are specific to
3606 // the given target. These come before user provided warning options
3607 // are provided.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003608 TC.addClangWarningOptions(CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003609
3610 // Select the appropriate action.
3611 RewriteKind rewriteKind = RK_None;
3612
Nico Weberb28ffd82019-07-27 01:13:00 +00003613 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
3614 // it claims when not running an assembler. Otherwise, clang would emit
3615 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
3616 // flags while debugging something. That'd be somewhat inconvenient, and it's
3617 // also inconsistent with most other flags -- we don't warn on
3618 // -ffunction-sections not being used in -E mode either for example, even
3619 // though it's not really used either.
3620 if (!isa<AssembleJobAction>(JA)) {
3621 // The args claimed here should match the args used in
3622 // CollectArgsForIntegratedAssembler().
3623 if (TC.useIntegratedAs()) {
3624 Args.ClaimAllArgs(options::OPT_mrelax_all);
3625 Args.ClaimAllArgs(options::OPT_mno_relax_all);
3626 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
3627 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
3628 switch (C.getDefaultToolChain().getArch()) {
3629 case llvm::Triple::arm:
3630 case llvm::Triple::armeb:
3631 case llvm::Triple::thumb:
3632 case llvm::Triple::thumbeb:
3633 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
Bjorn Pettersson60c1ee22019-07-27 17:09:08 +00003634 break;
Nico Weberb28ffd82019-07-27 01:13:00 +00003635 default:
3636 break;
3637 }
3638 }
3639 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
3640 Args.ClaimAllArgs(options::OPT_Xassembler);
3641 }
3642
David L. Jonesf561aba2017-03-08 01:02:16 +00003643 if (isa<AnalyzeJobAction>(JA)) {
3644 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3645 CmdArgs.push_back("-analyze");
3646 } else if (isa<MigrateJobAction>(JA)) {
3647 CmdArgs.push_back("-migrate");
3648 } else if (isa<PreprocessJobAction>(JA)) {
3649 if (Output.getType() == types::TY_Dependencies)
3650 CmdArgs.push_back("-Eonly");
3651 else {
3652 CmdArgs.push_back("-E");
3653 if (Args.hasArg(options::OPT_rewrite_objc) &&
3654 !Args.hasArg(options::OPT_g_Group))
3655 CmdArgs.push_back("-P");
3656 }
3657 } else if (isa<AssembleJobAction>(JA)) {
3658 CmdArgs.push_back("-emit-obj");
3659
3660 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3661
3662 // Also ignore explicit -force_cpusubtype_ALL option.
3663 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3664 } else if (isa<PrecompileJobAction>(JA)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003665 if (JA.getType() == types::TY_Nothing)
3666 CmdArgs.push_back("-fsyntax-only");
3667 else if (JA.getType() == types::TY_ModuleFile)
Richard Smithcd35eff2018-09-15 01:21:16 +00003668 CmdArgs.push_back(IsHeaderModulePrecompile
3669 ? "-emit-header-module"
3670 : "-emit-module-interface");
David L. Jonesf561aba2017-03-08 01:02:16 +00003671 else
Erich Keane0a6b5b62018-12-04 14:34:09 +00003672 CmdArgs.push_back("-emit-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00003673 } else if (isa<VerifyPCHJobAction>(JA)) {
3674 CmdArgs.push_back("-verify-pch");
3675 } else {
3676 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3677 "Invalid action for clang tool.");
3678 if (JA.getType() == types::TY_Nothing) {
3679 CmdArgs.push_back("-fsyntax-only");
3680 } else if (JA.getType() == types::TY_LLVM_IR ||
3681 JA.getType() == types::TY_LTO_IR) {
3682 CmdArgs.push_back("-emit-llvm");
3683 } else if (JA.getType() == types::TY_LLVM_BC ||
3684 JA.getType() == types::TY_LTO_BC) {
3685 CmdArgs.push_back("-emit-llvm-bc");
Puyan Lotfic382d032019-10-08 15:23:14 +00003686 } else if (JA.getType() == types::TY_IFS ||
3687 JA.getType() == types::TY_IFS_CPP) {
Puyan Lotfi926f4f72019-08-22 23:44:34 +00003688 StringRef ArgStr =
3689 Args.hasArg(options::OPT_iterface_stub_version_EQ)
3690 ? Args.getLastArgValue(options::OPT_iterface_stub_version_EQ)
Puyan Lotfic382d032019-10-08 15:23:14 +00003691 : "experimental-ifs-v1";
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003692 CmdArgs.push_back("-emit-interface-stubs");
3693 CmdArgs.push_back(
Puyan Lotfic382d032019-10-08 15:23:14 +00003694 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003695 } else if (JA.getType() == types::TY_PP_Asm) {
3696 CmdArgs.push_back("-S");
3697 } else if (JA.getType() == types::TY_AST) {
3698 CmdArgs.push_back("-emit-pch");
3699 } else if (JA.getType() == types::TY_ModuleFile) {
3700 CmdArgs.push_back("-module-file-info");
3701 } else if (JA.getType() == types::TY_RewrittenObjC) {
3702 CmdArgs.push_back("-rewrite-objc");
3703 rewriteKind = RK_NonFragile;
3704 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3705 CmdArgs.push_back("-rewrite-objc");
3706 rewriteKind = RK_Fragile;
3707 } else {
3708 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3709 }
3710
3711 // Preserve use-list order by default when emitting bitcode, so that
3712 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3713 // same result as running passes here. For LTO, we don't need to preserve
3714 // the use-list order, since serialization to bitcode is part of the flow.
3715 if (JA.getType() == types::TY_LLVM_BC)
3716 CmdArgs.push_back("-emit-llvm-uselists");
3717
Artem Belevichecb178b2018-03-21 22:22:59 +00003718 // Device-side jobs do not support LTO.
3719 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3720 JA.isDeviceOffloading(Action::OFK_Host));
3721
3722 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003723 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3724
Paul Robinsond23f2a82017-07-13 21:25:47 +00003725 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3726 // does not support LTO unit features (CFI, whole program vtable opt)
3727 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003728 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003729 D.getLTOMode() == LTOK_Full)
3730 CmdArgs.push_back("-flto-unit");
3731 }
3732 }
3733
3734 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3735 if (!types::isLLVMIR(Input.getType()))
Bob Haarman79434642019-07-15 20:51:44 +00003736 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003737 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3738 }
3739
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003740 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003741 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3742
David L. Jonesf561aba2017-03-08 01:02:16 +00003743 // Embed-bitcode option.
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003744 // Only white-listed flags below are allowed to be embedded.
David L. Jonesf561aba2017-03-08 01:02:16 +00003745 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3746 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3747 // Add flags implied by -fembed-bitcode.
3748 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3749 // Disable all llvm IR level optimizations.
3750 CmdArgs.push_back("-disable-llvm-passes");
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003751
Fangrui Song2632ebb2019-05-30 02:30:04 +00003752 // Render target options such as -fuse-init-array on modern ELF platforms.
3753 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3754
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003755 // reject options that shouldn't be supported in bitcode
3756 // also reject kernel/kext
3757 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3758 options::OPT_mkernel,
3759 options::OPT_fapple_kext,
3760 options::OPT_ffunction_sections,
3761 options::OPT_fno_function_sections,
3762 options::OPT_fdata_sections,
3763 options::OPT_fno_data_sections,
3764 options::OPT_funique_section_names,
3765 options::OPT_fno_unique_section_names,
3766 options::OPT_mrestrict_it,
3767 options::OPT_mno_restrict_it,
3768 options::OPT_mstackrealign,
3769 options::OPT_mno_stackrealign,
3770 options::OPT_mstack_alignment,
3771 options::OPT_mcmodel_EQ,
3772 options::OPT_mlong_calls,
3773 options::OPT_mno_long_calls,
3774 options::OPT_ggnu_pubnames,
3775 options::OPT_gdwarf_aranges,
3776 options::OPT_fdebug_types_section,
3777 options::OPT_fno_debug_types_section,
3778 options::OPT_fdwarf_directory_asm,
3779 options::OPT_fno_dwarf_directory_asm,
3780 options::OPT_mrelax_all,
3781 options::OPT_mno_relax_all,
3782 options::OPT_ftrap_function_EQ,
3783 options::OPT_ffixed_r9,
3784 options::OPT_mfix_cortex_a53_835769,
3785 options::OPT_mno_fix_cortex_a53_835769,
3786 options::OPT_ffixed_x18,
3787 options::OPT_mglobal_merge,
3788 options::OPT_mno_global_merge,
3789 options::OPT_mred_zone,
3790 options::OPT_mno_red_zone,
3791 options::OPT_Wa_COMMA,
3792 options::OPT_Xassembler,
3793 options::OPT_mllvm,
3794 };
3795 for (const auto &A : Args)
Fangrui Song75e74e02019-03-31 08:48:19 +00003796 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003797 std::end(kBitcodeOptionBlacklist))
3798 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3799
3800 // Render the CodeGen options that need to be passed.
3801 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3802 options::OPT_fno_optimize_sibling_calls))
3803 CmdArgs.push_back("-mdisable-tail-calls");
3804
3805 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3806 CmdArgs);
3807
3808 // Render ABI arguments
3809 switch (TC.getArch()) {
3810 default: break;
3811 case llvm::Triple::arm:
3812 case llvm::Triple::armeb:
3813 case llvm::Triple::thumbeb:
3814 RenderARMABI(Triple, Args, CmdArgs);
3815 break;
3816 case llvm::Triple::aarch64:
3817 case llvm::Triple::aarch64_be:
3818 RenderAArch64ABI(Triple, Args, CmdArgs);
3819 break;
3820 }
3821
3822 // Optimization level for CodeGen.
3823 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3824 if (A->getOption().matches(options::OPT_O4)) {
3825 CmdArgs.push_back("-O3");
3826 D.Diag(diag::warn_O4_is_O3);
3827 } else {
3828 A->render(Args, CmdArgs);
3829 }
3830 }
3831
3832 // Input/Output file.
3833 if (Output.getType() == types::TY_Dependencies) {
3834 // Handled with other dependency code.
3835 } else if (Output.isFilename()) {
3836 CmdArgs.push_back("-o");
3837 CmdArgs.push_back(Output.getFilename());
3838 } else {
3839 assert(Output.isNothing() && "Input output.");
3840 }
3841
3842 for (const auto &II : Inputs) {
3843 addDashXForInput(Args, II, CmdArgs);
3844 if (II.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00003845 CmdArgs.push_back(II.getFilename());
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003846 else
3847 II.getInputArg().renderAsInput(Args, CmdArgs);
3848 }
3849
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003850 C.addCommand(std::make_unique<Command>(JA, *this, D.getClangProgramPath(),
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003851 CmdArgs, Inputs));
3852 return;
David L. Jonesf561aba2017-03-08 01:02:16 +00003853 }
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003854
David L. Jonesf561aba2017-03-08 01:02:16 +00003855 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3856 CmdArgs.push_back("-fembed-bitcode=marker");
3857
3858 // We normally speed up the clang process a bit by skipping destructors at
3859 // exit, but when we're generating diagnostics we can rely on some of the
3860 // cleanup.
3861 if (!C.isForDiagnostics())
3862 CmdArgs.push_back("-disable-free");
3863
David L. Jonesf561aba2017-03-08 01:02:16 +00003864#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003865 const bool IsAssertBuild = false;
3866#else
3867 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003868#endif
3869
Eric Fiselier123c7492018-02-07 18:36:51 +00003870 // Disable the verification pass in -asserts builds.
3871 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003872 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003873
3874 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003875 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3876 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003877 CmdArgs.push_back("-discard-value-names");
3878
David L. Jonesf561aba2017-03-08 01:02:16 +00003879 // Set the main file name, so that debug info works even with
3880 // -save-temps.
3881 CmdArgs.push_back("-main-file-name");
3882 CmdArgs.push_back(getBaseInputName(Args, Input));
3883
3884 // Some flags which affect the language (via preprocessor
3885 // defines).
3886 if (Args.hasArg(options::OPT_static))
3887 CmdArgs.push_back("-static-define");
3888
Martin Storsjo434ef832018-08-06 19:48:44 +00003889 if (Args.hasArg(options::OPT_municode))
3890 CmdArgs.push_back("-DUNICODE");
3891
Jan Korousb26e9e22019-09-24 03:21:22 +00003892 if (isa<AnalyzeJobAction>(JA))
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003893 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003894
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003895 // Enable compatilibily mode to avoid analyzer-config related errors.
3896 // Since we can't access frontend flags through hasArg, let's manually iterate
3897 // through them.
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003898 bool FoundAnalyzerConfig = false;
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003899 for (auto Arg : Args.filtered(options::OPT_Xclang))
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003900 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3901 FoundAnalyzerConfig = true;
3902 break;
3903 }
3904 if (!FoundAnalyzerConfig)
3905 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3906 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3907 FoundAnalyzerConfig = true;
3908 break;
3909 }
3910 if (FoundAnalyzerConfig)
3911 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003912
David L. Jonesf561aba2017-03-08 01:02:16 +00003913 CheckCodeGenerationOptions(D, Args);
3914
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003915 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003916 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3917 if (FunctionAlignment) {
3918 CmdArgs.push_back("-function-alignment");
3919 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3920 }
3921
David L. Jonesf561aba2017-03-08 01:02:16 +00003922 llvm::Reloc::Model RelocationModel;
3923 unsigned PICLevel;
3924 bool IsPIE;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003925 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003926
3927 const char *RMName = RelocationModelName(RelocationModel);
3928
3929 if ((RelocationModel == llvm::Reloc::ROPI ||
3930 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3931 types::isCXX(Input.getType()) &&
3932 !Args.hasArg(options::OPT_fallow_unsupported))
3933 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3934
3935 if (RMName) {
3936 CmdArgs.push_back("-mrelocation-model");
3937 CmdArgs.push_back(RMName);
3938 }
3939 if (PICLevel > 0) {
3940 CmdArgs.push_back("-pic-level");
3941 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3942 if (IsPIE)
3943 CmdArgs.push_back("-pic-is-pie");
3944 }
3945
Oliver Stannarde3c8ce82019-02-18 12:39:47 +00003946 if (RelocationModel == llvm::Reloc::ROPI ||
3947 RelocationModel == llvm::Reloc::ROPI_RWPI)
3948 CmdArgs.push_back("-fropi");
3949 if (RelocationModel == llvm::Reloc::RWPI ||
3950 RelocationModel == llvm::Reloc::ROPI_RWPI)
3951 CmdArgs.push_back("-frwpi");
3952
David L. Jonesf561aba2017-03-08 01:02:16 +00003953 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3954 CmdArgs.push_back("-meabi");
3955 CmdArgs.push_back(A->getValue());
3956 }
3957
3958 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003959 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003960 if (!TC.isThreadModelSupported(A->getValue()))
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003961 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3962 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003963 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003964 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003965 else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00003966 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003967
3968 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3969
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003970 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3971 options::OPT_fno_merge_all_constants, false))
3972 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003973
Manoj Guptada08f6a2018-07-19 00:44:52 +00003974 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3975 options::OPT_fdelete_null_pointer_checks, false))
3976 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3977
David L. Jonesf561aba2017-03-08 01:02:16 +00003978 // LLVM Code Generator Options.
3979
3980 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3981 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3982 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3983 options::OPT_frewrite_map_file_EQ)) {
3984 StringRef Map = A->getValue();
3985 if (!llvm::sys::fs::exists(Map)) {
3986 D.Diag(diag::err_drv_no_such_file) << Map;
3987 } else {
3988 CmdArgs.push_back("-frewrite-map-file");
3989 CmdArgs.push_back(A->getValue());
3990 A->claim();
3991 }
3992 }
3993 }
3994
3995 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3996 StringRef v = A->getValue();
3997 CmdArgs.push_back("-mllvm");
3998 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3999 A->claim();
4000 }
4001
4002 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4003 true))
4004 CmdArgs.push_back("-fno-jump-tables");
4005
Dehao Chen5e97f232017-08-24 21:37:33 +00004006 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
4007 options::OPT_fno_profile_sample_accurate, false))
4008 CmdArgs.push_back("-fprofile-sample-accurate");
4009
David L. Jonesf561aba2017-03-08 01:02:16 +00004010 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
4011 options::OPT_fno_preserve_as_comments, true))
4012 CmdArgs.push_back("-fno-preserve-as-comments");
4013
4014 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4015 CmdArgs.push_back("-mregparm");
4016 CmdArgs.push_back(A->getValue());
4017 }
4018
4019 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4020 options::OPT_freg_struct_return)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004021 if (TC.getArch() != llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004022 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004023 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00004024 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4025 CmdArgs.push_back("-fpcc-struct-return");
4026 } else {
4027 assert(A->getOption().matches(options::OPT_freg_struct_return));
4028 CmdArgs.push_back("-freg-struct-return");
4029 }
4030 }
4031
4032 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4033 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4034
Yuanfang Chenff22ec32019-07-20 22:50:50 +00004035 CodeGenOptions::FramePointerKind FPKeepKind =
4036 getFramePointerKind(Args, RawTriple);
4037 const char *FPKeepKindStr = nullptr;
4038 switch (FPKeepKind) {
4039 case CodeGenOptions::FramePointerKind::None:
4040 FPKeepKindStr = "-mframe-pointer=none";
4041 break;
4042 case CodeGenOptions::FramePointerKind::NonLeaf:
4043 FPKeepKindStr = "-mframe-pointer=non-leaf";
4044 break;
4045 case CodeGenOptions::FramePointerKind::All:
4046 FPKeepKindStr = "-mframe-pointer=all";
4047 break;
Fangrui Songdc039662019-07-12 02:01:51 +00004048 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +00004049 assert(FPKeepKindStr && "unknown FramePointerKind");
4050 CmdArgs.push_back(FPKeepKindStr);
4051
David L. Jonesf561aba2017-03-08 01:02:16 +00004052 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4053 options::OPT_fno_zero_initialized_in_bss))
4054 CmdArgs.push_back("-mno-zero-initialized-in-bss");
4055
4056 bool OFastEnabled = isOptimizationLevelFast(Args);
4057 // If -Ofast is the optimization level, then -fstrict-aliasing should be
4058 // enabled. This alias option is being used to simplify the hasFlag logic.
4059 OptSpecifier StrictAliasingAliasOption =
4060 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4061 // We turn strict aliasing off by default if we're in CL mode, since MSVC
4062 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004063 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004064 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4065 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4066 CmdArgs.push_back("-relaxed-aliasing");
4067 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4068 options::OPT_fno_struct_path_tbaa))
4069 CmdArgs.push_back("-no-struct-path-tbaa");
4070 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4071 false))
4072 CmdArgs.push_back("-fstrict-enums");
4073 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4074 true))
4075 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00004076 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
4077 options::OPT_fno_allow_editor_placeholders, false))
4078 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00004079 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4080 options::OPT_fno_strict_vtable_pointers,
4081 false))
4082 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00004083 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
4084 options::OPT_fno_force_emit_vtables,
4085 false))
4086 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00004087 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4088 options::OPT_fno_optimize_sibling_calls))
4089 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00004090 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00004091 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00004092 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00004093
Wei Mi9b3d6272017-10-16 16:50:27 +00004094 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4095 options::OPT_fno_fine_grained_bitfield_accesses);
4096
David L. Jonesf561aba2017-03-08 01:02:16 +00004097 // Handle segmented stacks.
4098 if (Args.hasArg(options::OPT_fsplit_stack))
4099 CmdArgs.push_back("-split-stacks");
4100
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004101 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004102
Troy A. Johnsonc0d70bc2019-08-17 04:20:24 +00004103 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
Fangrui Song11cb39c2019-07-09 00:27:43 +00004104 if (TC.getArch() == llvm::Triple::x86 ||
Troy A. Johnsonc0d70bc2019-08-17 04:20:24 +00004105 TC.getArch() == llvm::Triple::x86_64)
4106 A->render(Args, CmdArgs);
4107 else if ((TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64()) &&
4108 (A->getOption().getID() != options::OPT_mlong_double_80))
Fangrui Songc46d78d2019-07-12 02:32:15 +00004109 A->render(Args, CmdArgs);
4110 else
Fangrui Song11cb39c2019-07-09 00:27:43 +00004111 D.Diag(diag::err_drv_unsupported_opt_for_target)
4112 << A->getAsString(Args) << TripleStr;
Fangrui Song11cb39c2019-07-09 00:27:43 +00004113 }
4114
David L. Jonesf561aba2017-03-08 01:02:16 +00004115 // Decide whether to use verbose asm. Verbose assembly is the default on
4116 // toolchains which have the integrated assembler on by default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004117 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00004118 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
Erich Keanee30b71f2019-08-26 17:00:13 +00004119 IsIntegratedAssemblerDefault))
David L. Jonesf561aba2017-03-08 01:02:16 +00004120 CmdArgs.push_back("-masm-verbose");
4121
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004122 if (!TC.useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00004123 CmdArgs.push_back("-no-integrated-as");
4124
4125 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4126 CmdArgs.push_back("-mdebug-pass");
4127 CmdArgs.push_back("Structure");
4128 }
4129 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4130 CmdArgs.push_back("-mdebug-pass");
4131 CmdArgs.push_back("Arguments");
4132 }
4133
4134 // Enable -mconstructor-aliases except on darwin, where we have to work around
4135 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4136 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004137 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00004138 CmdArgs.push_back("-mconstructor-aliases");
4139
4140 // Darwin's kernel doesn't support guard variables; just die if we
4141 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004142 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00004143 CmdArgs.push_back("-fforbid-guard-variables");
4144
4145 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4146 false)) {
4147 CmdArgs.push_back("-mms-bitfields");
4148 }
4149
4150 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4151 options::OPT_mno_pie_copy_relocations,
4152 false)) {
4153 CmdArgs.push_back("-mpie-copy-relocations");
4154 }
4155
Sriraman Tallam5c651482017-11-07 19:37:51 +00004156 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4157 CmdArgs.push_back("-fno-plt");
4158 }
4159
Vedant Kumardf502592017-09-12 22:51:53 +00004160 // -fhosted is default.
4161 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4162 // use Freestanding.
4163 bool Freestanding =
4164 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4165 KernelOrKext;
4166 if (Freestanding)
4167 CmdArgs.push_back("-ffreestanding");
4168
David L. Jonesf561aba2017-03-08 01:02:16 +00004169 // This is a coarse approximation of what llvm-gcc actually does, both
4170 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4171 // complicated ways.
4172 bool AsynchronousUnwindTables =
4173 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4174 options::OPT_fno_asynchronous_unwind_tables,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004175 (TC.IsUnwindTablesDefault(Args) ||
4176 TC.getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00004177 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00004178 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4179 AsynchronousUnwindTables))
4180 CmdArgs.push_back("-munwind-tables");
4181
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004182 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00004183
David L. Jonesf561aba2017-03-08 01:02:16 +00004184 // FIXME: Handle -mtune=.
4185 (void)Args.hasArg(options::OPT_mtune_EQ);
4186
4187 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4188 CmdArgs.push_back("-mcode-model");
4189 CmdArgs.push_back(A->getValue());
4190 }
4191
4192 // Add the target cpu
4193 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4194 if (!CPU.empty()) {
4195 CmdArgs.push_back("-target-cpu");
4196 CmdArgs.push_back(Args.MakeArgString(CPU));
4197 }
4198
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00004199 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004200
David L. Jonesf561aba2017-03-08 01:02:16 +00004201 // These two are potentially updated by AddClangCLArgs.
4202 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4203 bool EmitCodeView = false;
4204
4205 // Add clang-cl arguments.
4206 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004207 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00004208 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4209
George Rimar91829ee2018-11-14 09:22:16 +00004210 DwarfFissionKind DwarfFission;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004211 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
George Rimar91829ee2018-11-14 09:22:16 +00004212 CmdArgs, DebugInfoKind, DwarfFission);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004213
4214 // Add the split debug info name to the command lines here so we
4215 // can propagate it to the backend.
George Rimar91829ee2018-11-14 09:22:16 +00004216 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
Fangrui Songee957e02019-03-28 08:24:00 +00004217 TC.getTriple().isOSBinFormatELF() &&
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004218 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4219 isa<BackendJobAction>(JA));
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004220 if (SplitDWARF) {
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004221 const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
4222 CmdArgs.push_back("-split-dwarf-file");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004223 CmdArgs.push_back(SplitDWARFOut);
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004224 if (DwarfFission == DwarfFissionKind::Split) {
4225 CmdArgs.push_back("-split-dwarf-output");
4226 CmdArgs.push_back(SplitDWARFOut);
4227 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004228 }
4229
David L. Jonesf561aba2017-03-08 01:02:16 +00004230 // Pass the linker version in use.
4231 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4232 CmdArgs.push_back("-target-linker-version");
4233 CmdArgs.push_back(A->getValue());
4234 }
4235
David L. Jonesf561aba2017-03-08 01:02:16 +00004236 // Explicitly error on some things we know we don't support and can't just
4237 // ignore.
4238 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4239 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004240 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004241 TC.getArch() == llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004242 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4243 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4244 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4245 << Unsupported->getOption().getName();
4246 }
Eric Christopher758aad72017-03-21 22:06:18 +00004247 // The faltivec option has been superseded by the maltivec option.
4248 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4249 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4250 << Unsupported->getOption().getName()
4251 << "please use -maltivec and include altivec.h explicitly";
4252 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4253 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4254 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00004255 }
4256
4257 Args.AddAllArgs(CmdArgs, options::OPT_v);
4258 Args.AddLastArg(CmdArgs, options::OPT_H);
4259 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4260 CmdArgs.push_back("-header-include-file");
4261 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4262 : "-");
4263 }
4264 Args.AddLastArg(CmdArgs, options::OPT_P);
4265 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4266
4267 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4268 CmdArgs.push_back("-diagnostic-log-file");
4269 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4270 : "-");
4271 }
4272
David L. Jonesf561aba2017-03-08 01:02:16 +00004273 bool UseSeparateSections = isUseSeparateSections(Triple);
4274
4275 if (Args.hasFlag(options::OPT_ffunction_sections,
4276 options::OPT_fno_function_sections, UseSeparateSections)) {
4277 CmdArgs.push_back("-ffunction-sections");
4278 }
4279
4280 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4281 UseSeparateSections)) {
4282 CmdArgs.push_back("-fdata-sections");
4283 }
4284
4285 if (!Args.hasFlag(options::OPT_funique_section_names,
4286 options::OPT_fno_unique_section_names, true))
4287 CmdArgs.push_back("-fno-unique-section-names");
4288
Nico Weber908b6972019-06-26 17:51:47 +00004289 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
4290 options::OPT_finstrument_functions_after_inlining,
4291 options::OPT_finstrument_function_entry_bare);
David L. Jonesf561aba2017-03-08 01:02:16 +00004292
Artem Belevichc30bcad2018-01-24 17:41:02 +00004293 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4294 // sampling, overhead of call arc collection is way too high and there's no
4295 // way to collect the output.
4296 if (!Triple.isNVPTX())
Russell Gallop7a9ccf82019-05-14 14:01:40 +00004297 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004298
Nico Weber908b6972019-06-26 17:51:47 +00004299 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
Richard Smithf667ad52017-08-26 01:04:35 +00004300
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004301 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
Pierre Gousseau53b5cfb2018-12-18 17:03:35 +00004302 if (RawTriple.isPS4CPU() &&
4303 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004304 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4305 PS4cpu::addSanitizerArgs(TC, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004306 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004307
4308 // Pass options for controlling the default header search paths.
4309 if (Args.hasArg(options::OPT_nostdinc)) {
4310 CmdArgs.push_back("-nostdsysteminc");
4311 CmdArgs.push_back("-nobuiltininc");
4312 } else {
4313 if (Args.hasArg(options::OPT_nostdlibinc))
4314 CmdArgs.push_back("-nostdsysteminc");
4315 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4316 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4317 }
4318
4319 // Pass the path to compiler resource files.
4320 CmdArgs.push_back("-resource-dir");
4321 CmdArgs.push_back(D.ResourceDir.c_str());
4322
4323 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4324
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00004325 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004326
4327 // Add preprocessing options like -I, -D, etc. if we are using the
4328 // preprocessor.
4329 //
4330 // FIXME: Support -fpreprocessed
4331 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4332 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4333
4334 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4335 // that "The compiler can only warn and ignore the option if not recognized".
4336 // When building with ccache, it will pass -D options to clang even on
4337 // preprocessed inputs and configure concludes that -fPIC is not supported.
4338 Args.ClaimAllArgs(options::OPT_D);
4339
4340 // Manually translate -O4 to -O3; let clang reject others.
4341 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4342 if (A->getOption().matches(options::OPT_O4)) {
4343 CmdArgs.push_back("-O3");
4344 D.Diag(diag::warn_O4_is_O3);
4345 } else {
4346 A->render(Args, CmdArgs);
4347 }
4348 }
4349
4350 // Warn about ignored options to clang.
4351 for (const Arg *A :
4352 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4353 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4354 A->claim();
4355 }
4356
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00004357 for (const Arg *A :
4358 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4359 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4360 A->claim();
4361 }
4362
David L. Jonesf561aba2017-03-08 01:02:16 +00004363 claimNoWarnArgs(Args);
4364
4365 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4366
4367 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4368 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4369 CmdArgs.push_back("-pedantic");
4370 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4371 Args.AddLastArg(CmdArgs, options::OPT_w);
4372
Leonard Chanf921d852018-06-04 16:07:52 +00004373 // Fixed point flags
4374 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4375 /*Default=*/false))
4376 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4377
David L. Jonesf561aba2017-03-08 01:02:16 +00004378 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4379 // (-ansi is equivalent to -std=c89 or -std=c++98).
4380 //
4381 // If a std is supplied, only add -trigraphs if it follows the
4382 // option.
4383 bool ImplyVCPPCXXVer = false;
Richard Smithb1b580e2019-04-14 11:11:37 +00004384 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
4385 if (Std) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004386 if (Std->getOption().matches(options::OPT_ansi))
4387 if (types::isCXX(InputType))
4388 CmdArgs.push_back("-std=c++98");
4389 else
4390 CmdArgs.push_back("-std=c89");
4391 else
4392 Std->render(Args, CmdArgs);
4393
4394 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4395 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4396 options::OPT_ftrigraphs,
4397 options::OPT_fno_trigraphs))
4398 if (A != Std)
4399 A->render(Args, CmdArgs);
4400 } else {
4401 // Honor -std-default.
4402 //
4403 // FIXME: Clang doesn't correctly handle -std= when the input language
4404 // doesn't match. For the time being just ignore this for C++ inputs;
4405 // eventually we want to do all the standard defaulting here instead of
4406 // splitting it between the driver and clang -cc1.
4407 if (!types::isCXX(InputType))
4408 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4409 /*Joined=*/true);
4410 else if (IsWindowsMSVC)
4411 ImplyVCPPCXXVer = true;
4412
4413 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4414 options::OPT_fno_trigraphs);
4415 }
4416
4417 // GCC's behavior for -Wwrite-strings is a bit strange:
4418 // * In C, this "warning flag" changes the types of string literals from
4419 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4420 // for the discarded qualifier.
4421 // * In C++, this is just a normal warning flag.
4422 //
4423 // Implementing this warning correctly in C is hard, so we follow GCC's
4424 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4425 // a non-const char* in C, rather than using this crude hack.
4426 if (!types::isCXX(InputType)) {
4427 // FIXME: This should behave just like a warning flag, and thus should also
4428 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4429 Arg *WriteStrings =
4430 Args.getLastArg(options::OPT_Wwrite_strings,
4431 options::OPT_Wno_write_strings, options::OPT_w);
4432 if (WriteStrings &&
4433 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4434 CmdArgs.push_back("-fconst-strings");
4435 }
4436
4437 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4438 // during C++ compilation, which it is by default. GCC keeps this define even
4439 // in the presence of '-w', match this behavior bug-for-bug.
4440 if (types::isCXX(InputType) &&
4441 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4442 true)) {
4443 CmdArgs.push_back("-fdeprecated-macro");
4444 }
4445
4446 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4447 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4448 if (Asm->getOption().matches(options::OPT_fasm))
4449 CmdArgs.push_back("-fgnu-keywords");
4450 else
4451 CmdArgs.push_back("-fno-gnu-keywords");
4452 }
4453
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004454 if (ShouldDisableDwarfDirectory(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004455 CmdArgs.push_back("-fno-dwarf-directory-asm");
4456
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004457 if (ShouldDisableAutolink(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004458 CmdArgs.push_back("-fno-autolink");
4459
4460 // Add in -fdebug-compilation-dir if necessary.
Hans Wennborg999f8a72019-09-05 08:43:00 +00004461 addDebugCompDirArg(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004462
Paul Robinson9b292b42018-07-10 15:15:24 +00004463 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004464
4465 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4466 options::OPT_ftemplate_depth_EQ)) {
4467 CmdArgs.push_back("-ftemplate-depth");
4468 CmdArgs.push_back(A->getValue());
4469 }
4470
4471 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4472 CmdArgs.push_back("-foperator-arrow-depth");
4473 CmdArgs.push_back(A->getValue());
4474 }
4475
4476 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4477 CmdArgs.push_back("-fconstexpr-depth");
4478 CmdArgs.push_back(A->getValue());
4479 }
4480
4481 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4482 CmdArgs.push_back("-fconstexpr-steps");
4483 CmdArgs.push_back(A->getValue());
4484 }
4485
Nandor Licker950b70d2019-09-13 09:46:16 +00004486 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
4487 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
4488
4489 if (Args.hasArg(options::OPT_fforce_experimental_new_constant_interpreter))
4490 CmdArgs.push_back("-fforce-experimental-new-constant-interpreter");
4491
David L. Jonesf561aba2017-03-08 01:02:16 +00004492 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4493 CmdArgs.push_back("-fbracket-depth");
4494 CmdArgs.push_back(A->getValue());
4495 }
4496
4497 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4498 options::OPT_Wlarge_by_value_copy_def)) {
4499 if (A->getNumValues()) {
4500 StringRef bytes = A->getValue();
4501 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4502 } else
4503 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4504 }
4505
4506 if (Args.hasArg(options::OPT_relocatable_pch))
4507 CmdArgs.push_back("-relocatable-pch");
4508
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004509 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4510 static const char *kCFABIs[] = {
4511 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4512 };
4513
4514 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4515 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4516 else
4517 A->render(Args, CmdArgs);
4518 }
4519
David L. Jonesf561aba2017-03-08 01:02:16 +00004520 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4521 CmdArgs.push_back("-fconstant-string-class");
4522 CmdArgs.push_back(A->getValue());
4523 }
4524
4525 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4526 CmdArgs.push_back("-ftabstop");
4527 CmdArgs.push_back(A->getValue());
4528 }
4529
Sean Eveson5110d4f2018-01-08 13:42:26 +00004530 if (Args.hasFlag(options::OPT_fstack_size_section,
4531 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4532 CmdArgs.push_back("-fstack-size-section");
4533
David L. Jonesf561aba2017-03-08 01:02:16 +00004534 CmdArgs.push_back("-ferror-limit");
4535 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4536 CmdArgs.push_back(A->getValue());
4537 else
4538 CmdArgs.push_back("19");
4539
4540 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4541 CmdArgs.push_back("-fmacro-backtrace-limit");
4542 CmdArgs.push_back(A->getValue());
4543 }
4544
4545 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4546 CmdArgs.push_back("-ftemplate-backtrace-limit");
4547 CmdArgs.push_back(A->getValue());
4548 }
4549
4550 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4551 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4552 CmdArgs.push_back(A->getValue());
4553 }
4554
4555 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4556 CmdArgs.push_back("-fspell-checking-limit");
4557 CmdArgs.push_back(A->getValue());
4558 }
4559
4560 // Pass -fmessage-length=.
4561 CmdArgs.push_back("-fmessage-length");
4562 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4563 CmdArgs.push_back(A->getValue());
4564 } else {
4565 // If -fmessage-length=N was not specified, determine whether this is a
4566 // terminal and, if so, implicitly define -fmessage-length appropriately.
4567 unsigned N = llvm::sys::Process::StandardErrColumns();
4568 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4569 }
4570
4571 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4572 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4573 options::OPT_fvisibility_ms_compat)) {
4574 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4575 CmdArgs.push_back("-fvisibility");
4576 CmdArgs.push_back(A->getValue());
4577 } else {
4578 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4579 CmdArgs.push_back("-fvisibility");
4580 CmdArgs.push_back("hidden");
4581 CmdArgs.push_back("-ftype-visibility");
4582 CmdArgs.push_back("default");
4583 }
4584 }
4585
4586 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
Petr Hosek821b38f2018-12-04 03:25:25 +00004587 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
David L. Jonesf561aba2017-03-08 01:02:16 +00004588
4589 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4590
David L. Jonesf561aba2017-03-08 01:02:16 +00004591 // Forward -f (flag) options which we can pass directly.
4592 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4593 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004594 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004595 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004596 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4597 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004598 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004599
David L. Jonesf561aba2017-03-08 01:02:16 +00004600 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004601 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004602 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004603
David L. Jonesf561aba2017-03-08 01:02:16 +00004604 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4605 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4606
4607 // Forward flags for OpenMP. We don't do this if the current action is an
4608 // device offloading action other than OpenMP.
4609 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4610 options::OPT_fno_openmp, false) &&
4611 (JA.isDeviceOffloading(Action::OFK_None) ||
4612 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004613 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004614 case Driver::OMPRT_OMP:
4615 case Driver::OMPRT_IOMP5:
4616 // Clang can generate useful OpenMP code for these two runtime libraries.
4617 CmdArgs.push_back("-fopenmp");
4618
4619 // If no option regarding the use of TLS in OpenMP codegeneration is
4620 // given, decide a default based on the target. Otherwise rely on the
4621 // options and pass the right information to the frontend.
4622 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4623 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4624 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004625 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4626 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004627 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Alexey Bataeve4090182018-11-02 14:54:07 +00004628 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4629 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004630 Args.AddAllArgs(CmdArgs,
4631 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004632 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4633 options::OPT_fno_openmp_optimistic_collapse,
4634 /*Default=*/false))
4635 CmdArgs.push_back("-fopenmp-optimistic-collapse");
Carlo Bertolli79712092018-02-28 20:48:35 +00004636
4637 // When in OpenMP offloading mode with NVPTX target, forward
4638 // cuda-mode flag
Alexey Bataev80a9a612018-08-30 14:45:24 +00004639 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4640 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4641 CmdArgs.push_back("-fopenmp-cuda-mode");
4642
4643 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4644 // is required.
4645 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4646 options::OPT_fno_openmp_cuda_force_full_runtime,
4647 /*Default=*/false))
4648 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
David L. Jonesf561aba2017-03-08 01:02:16 +00004649 break;
4650 default:
4651 // By default, if Clang doesn't know how to generate useful OpenMP code
4652 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4653 // down to the actual compilation.
4654 // FIXME: It would be better to have a mode which *only* omits IR
4655 // generation based on the OpenMP support so that we get consistent
4656 // semantic analysis, etc.
4657 break;
4658 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004659 } else {
4660 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4661 options::OPT_fno_openmp_simd);
4662 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004663 }
4664
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004665 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4666 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
David L. Jonesf561aba2017-03-08 01:02:16 +00004667
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004668 const XRayArgs &XRay = TC.getXRayArgs();
4669 XRay.addArgs(TC, Args, CmdArgs, InputType);
Dean Michael Berris835832d2017-03-30 00:29:36 +00004670
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004671 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004672 Args.AddLastArg(CmdArgs, options::OPT_pg);
4673
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004674 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004675 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4676
David L. Jonesf561aba2017-03-08 01:02:16 +00004677 if (Args.getLastArg(options::OPT_fapple_kext) ||
4678 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4679 CmdArgs.push_back("-fapple-kext");
4680
Richard Smithc6245102019-09-13 06:02:15 +00004681 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004682 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4683 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4684 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4685 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
Anton Afanasyevd880de22019-03-30 08:42:48 +00004686 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +00004687 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004688 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
Craig Topper3205dbb2019-03-21 20:07:24 +00004689 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
David L. Jonesf561aba2017-03-08 01:02:16 +00004690
4691 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4692 CmdArgs.push_back("-ftrapv-handler");
4693 CmdArgs.push_back(A->getValue());
4694 }
4695
4696 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4697
4698 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4699 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4700 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4701 if (A->getOption().matches(options::OPT_fwrapv))
4702 CmdArgs.push_back("-fwrapv");
4703 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4704 options::OPT_fno_strict_overflow)) {
4705 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4706 CmdArgs.push_back("-fwrapv");
4707 }
4708
4709 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4710 options::OPT_fno_reroll_loops))
4711 if (A->getOption().matches(options::OPT_freroll_loops))
4712 CmdArgs.push_back("-freroll-loops");
4713
4714 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4715 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4716 options::OPT_fno_unroll_loops);
4717
4718 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4719
Zola Bridgesc8666792018-11-26 18:13:31 +00004720 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4721 false))
4722 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
Chandler Carruth664aa862018-09-04 12:38:00 +00004723
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004724 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
JF Bastien14daa202018-12-18 05:12:21 +00004725 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004726
4727 // Translate -mstackrealign
4728 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4729 false))
4730 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4731
4732 if (Args.hasArg(options::OPT_mstack_alignment)) {
4733 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4734 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4735 }
4736
4737 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4738 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4739
4740 if (!Size.empty())
4741 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4742 else
4743 CmdArgs.push_back("-mstack-probe-size=0");
4744 }
4745
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004746 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4747 options::OPT_mno_stack_arg_probe, true))
4748 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4749
David L. Jonesf561aba2017-03-08 01:02:16 +00004750 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4751 options::OPT_mno_restrict_it)) {
4752 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004753 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004754 CmdArgs.push_back("-arm-restrict-it");
4755 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004756 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004757 CmdArgs.push_back("-arm-no-restrict-it");
4758 }
4759 } else if (Triple.isOSWindows() &&
4760 (Triple.getArch() == llvm::Triple::arm ||
4761 Triple.getArch() == llvm::Triple::thumb)) {
4762 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004763 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004764 CmdArgs.push_back("-arm-restrict-it");
4765 }
4766
4767 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004768 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004769
Yaxun Liu12828892019-09-24 19:16:40 +00004770 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
4771 options::OPT_fno_hip_new_launch_api, false))
4772 CmdArgs.push_back("-fhip-new-launch-api");
4773
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004774 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4775 CmdArgs.push_back(
4776 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4777 }
4778
David L. Jonesf561aba2017-03-08 01:02:16 +00004779 // Forward -f options with positive and negative forms; we translate
4780 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004781 if (Arg *A = getLastProfileSampleUseArg(Args)) {
Rong Xua4a09b22019-03-04 20:21:31 +00004782 auto *PGOArg = Args.getLastArg(
4783 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4784 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4785 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4786 if (PGOArg)
4787 D.Diag(diag::err_drv_argument_not_allowed_with)
4788 << "SampleUse with PGO options";
4789
David L. Jonesf561aba2017-03-08 01:02:16 +00004790 StringRef fname = A->getValue();
4791 if (!llvm::sys::fs::exists(fname))
4792 D.Diag(diag::err_drv_no_such_file) << fname;
4793 else
4794 A->render(Args, CmdArgs);
4795 }
Richard Smith8654ae52018-10-10 23:13:35 +00004796 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004797
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004798 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004799
4800 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4801 options::OPT_fno_assume_sane_operator_new))
4802 CmdArgs.push_back("-fno-assume-sane-operator-new");
4803
4804 // -fblocks=0 is default.
4805 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004806 TC.IsBlocksDefault()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004807 (Args.hasArg(options::OPT_fgnu_runtime) &&
4808 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4809 !Args.hasArg(options::OPT_fno_blocks))) {
4810 CmdArgs.push_back("-fblocks");
4811
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004812 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
David L. Jonesf561aba2017-03-08 01:02:16 +00004813 CmdArgs.push_back("-fblocks-runtime-optional");
4814 }
4815
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004816 // -fencode-extended-block-signature=1 is default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004817 if (TC.IsEncodeExtendedBlockSignatureDefault())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004818 CmdArgs.push_back("-fencode-extended-block-signature");
4819
David L. Jonesf561aba2017-03-08 01:02:16 +00004820 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4821 false) &&
4822 types::isCXX(InputType)) {
4823 CmdArgs.push_back("-fcoroutines-ts");
4824 }
4825
Aaron Ballman61736552017-10-21 20:28:58 +00004826 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4827 options::OPT_fno_double_square_bracket_attributes);
4828
David L. Jonesf561aba2017-03-08 01:02:16 +00004829 // -faccess-control is default.
4830 if (Args.hasFlag(options::OPT_fno_access_control,
4831 options::OPT_faccess_control, false))
4832 CmdArgs.push_back("-fno-access-control");
4833
4834 // -felide-constructors is the default.
4835 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4836 options::OPT_felide_constructors, false))
4837 CmdArgs.push_back("-fno-elide-constructors");
4838
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004839 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004840
4841 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004842 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004843 CmdArgs.push_back("-fno-rtti");
4844
4845 // -fshort-enums=0 is default for all architectures except Hexagon.
4846 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004847 TC.getArch() == llvm::Triple::hexagon))
David L. Jonesf561aba2017-03-08 01:02:16 +00004848 CmdArgs.push_back("-fshort-enums");
4849
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004850 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004851
4852 // -fuse-cxa-atexit is default.
4853 if (!Args.hasFlag(
4854 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004855 !RawTriple.isOSWindows() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004856 TC.getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004857 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4858 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004859 KernelOrKext)
4860 CmdArgs.push_back("-fno-use-cxa-atexit");
4861
Akira Hatanaka617e2612018-04-17 18:41:52 +00004862 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4863 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004864 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004865 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4866
David L. Jonesf561aba2017-03-08 01:02:16 +00004867 // -fms-extensions=0 is default.
4868 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4869 IsWindowsMSVC))
4870 CmdArgs.push_back("-fms-extensions");
4871
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004872 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004873 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004874 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004875 CmdArgs.push_back("-fuse-line-directives");
4876
4877 // -fms-compatibility=0 is default.
4878 if (Args.hasFlag(options::OPT_fms_compatibility,
4879 options::OPT_fno_ms_compatibility,
4880 (IsWindowsMSVC &&
4881 Args.hasFlag(options::OPT_fms_extensions,
4882 options::OPT_fno_ms_extensions, true))))
4883 CmdArgs.push_back("-fms-compatibility");
4884
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004885 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004886 if (!MSVT.empty())
4887 CmdArgs.push_back(
4888 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4889
4890 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4891 if (ImplyVCPPCXXVer) {
4892 StringRef LanguageStandard;
4893 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
Richard Smithb1b580e2019-04-14 11:11:37 +00004894 Std = StdArg;
David L. Jonesf561aba2017-03-08 01:02:16 +00004895 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4896 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004897 .Case("c++17", "-std=c++17")
4898 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004899 .Default("");
4900 if (LanguageStandard.empty())
4901 D.Diag(clang::diag::warn_drv_unused_argument)
4902 << StdArg->getAsString(Args);
4903 }
4904
4905 if (LanguageStandard.empty()) {
4906 if (IsMSVC2015Compatible)
4907 LanguageStandard = "-std=c++14";
4908 else
4909 LanguageStandard = "-std=c++11";
4910 }
4911
4912 CmdArgs.push_back(LanguageStandard.data());
4913 }
4914
4915 // -fno-borland-extensions is default.
4916 if (Args.hasFlag(options::OPT_fborland_extensions,
4917 options::OPT_fno_borland_extensions, false))
4918 CmdArgs.push_back("-fborland-extensions");
4919
4920 // -fno-declspec is default, except for PS4.
4921 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004922 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004923 CmdArgs.push_back("-fdeclspec");
4924 else if (Args.hasArg(options::OPT_fno_declspec))
4925 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4926
4927 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4928 // than 19.
4929 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4930 options::OPT_fno_threadsafe_statics,
4931 !IsWindowsMSVC || IsMSVC2015Compatible))
4932 CmdArgs.push_back("-fno-threadsafe-statics");
4933
Hans Wennborg82884532019-08-22 13:15:36 +00004934 // -fno-delayed-template-parsing is default, except when targeting MSVC.
4935 // Many old Windows SDK versions require this to parse.
4936 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4937 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004938 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
Hans Wennborg82884532019-08-22 13:15:36 +00004939 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004940 CmdArgs.push_back("-fdelayed-template-parsing");
4941
4942 // -fgnu-keywords default varies depending on language; only pass if
4943 // specified.
Nico Weber908b6972019-06-26 17:51:47 +00004944 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
4945 options::OPT_fno_gnu_keywords);
David L. Jonesf561aba2017-03-08 01:02:16 +00004946
4947 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4948 false))
4949 CmdArgs.push_back("-fgnu89-inline");
4950
4951 if (Args.hasArg(options::OPT_fno_inline))
4952 CmdArgs.push_back("-fno-inline");
4953
Nico Weber908b6972019-06-26 17:51:47 +00004954 Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
4955 options::OPT_finline_hint_functions,
4956 options::OPT_fno_inline_functions);
David L. Jonesf561aba2017-03-08 01:02:16 +00004957
Richard Smithb1b580e2019-04-14 11:11:37 +00004958 // FIXME: Find a better way to determine whether the language has modules
4959 // support by default, or just assume that all languages do.
4960 bool HaveModules =
4961 Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
4962 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4963
David L. Jonesf561aba2017-03-08 01:02:16 +00004964 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4965 options::OPT_fno_experimental_new_pass_manager);
4966
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004967 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004968 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4969 Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004970
4971 if (Args.hasFlag(options::OPT_fapplication_extension,
4972 options::OPT_fno_application_extension, false))
4973 CmdArgs.push_back("-fapplication-extension");
4974
4975 // Handle GCC-style exception args.
4976 if (!C.getDriver().IsCLMode())
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004977 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004978
Martell Malonec950c652017-11-29 07:25:12 +00004979 // Handle exception personalities
Heejin Ahne8b2b882019-09-12 04:01:37 +00004980 Arg *A = Args.getLastArg(
4981 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
4982 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
Martell Malonec950c652017-11-29 07:25:12 +00004983 if (A) {
4984 const Option &Opt = A->getOption();
4985 if (Opt.matches(options::OPT_fsjlj_exceptions))
4986 CmdArgs.push_back("-fsjlj-exceptions");
4987 if (Opt.matches(options::OPT_fseh_exceptions))
4988 CmdArgs.push_back("-fseh-exceptions");
4989 if (Opt.matches(options::OPT_fdwarf_exceptions))
4990 CmdArgs.push_back("-fdwarf-exceptions");
Heejin Ahne8b2b882019-09-12 04:01:37 +00004991 if (Opt.matches(options::OPT_fwasm_exceptions))
4992 CmdArgs.push_back("-fwasm-exceptions");
Martell Malonec950c652017-11-29 07:25:12 +00004993 } else {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004994 switch (TC.GetExceptionModel(Args)) {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004995 default:
4996 break;
4997 case llvm::ExceptionHandling::DwarfCFI:
4998 CmdArgs.push_back("-fdwarf-exceptions");
4999 break;
5000 case llvm::ExceptionHandling::SjLj:
5001 CmdArgs.push_back("-fsjlj-exceptions");
5002 break;
5003 case llvm::ExceptionHandling::WinEH:
5004 CmdArgs.push_back("-fseh-exceptions");
5005 break;
Martell Malonec950c652017-11-29 07:25:12 +00005006 }
5007 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005008
5009 // C++ "sane" operator new.
5010 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5011 options::OPT_fno_assume_sane_operator_new))
5012 CmdArgs.push_back("-fno-assume-sane-operator-new");
5013
5014 // -frelaxed-template-template-args is off by default, as it is a severe
5015 // breaking change until a corresponding change to template partial ordering
5016 // is provided.
5017 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
5018 options::OPT_fno_relaxed_template_template_args, false))
5019 CmdArgs.push_back("-frelaxed-template-template-args");
5020
5021 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5022 // most platforms.
5023 if (Args.hasFlag(options::OPT_fsized_deallocation,
5024 options::OPT_fno_sized_deallocation, false))
5025 CmdArgs.push_back("-fsized-deallocation");
5026
5027 // -faligned-allocation is on by default in C++17 onwards and otherwise off
5028 // by default.
5029 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
5030 options::OPT_fno_aligned_allocation,
5031 options::OPT_faligned_new_EQ)) {
5032 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
5033 CmdArgs.push_back("-fno-aligned-allocation");
5034 else
5035 CmdArgs.push_back("-faligned-allocation");
5036 }
5037
5038 // The default new alignment can be specified using a dedicated option or via
5039 // a GCC-compatible option that also turns on aligned allocation.
5040 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
5041 options::OPT_faligned_new_EQ))
5042 CmdArgs.push_back(
5043 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
5044
5045 // -fconstant-cfstrings is default, and may be subject to argument translation
5046 // on Darwin.
5047 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5048 options::OPT_fno_constant_cfstrings) ||
5049 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5050 options::OPT_mno_constant_cfstrings))
5051 CmdArgs.push_back("-fno-constant-cfstrings");
5052
David L. Jonesf561aba2017-03-08 01:02:16 +00005053 // -fno-pascal-strings is default, only pass non-default.
5054 if (Args.hasFlag(options::OPT_fpascal_strings,
5055 options::OPT_fno_pascal_strings, false))
5056 CmdArgs.push_back("-fpascal-strings");
5057
5058 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5059 // -fno-pack-struct doesn't apply to -fpack-struct=.
5060 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5061 std::string PackStructStr = "-fpack-struct=";
5062 PackStructStr += A->getValue();
5063 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5064 } else if (Args.hasFlag(options::OPT_fpack_struct,
5065 options::OPT_fno_pack_struct, false)) {
5066 CmdArgs.push_back("-fpack-struct=1");
5067 }
5068
5069 // Handle -fmax-type-align=N and -fno-type-align
5070 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5071 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5072 if (!SkipMaxTypeAlign) {
5073 std::string MaxTypeAlignStr = "-fmax-type-align=";
5074 MaxTypeAlignStr += A->getValue();
5075 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5076 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00005077 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005078 if (!SkipMaxTypeAlign) {
5079 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5080 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5081 }
5082 }
5083
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00005084 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
5085 CmdArgs.push_back("-Qn");
5086
David L. Jonesf561aba2017-03-08 01:02:16 +00005087 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00005088 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00005089 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5090 !NoCommonDefault))
5091 CmdArgs.push_back("-fno-common");
5092
5093 // -fsigned-bitfields is default, and clang doesn't yet support
5094 // -funsigned-bitfields.
5095 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5096 options::OPT_funsigned_bitfields))
5097 D.Diag(diag::warn_drv_clang_unsupported)
5098 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5099
5100 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5101 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5102 D.Diag(diag::err_drv_clang_unsupported)
5103 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5104
5105 // -finput_charset=UTF-8 is default. Reject others
5106 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5107 StringRef value = inputCharset->getValue();
5108 if (!value.equals_lower("utf-8"))
5109 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5110 << value;
5111 }
5112
5113 // -fexec_charset=UTF-8 is default. Reject others
5114 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5115 StringRef value = execCharset->getValue();
5116 if (!value.equals_lower("utf-8"))
5117 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5118 << value;
5119 }
5120
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00005121 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005122
5123 // -fno-asm-blocks is default.
5124 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5125 false))
5126 CmdArgs.push_back("-fasm-blocks");
5127
5128 // -fgnu-inline-asm is default.
5129 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5130 options::OPT_fno_gnu_inline_asm, true))
5131 CmdArgs.push_back("-fno-gnu-inline-asm");
5132
5133 // Enable vectorization per default according to the optimization level
5134 // selected. For optimization levels that want vectorization we use the alias
5135 // option to simplify the hasFlag logic.
5136 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5137 OptSpecifier VectorizeAliasOption =
5138 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5139 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5140 options::OPT_fno_vectorize, EnableVec))
5141 CmdArgs.push_back("-vectorize-loops");
5142
5143 // -fslp-vectorize is enabled based on the optimization level selected.
5144 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5145 OptSpecifier SLPVectAliasOption =
5146 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5147 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5148 options::OPT_fno_slp_vectorize, EnableSLPVec))
5149 CmdArgs.push_back("-vectorize-slp");
5150
Craig Topper9a724aa2017-12-11 21:09:19 +00005151 ParseMPreferVectorWidth(D, Args, CmdArgs);
5152
Nico Weber908b6972019-06-26 17:51:47 +00005153 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
5154 Args.AddLastArg(CmdArgs,
5155 options::OPT_fsanitize_undefined_strip_path_components_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00005156
5157 // -fdollars-in-identifiers default varies depending on platform and
5158 // language; only pass if specified.
5159 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5160 options::OPT_fno_dollars_in_identifiers)) {
5161 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5162 CmdArgs.push_back("-fdollars-in-identifiers");
5163 else
5164 CmdArgs.push_back("-fno-dollars-in-identifiers");
5165 }
5166
5167 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5168 // practical purposes.
5169 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5170 options::OPT_fno_unit_at_a_time)) {
5171 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5172 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5173 }
5174
5175 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5176 options::OPT_fno_apple_pragma_pack, false))
5177 CmdArgs.push_back("-fapple-pragma-pack");
5178
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005179 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
David L. Jonesf561aba2017-03-08 01:02:16 +00005180 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00005181 options::OPT_foptimization_record_file_EQ,
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005182 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005183 Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5184 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005185 Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00005186 options::OPT_fno_save_optimization_record, false)) {
5187 CmdArgs.push_back("-opt-record-file");
5188
5189 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5190 if (A) {
5191 CmdArgs.push_back(A->getValue());
5192 } else {
5193 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00005194
5195 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5196 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5197 F = FinalOutput->getValue();
5198 }
5199
5200 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005201 // Use the input filename.
5202 F = llvm::sys::path::stem(Input.getBaseInput());
5203
5204 // If we're compiling for an offload architecture (i.e. a CUDA device),
5205 // we need to make the file name for the device compilation different
5206 // from the host compilation.
5207 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5208 !JA.isDeviceOffloading(Action::OFK_Host)) {
5209 llvm::sys::path::replace_extension(F, "");
5210 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5211 Triple.normalize());
5212 F += "-";
5213 F += JA.getOffloadingArch();
5214 }
5215 }
5216
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005217 std::string Extension = "opt.";
5218 if (const Arg *A =
5219 Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
5220 Extension += A->getValue();
5221 else
5222 Extension += "yaml";
5223
5224 llvm::sys::path::replace_extension(F, Extension);
David L. Jonesf561aba2017-03-08 01:02:16 +00005225 CmdArgs.push_back(Args.MakeArgString(F));
5226 }
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005227
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005228 if (const Arg *A =
5229 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5230 CmdArgs.push_back("-opt-record-passes");
5231 CmdArgs.push_back(A->getValue());
5232 }
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005233
5234 if (const Arg *A =
5235 Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
5236 CmdArgs.push_back("-opt-record-format");
5237 CmdArgs.push_back(A->getValue());
5238 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005239 }
5240
Richard Smith86a3ef52017-06-09 21:24:02 +00005241 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5242 options::OPT_fno_rewrite_imports, false);
5243 if (RewriteImports)
5244 CmdArgs.push_back("-frewrite-imports");
5245
David L. Jonesf561aba2017-03-08 01:02:16 +00005246 // Enable rewrite includes if the user's asked for it or if we're generating
5247 // diagnostics.
5248 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5249 // nice to enable this when doing a crashdump for modules as well.
5250 if (Args.hasFlag(options::OPT_frewrite_includes,
5251 options::OPT_fno_rewrite_includes, false) ||
David Blaikiea99b8e42018-11-15 03:04:19 +00005252 (C.isForDiagnostics() && !HaveModules))
David L. Jonesf561aba2017-03-08 01:02:16 +00005253 CmdArgs.push_back("-frewrite-includes");
5254
5255 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5256 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5257 options::OPT_traditional_cpp)) {
5258 if (isa<PreprocessJobAction>(JA))
5259 CmdArgs.push_back("-traditional-cpp");
5260 else
5261 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5262 }
5263
5264 Args.AddLastArg(CmdArgs, options::OPT_dM);
5265 Args.AddLastArg(CmdArgs, options::OPT_dD);
5266
5267 // Handle serialized diagnostics.
5268 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5269 CmdArgs.push_back("-serialize-diagnostic-file");
5270 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5271 }
5272
5273 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5274 CmdArgs.push_back("-fretain-comments-from-system-headers");
5275
5276 // Forward -fcomment-block-commands to -cc1.
5277 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5278 // Forward -fparse-all-comments to -cc1.
5279 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5280
5281 // Turn -fplugin=name.so into -load name.so
5282 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5283 CmdArgs.push_back("-load");
5284 CmdArgs.push_back(A->getValue());
5285 A->claim();
5286 }
5287
Philip Pfaffee3f105c2019-02-02 23:19:32 +00005288 // Forward -fpass-plugin=name.so to -cc1.
5289 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5290 CmdArgs.push_back(
5291 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5292 A->claim();
5293 }
5294
David L. Jonesf561aba2017-03-08 01:02:16 +00005295 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00005296 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5297 if (!StatsFile.empty())
5298 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00005299
5300 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5301 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00005302 // -finclude-default-header flag is for preprocessor,
5303 // do not pass it to other cc1 commands when save-temps is enabled
5304 if (C.getDriver().isSaveTempsEnabled() &&
5305 !isa<PreprocessJobAction>(JA)) {
5306 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5307 Arg->claim();
5308 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5309 CmdArgs.push_back(Arg->getValue());
5310 }
5311 }
5312 else {
5313 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5314 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005315 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5316 A->claim();
5317
5318 // We translate this by hand to the -cc1 argument, since nightly test uses
5319 // it and developers have been trained to spell it with -mllvm. Both
5320 // spellings are now deprecated and should be removed.
5321 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5322 CmdArgs.push_back("-disable-llvm-optzns");
5323 } else {
5324 A->render(Args, CmdArgs);
5325 }
5326 }
5327
5328 // With -save-temps, we want to save the unoptimized bitcode output from the
5329 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5330 // by the frontend.
5331 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5332 // has slightly different breakdown between stages.
5333 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5334 // pristine IR generated by the frontend. Ideally, a new compile action should
5335 // be added so both IR can be captured.
5336 if (C.getDriver().isSaveTempsEnabled() &&
5337 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5338 isa<CompileJobAction>(JA))
5339 CmdArgs.push_back("-disable-llvm-passes");
5340
David L. Jonesf561aba2017-03-08 01:02:16 +00005341 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5342
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00005343 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00005344
Scott Linderde6beb02018-12-14 15:38:15 +00005345 // Optionally embed the -cc1 level arguments into the debug info or a
5346 // section, for build analysis.
Eric Christopherca325172017-03-29 23:34:20 +00005347 // Also record command line arguments into the debug info if
5348 // -grecord-gcc-switches options is set on.
5349 // By default, -gno-record-gcc-switches is set on and no recording.
Scott Linderde6beb02018-12-14 15:38:15 +00005350 auto GRecordSwitches =
5351 Args.hasFlag(options::OPT_grecord_command_line,
5352 options::OPT_gno_record_command_line, false);
5353 auto FRecordSwitches =
5354 Args.hasFlag(options::OPT_frecord_command_line,
5355 options::OPT_fno_record_command_line, false);
5356 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5357 D.Diag(diag::err_drv_unsupported_opt_for_target)
5358 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5359 << TripleStr;
5360 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005361 ArgStringList OriginalArgs;
5362 for (const auto &Arg : Args)
5363 Arg->render(Args, OriginalArgs);
5364
5365 SmallString<256> Flags;
5366 Flags += Exec;
5367 for (const char *OriginalArg : OriginalArgs) {
5368 SmallString<128> EscapedArg;
5369 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5370 Flags += " ";
5371 Flags += EscapedArg;
5372 }
Scott Linderde6beb02018-12-14 15:38:15 +00005373 auto FlagsArgString = Args.MakeArgString(Flags);
5374 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5375 CmdArgs.push_back("-dwarf-debug-flags");
5376 CmdArgs.push_back(FlagsArgString);
5377 }
5378 if (FRecordSwitches) {
5379 CmdArgs.push_back("-record-command-line");
5380 CmdArgs.push_back(FlagsArgString);
5381 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005382 }
5383
Yaxun Liu97670892018-10-02 17:48:54 +00005384 // Host-side cuda compilation receives all device-side outputs in a single
5385 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5386 if ((IsCuda || IsHIP) && CudaDeviceInput) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00005387 CmdArgs.push_back("-fcuda-include-gpubinary");
Richard Smithcd35eff2018-09-15 01:21:16 +00005388 CmdArgs.push_back(CudaDeviceInput->getFilename());
Yaxun Liu97670892018-10-02 17:48:54 +00005389 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5390 CmdArgs.push_back("-fgpu-rdc");
5391 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005392
Yaxun Liu97670892018-10-02 17:48:54 +00005393 if (IsCuda) {
Artem Belevich679dafe2018-05-09 23:10:09 +00005394 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5395 options::OPT_fno_cuda_short_ptr, false))
5396 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00005397 }
5398
David L. Jonesf561aba2017-03-08 01:02:16 +00005399 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5400 // to specify the result of the compile phase on the host, so the meaningful
5401 // device declarations can be identified. Also, -fopenmp-is-device is passed
5402 // along to tell the frontend that it is generating code for a device, so that
5403 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005404 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005405 CmdArgs.push_back("-fopenmp-is-device");
Richard Smithcd35eff2018-09-15 01:21:16 +00005406 if (OpenMPDeviceInput) {
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005407 CmdArgs.push_back("-fopenmp-host-ir-file-path");
Richard Smithcd35eff2018-09-15 01:21:16 +00005408 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005409 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005410 }
5411
5412 // For all the host OpenMP offloading compile jobs we need to pass the targets
5413 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00005414 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005415 SmallString<128> TargetInfo("-fopenmp-targets=");
5416
5417 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5418 assert(Tgts && Tgts->getNumValues() &&
5419 "OpenMP offloading has to have targets specified.");
5420 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5421 if (i)
5422 TargetInfo += ',';
5423 // We need to get the string from the triple because it may be not exactly
5424 // the same as the one we get directly from the arguments.
5425 llvm::Triple T(Tgts->getValue(i));
5426 TargetInfo += T.getTriple();
5427 }
5428 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5429 }
5430
5431 bool WholeProgramVTables =
5432 Args.hasFlag(options::OPT_fwhole_program_vtables,
5433 options::OPT_fno_whole_program_vtables, false);
5434 if (WholeProgramVTables) {
5435 if (!D.isUsingLTO())
5436 D.Diag(diag::err_drv_argument_only_allowed_with)
5437 << "-fwhole-program-vtables"
5438 << "-flto";
5439 CmdArgs.push_back("-fwhole-program-vtables");
5440 }
5441
Teresa Johnsondca5b942019-10-01 18:08:29 +00005442 bool DefaultsSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
Teresa Johnson84cecfc2019-01-11 18:32:07 +00005443 bool SplitLTOUnit =
5444 Args.hasFlag(options::OPT_fsplit_lto_unit,
Teresa Johnsondca5b942019-10-01 18:08:29 +00005445 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
5446 if (Sanitize.needsLTO() && !SplitLTOUnit)
5447 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
5448 << "-fsanitize=cfi";
Teresa Johnson84cecfc2019-01-11 18:32:07 +00005449 if (SplitLTOUnit)
5450 CmdArgs.push_back("-fsplit-lto-unit");
5451
Amara Emerson4ee9f822018-01-26 00:27:22 +00005452 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5453 options::OPT_fno_experimental_isel)) {
5454 CmdArgs.push_back("-mllvm");
5455 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5456 CmdArgs.push_back("-global-isel=1");
5457
5458 // GISel is on by default on AArch64 -O0, so don't bother adding
5459 // the fallback remarks for it. Other combinations will add a warning of
5460 // some kind.
5461 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5462 bool IsOptLevelSupported = false;
5463
5464 Arg *A = Args.getLastArg(options::OPT_O_Group);
5465 if (Triple.getArch() == llvm::Triple::aarch64) {
5466 if (!A || A->getOption().matches(options::OPT_O0))
5467 IsOptLevelSupported = true;
5468 }
5469 if (!IsArchSupported || !IsOptLevelSupported) {
5470 CmdArgs.push_back("-mllvm");
5471 CmdArgs.push_back("-global-isel-abort=2");
5472
5473 if (!IsArchSupported)
5474 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5475 else
5476 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5477 }
5478 } else {
5479 CmdArgs.push_back("-global-isel=0");
5480 }
5481 }
5482
Manman Ren394d4cc2019-03-04 20:30:30 +00005483 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5484 CmdArgs.push_back("-forder-file-instrumentation");
5485 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5486 // on, we need to pass these flags as linker flags and that will be handled
5487 // outside of the compiler.
5488 if (!D.isUsingLTO()) {
5489 CmdArgs.push_back("-mllvm");
5490 CmdArgs.push_back("-enable-order-file-instrumentation");
5491 }
5492 }
5493
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00005494 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5495 options::OPT_fno_force_enable_int128)) {
5496 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5497 CmdArgs.push_back("-fforce-enable-int128");
5498 }
5499
Peter Collingbourne54d13b42018-05-30 03:40:04 +00005500 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5501 options::OPT_fno_complete_member_pointers, false))
5502 CmdArgs.push_back("-fcomplete-member-pointers");
5503
Erik Pilkington5a559e62018-08-21 17:24:06 +00005504 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5505 options::OPT_fno_cxx_static_destructors, true))
5506 CmdArgs.push_back("-fno-c++-static-destructors");
5507
Jessica Paquette36a25672018-06-29 18:06:10 +00005508 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5509 options::OPT_mno_outline)) {
5510 if (A->getOption().matches(options::OPT_moutline)) {
5511 // We only support -moutline in AArch64 right now. If we're not compiling
5512 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5513 // proper mllvm flags.
5514 if (Triple.getArch() != llvm::Triple::aarch64) {
5515 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5516 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00005517 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00005518 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005519 }
Jessica Paquette36a25672018-06-29 18:06:10 +00005520 } else {
5521 // Disable all outlining behaviour.
5522 CmdArgs.push_back("-mllvm");
5523 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005524 }
5525 }
5526
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005527 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00005528 (TC.getTriple().isOSBinFormatELF() ||
5529 TC.getTriple().isOSBinFormatCOFF()) &&
Douglas Yung25f04772018-12-19 22:45:26 +00005530 !TC.getTriple().isPS4() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005531 !TC.getTriple().isOSNetBSD() &&
Michal Gornydae01c32018-12-23 15:07:26 +00005532 !Distro(D.getVFS()).IsGentoo() &&
Dan Albertdd142342019-01-08 22:33:59 +00005533 !TC.getTriple().isAndroid() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005534 TC.useIntegratedAs()))
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005535 CmdArgs.push_back("-faddrsig");
5536
Peter Collingbournee08e68d2019-06-07 19:10:08 +00005537 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
5538 std::string Str = A->getAsString(Args);
5539 if (!TC.getTriple().isOSBinFormatELF())
5540 D.Diag(diag::err_drv_unsupported_opt_for_target)
5541 << Str << TC.getTripleString();
5542 CmdArgs.push_back(Args.MakeArgString(Str));
5543 }
5544
Reid Kleckner549ed542019-05-23 18:35:43 +00005545 // Add the "-o out -x type src.c" flags last. This is done primarily to make
5546 // the -cc1 command easier to edit when reproducing compiler crashes.
5547 if (Output.getType() == types::TY_Dependencies) {
5548 // Handled with other dependency code.
5549 } else if (Output.isFilename()) {
5550 CmdArgs.push_back("-o");
5551 CmdArgs.push_back(Output.getFilename());
5552 } else {
5553 assert(Output.isNothing() && "Invalid output.");
5554 }
5555
5556 addDashXForInput(Args, Input, CmdArgs);
5557
5558 ArrayRef<InputInfo> FrontendInputs = Input;
5559 if (IsHeaderModulePrecompile)
5560 FrontendInputs = ModuleHeaderInputs;
5561 else if (Input.isNothing())
5562 FrontendInputs = {};
5563
5564 for (const InputInfo &Input : FrontendInputs) {
5565 if (Input.isFilename())
5566 CmdArgs.push_back(Input.getFilename());
5567 else
5568 Input.getInputArg().renderAsInput(Args, CmdArgs);
5569 }
5570
David L. Jonesf561aba2017-03-08 01:02:16 +00005571 // Finally add the compile command to the compilation.
5572 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5573 Output.getType() == types::TY_Object &&
5574 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5575 auto CLCommand =
5576 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00005577 C.addCommand(std::make_unique<FallbackCommand>(
David L. Jonesf561aba2017-03-08 01:02:16 +00005578 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5579 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5580 isa<PrecompileJobAction>(JA)) {
5581 // In /fallback builds, run the main compilation even if the pch generation
5582 // fails, so that the main compilation's fallback to cl.exe runs.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00005583 C.addCommand(std::make_unique<ForceSuccessCommand>(JA, *this, Exec,
David L. Jonesf561aba2017-03-08 01:02:16 +00005584 CmdArgs, Inputs));
5585 } else {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00005586 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005587 }
5588
Hans Wennborg2fe01042018-10-13 19:13:14 +00005589 // Make the compile command echo its inputs for /showFilenames.
5590 if (Output.getType() == types::TY_Object &&
5591 Args.hasFlag(options::OPT__SLASH_showFilenames,
5592 options::OPT__SLASH_showFilenames_, false)) {
5593 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5594 }
5595
David L. Jonesf561aba2017-03-08 01:02:16 +00005596 if (Arg *A = Args.getLastArg(options::OPT_pg))
Yuanfang Chenff22ec32019-07-20 22:50:50 +00005597 if (FPKeepKind == CodeGenOptions::FramePointerKind::None)
David L. Jonesf561aba2017-03-08 01:02:16 +00005598 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5599 << A->getAsString(Args);
5600
5601 // Claim some arguments which clang supports automatically.
5602
5603 // -fpch-preprocess is used with gcc to add a special marker in the output to
Erich Keane0a6b5b62018-12-04 14:34:09 +00005604 // include the PCH file.
David L. Jonesf561aba2017-03-08 01:02:16 +00005605 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5606
5607 // Claim some arguments which clang doesn't support, but we don't
5608 // care to warn the user about.
5609 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5610 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5611
5612 // Disable warnings for clang -E -emit-llvm foo.c
5613 Args.ClaimAllArgs(options::OPT_emit_llvm);
5614}
5615
5616Clang::Clang(const ToolChain &TC)
5617 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5618 // as it is for other tools. Some operations on a Tool actually test
5619 // whether that tool is Clang based on the Tool's Name as a string.
5620 : Tool("clang", "clang frontend", TC, RF_Full) {}
5621
5622Clang::~Clang() {}
5623
5624/// Add options related to the Objective-C runtime/ABI.
5625///
5626/// Returns true if the runtime is non-fragile.
5627ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5628 ArgStringList &cmdArgs,
5629 RewriteKind rewriteKind) const {
5630 // Look for the controlling runtime option.
5631 Arg *runtimeArg =
5632 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5633 options::OPT_fobjc_runtime_EQ);
5634
5635 // Just forward -fobjc-runtime= to the frontend. This supercedes
5636 // options about fragility.
5637 if (runtimeArg &&
5638 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5639 ObjCRuntime runtime;
5640 StringRef value = runtimeArg->getValue();
5641 if (runtime.tryParse(value)) {
5642 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5643 << value;
5644 }
David Chisnall404bbcb2018-05-22 10:13:06 +00005645 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5646 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnallef16ea72018-09-04 10:07:27 +00005647 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5648 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00005649 getToolChain().getDriver().Diag(
5650 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5651 << runtime.getVersion().getMajor();
5652 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005653
5654 runtimeArg->render(args, cmdArgs);
5655 return runtime;
5656 }
5657
5658 // Otherwise, we'll need the ABI "version". Version numbers are
5659 // slightly confusing for historical reasons:
5660 // 1 - Traditional "fragile" ABI
5661 // 2 - Non-fragile ABI, version 1
5662 // 3 - Non-fragile ABI, version 2
5663 unsigned objcABIVersion = 1;
5664 // If -fobjc-abi-version= is present, use that to set the version.
5665 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5666 StringRef value = abiArg->getValue();
5667 if (value == "1")
5668 objcABIVersion = 1;
5669 else if (value == "2")
5670 objcABIVersion = 2;
5671 else if (value == "3")
5672 objcABIVersion = 3;
5673 else
5674 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5675 } else {
5676 // Otherwise, determine if we are using the non-fragile ABI.
5677 bool nonFragileABIIsDefault =
5678 (rewriteKind == RK_NonFragile ||
5679 (rewriteKind == RK_None &&
5680 getToolChain().IsObjCNonFragileABIDefault()));
5681 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5682 options::OPT_fno_objc_nonfragile_abi,
5683 nonFragileABIIsDefault)) {
5684// Determine the non-fragile ABI version to use.
5685#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5686 unsigned nonFragileABIVersion = 1;
5687#else
5688 unsigned nonFragileABIVersion = 2;
5689#endif
5690
5691 if (Arg *abiArg =
5692 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5693 StringRef value = abiArg->getValue();
5694 if (value == "1")
5695 nonFragileABIVersion = 1;
5696 else if (value == "2")
5697 nonFragileABIVersion = 2;
5698 else
5699 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5700 << value;
5701 }
5702
5703 objcABIVersion = 1 + nonFragileABIVersion;
5704 } else {
5705 objcABIVersion = 1;
5706 }
5707 }
5708
5709 // We don't actually care about the ABI version other than whether
5710 // it's non-fragile.
5711 bool isNonFragile = objcABIVersion != 1;
5712
5713 // If we have no runtime argument, ask the toolchain for its default runtime.
5714 // However, the rewriter only really supports the Mac runtime, so assume that.
5715 ObjCRuntime runtime;
5716 if (!runtimeArg) {
5717 switch (rewriteKind) {
5718 case RK_None:
5719 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5720 break;
5721 case RK_Fragile:
5722 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5723 break;
5724 case RK_NonFragile:
5725 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5726 break;
5727 }
5728
5729 // -fnext-runtime
5730 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5731 // On Darwin, make this use the default behavior for the toolchain.
5732 if (getToolChain().getTriple().isOSDarwin()) {
5733 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5734
5735 // Otherwise, build for a generic macosx port.
5736 } else {
5737 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5738 }
5739
5740 // -fgnu-runtime
5741 } else {
5742 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5743 // Legacy behaviour is to target the gnustep runtime if we are in
5744 // non-fragile mode or the GCC runtime in fragile mode.
5745 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005746 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005747 else
5748 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5749 }
5750
5751 cmdArgs.push_back(
5752 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5753 return runtime;
5754}
5755
5756static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5757 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5758 I += HaveDash;
5759 return !HaveDash;
5760}
5761
5762namespace {
5763struct EHFlags {
5764 bool Synch = false;
5765 bool Asynch = false;
5766 bool NoUnwindC = false;
5767};
5768} // end anonymous namespace
5769
5770/// /EH controls whether to run destructor cleanups when exceptions are
5771/// thrown. There are three modifiers:
5772/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5773/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5774/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5775/// - c: Assume that extern "C" functions are implicitly nounwind.
5776/// The default is /EHs-c-, meaning cleanups are disabled.
5777static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5778 EHFlags EH;
5779
5780 std::vector<std::string> EHArgs =
5781 Args.getAllArgValues(options::OPT__SLASH_EH);
5782 for (auto EHVal : EHArgs) {
5783 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5784 switch (EHVal[I]) {
5785 case 'a':
5786 EH.Asynch = maybeConsumeDash(EHVal, I);
5787 if (EH.Asynch)
5788 EH.Synch = false;
5789 continue;
5790 case 'c':
5791 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5792 continue;
5793 case 's':
5794 EH.Synch = maybeConsumeDash(EHVal, I);
5795 if (EH.Synch)
5796 EH.Asynch = false;
5797 continue;
5798 default:
5799 break;
5800 }
5801 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5802 break;
5803 }
5804 }
5805 // The /GX, /GX- flags are only processed if there are not /EH flags.
5806 // The default is that /GX is not specified.
5807 if (EHArgs.empty() &&
5808 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005809 /*Default=*/false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005810 EH.Synch = true;
5811 EH.NoUnwindC = true;
5812 }
5813
5814 return EH;
5815}
5816
5817void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5818 ArgStringList &CmdArgs,
5819 codegenoptions::DebugInfoKind *DebugInfoKind,
5820 bool *EmitCodeView) const {
5821 unsigned RTOptionID = options::OPT__SLASH_MT;
5822
5823 if (Args.hasArg(options::OPT__SLASH_LDd))
5824 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5825 // but defining _DEBUG is sticky.
5826 RTOptionID = options::OPT__SLASH_MTd;
5827
5828 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5829 RTOptionID = A->getOption().getID();
5830
5831 StringRef FlagForCRT;
5832 switch (RTOptionID) {
5833 case options::OPT__SLASH_MD:
5834 if (Args.hasArg(options::OPT__SLASH_LDd))
5835 CmdArgs.push_back("-D_DEBUG");
5836 CmdArgs.push_back("-D_MT");
5837 CmdArgs.push_back("-D_DLL");
5838 FlagForCRT = "--dependent-lib=msvcrt";
5839 break;
5840 case options::OPT__SLASH_MDd:
5841 CmdArgs.push_back("-D_DEBUG");
5842 CmdArgs.push_back("-D_MT");
5843 CmdArgs.push_back("-D_DLL");
5844 FlagForCRT = "--dependent-lib=msvcrtd";
5845 break;
5846 case options::OPT__SLASH_MT:
5847 if (Args.hasArg(options::OPT__SLASH_LDd))
5848 CmdArgs.push_back("-D_DEBUG");
5849 CmdArgs.push_back("-D_MT");
5850 CmdArgs.push_back("-flto-visibility-public-std");
5851 FlagForCRT = "--dependent-lib=libcmt";
5852 break;
5853 case options::OPT__SLASH_MTd:
5854 CmdArgs.push_back("-D_DEBUG");
5855 CmdArgs.push_back("-D_MT");
5856 CmdArgs.push_back("-flto-visibility-public-std");
5857 FlagForCRT = "--dependent-lib=libcmtd";
5858 break;
5859 default:
5860 llvm_unreachable("Unexpected option ID.");
5861 }
5862
5863 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5864 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5865 } else {
5866 CmdArgs.push_back(FlagForCRT.data());
5867
5868 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5869 // users want. The /Za flag to cl.exe turns this off, but it's not
5870 // implemented in clang.
5871 CmdArgs.push_back("--dependent-lib=oldnames");
5872 }
5873
Nico Weber908b6972019-06-26 17:51:47 +00005874 Args.AddLastArg(CmdArgs, options::OPT_show_includes);
David L. Jonesf561aba2017-03-08 01:02:16 +00005875
5876 // This controls whether or not we emit RTTI data for polymorphic types.
5877 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005878 /*Default=*/false))
David L. Jonesf561aba2017-03-08 01:02:16 +00005879 CmdArgs.push_back("-fno-rtti-data");
5880
5881 // This controls whether or not we emit stack-protector instrumentation.
5882 // In MSVC, Buffer Security Check (/GS) is on by default.
5883 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005884 /*Default=*/true)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005885 CmdArgs.push_back("-stack-protector");
5886 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5887 }
5888
5889 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5890 if (Arg *DebugInfoArg =
5891 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5892 options::OPT_gline_tables_only)) {
5893 *EmitCodeView = true;
5894 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5895 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5896 else
5897 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +00005898 } else {
5899 *EmitCodeView = false;
5900 }
5901
5902 const Driver &D = getToolChain().getDriver();
5903 EHFlags EH = parseClangCLEHFlags(D, Args);
5904 if (EH.Synch || EH.Asynch) {
5905 if (types::isCXX(InputType))
5906 CmdArgs.push_back("-fcxx-exceptions");
5907 CmdArgs.push_back("-fexceptions");
5908 }
5909 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5910 CmdArgs.push_back("-fexternc-nounwind");
5911
5912 // /EP should expand to -E -P.
5913 if (Args.hasArg(options::OPT__SLASH_EP)) {
5914 CmdArgs.push_back("-E");
5915 CmdArgs.push_back("-P");
5916 }
5917
5918 unsigned VolatileOptionID;
5919 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5920 getToolChain().getArch() == llvm::Triple::x86)
5921 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5922 else
5923 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5924
5925 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5926 VolatileOptionID = A->getOption().getID();
5927
5928 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5929 CmdArgs.push_back("-fms-volatile");
5930
Takuto Ikuta302c6432018-11-03 06:45:00 +00005931 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5932 options::OPT__SLASH_Zc_dllexportInlines,
Takuto Ikuta245d9472018-11-13 04:14:09 +00005933 false)) {
5934 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5935 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5936 } else {
Takuto Ikuta302c6432018-11-03 06:45:00 +00005937 CmdArgs.push_back("-fno-dllexport-inlines");
Takuto Ikuta245d9472018-11-13 04:14:09 +00005938 }
5939 }
Takuto Ikuta302c6432018-11-03 06:45:00 +00005940
David L. Jonesf561aba2017-03-08 01:02:16 +00005941 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5942 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5943 if (MostGeneralArg && BestCaseArg)
5944 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5945 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5946
5947 if (MostGeneralArg) {
5948 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5949 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5950 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5951
5952 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5953 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5954 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5955 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5956 << FirstConflict->getAsString(Args)
5957 << SecondConflict->getAsString(Args);
5958
5959 if (SingleArg)
5960 CmdArgs.push_back("-fms-memptr-rep=single");
5961 else if (MultipleArg)
5962 CmdArgs.push_back("-fms-memptr-rep=multiple");
5963 else
5964 CmdArgs.push_back("-fms-memptr-rep=virtual");
5965 }
5966
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005967 // Parse the default calling convention options.
5968 if (Arg *CCArg =
5969 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005970 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5971 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005972 unsigned DCCOptId = CCArg->getOption().getID();
5973 const char *DCCFlag = nullptr;
5974 bool ArchSupported = true;
5975 llvm::Triple::ArchType Arch = getToolChain().getArch();
5976 switch (DCCOptId) {
5977 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005978 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005979 break;
5980 case options::OPT__SLASH_Gr:
5981 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005982 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005983 break;
5984 case options::OPT__SLASH_Gz:
5985 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005986 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005987 break;
5988 case options::OPT__SLASH_Gv:
5989 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005990 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005991 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005992 case options::OPT__SLASH_Gregcall:
5993 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5994 DCCFlag = "-fdefault-calling-conv=regcall";
5995 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005996 }
5997
5998 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5999 if (ArchSupported && DCCFlag)
6000 CmdArgs.push_back(DCCFlag);
6001 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006002
Nico Weber908b6972019-06-26 17:51:47 +00006003 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00006004
6005 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6006 CmdArgs.push_back("-fdiagnostics-format");
6007 if (Args.hasArg(options::OPT__SLASH_fallback))
6008 CmdArgs.push_back("msvc-fallback");
6009 else
6010 CmdArgs.push_back("msvc");
6011 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00006012
Hans Wennborga912e3e2018-08-10 09:49:21 +00006013 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
6014 SmallVector<StringRef, 1> SplitArgs;
6015 StringRef(A->getValue()).split(SplitArgs, ",");
6016 bool Instrument = false;
6017 bool NoChecks = false;
6018 for (StringRef Arg : SplitArgs) {
6019 if (Arg.equals_lower("cf"))
6020 Instrument = true;
6021 else if (Arg.equals_lower("cf-"))
6022 Instrument = false;
6023 else if (Arg.equals_lower("nochecks"))
6024 NoChecks = true;
6025 else if (Arg.equals_lower("nochecks-"))
6026 NoChecks = false;
6027 else
6028 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
6029 }
6030 // Currently there's no support emitting CFG instrumentation; the flag only
6031 // emits the table of address-taken functions.
6032 if (Instrument || NoChecks)
6033 CmdArgs.push_back("-cfguard");
6034 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006035}
6036
6037visualstudio::Compiler *Clang::getCLFallback() const {
6038 if (!CLFallback)
6039 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6040 return CLFallback.get();
6041}
6042
6043
6044const char *Clang::getBaseInputName(const ArgList &Args,
6045 const InputInfo &Input) {
6046 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6047}
6048
6049const char *Clang::getBaseInputStem(const ArgList &Args,
6050 const InputInfoList &Inputs) {
6051 const char *Str = getBaseInputName(Args, Inputs[0]);
6052
6053 if (const char *End = strrchr(Str, '.'))
6054 return Args.MakeArgString(std::string(Str, End));
6055
6056 return Str;
6057}
6058
6059const char *Clang::getDependencyFileName(const ArgList &Args,
6060 const InputInfoList &Inputs) {
6061 // FIXME: Think about this more.
David L. Jonesf561aba2017-03-08 01:02:16 +00006062
6063 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
Luke Cheesemanab9acda2019-09-13 13:15:35 +00006064 SmallString<128> OutputFilename(OutputOpt->getValue());
6065 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
6066 return Args.MakeArgString(OutputFilename);
David L. Jonesf561aba2017-03-08 01:02:16 +00006067 }
Luke Cheesemanab9acda2019-09-13 13:15:35 +00006068
Fangrui Song6fe3d362019-09-14 04:13:15 +00006069 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
David L. Jonesf561aba2017-03-08 01:02:16 +00006070}
6071
6072// Begin ClangAs
6073
6074void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6075 ArgStringList &CmdArgs) const {
6076 StringRef CPUName;
6077 StringRef ABIName;
6078 const llvm::Triple &Triple = getToolChain().getTriple();
6079 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6080
6081 CmdArgs.push_back("-target-abi");
6082 CmdArgs.push_back(ABIName.data());
6083}
6084
6085void ClangAs::AddX86TargetArgs(const ArgList &Args,
6086 ArgStringList &CmdArgs) const {
6087 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
6088 StringRef Value = A->getValue();
6089 if (Value == "intel" || Value == "att") {
6090 CmdArgs.push_back("-mllvm");
6091 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
6092 } else {
6093 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
6094 << A->getOption().getName() << Value;
6095 }
6096 }
6097}
6098
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006099void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
6100 ArgStringList &CmdArgs) const {
6101 const llvm::Triple &Triple = getToolChain().getTriple();
6102 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
6103
6104 CmdArgs.push_back("-target-abi");
6105 CmdArgs.push_back(ABIName.data());
6106}
6107
David L. Jonesf561aba2017-03-08 01:02:16 +00006108void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6109 const InputInfo &Output, const InputInfoList &Inputs,
6110 const ArgList &Args,
6111 const char *LinkingOutput) const {
6112 ArgStringList CmdArgs;
6113
6114 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6115 const InputInfo &Input = Inputs[0];
6116
Martin Storsjob547ef22018-10-26 08:33:29 +00006117 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00006118 const std::string &TripleStr = Triple.getTriple();
Martin Storsjob547ef22018-10-26 08:33:29 +00006119 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00006120
6121 // Don't warn about "clang -w -c foo.s"
6122 Args.ClaimAllArgs(options::OPT_w);
6123 // and "clang -emit-llvm -c foo.s"
6124 Args.ClaimAllArgs(options::OPT_emit_llvm);
6125
6126 claimNoWarnArgs(Args);
6127
6128 // Invoke ourselves in -cc1as mode.
6129 //
6130 // FIXME: Implement custom jobs for internal actions.
6131 CmdArgs.push_back("-cc1as");
6132
6133 // Add the "effective" target triple.
6134 CmdArgs.push_back("-triple");
6135 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6136
6137 // Set the output mode, we currently only expect to be used as a real
6138 // assembler.
6139 CmdArgs.push_back("-filetype");
6140 CmdArgs.push_back("obj");
6141
6142 // Set the main file name, so that debug info works even with
6143 // -save-temps or preprocessed assembly.
6144 CmdArgs.push_back("-main-file-name");
6145 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6146
6147 // Add the target cpu
6148 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6149 if (!CPU.empty()) {
6150 CmdArgs.push_back("-target-cpu");
6151 CmdArgs.push_back(Args.MakeArgString(CPU));
6152 }
6153
6154 // Add the target features
6155 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6156
6157 // Ignore explicit -force_cpusubtype_ALL option.
6158 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6159
6160 // Pass along any -I options so we get proper .include search paths.
6161 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6162
6163 // Determine the original source input.
6164 const Action *SourceAction = &JA;
6165 while (SourceAction->getKind() != Action::InputClass) {
6166 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6167 SourceAction = SourceAction->getInputs()[0];
6168 }
6169
6170 // Forward -g and handle debug info related flags, assuming we are dealing
6171 // with an actual assembly file.
6172 bool WantDebug = false;
6173 unsigned DwarfVersion = 0;
6174 Args.ClaimAllArgs(options::OPT_g_Group);
6175 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6176 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6177 !A->getOption().matches(options::OPT_ggdb0);
6178 if (WantDebug)
6179 DwarfVersion = DwarfVersionNum(A->getSpelling());
6180 }
6181 if (DwarfVersion == 0)
6182 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6183
6184 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6185
6186 if (SourceAction->getType() == types::TY_Asm ||
6187 SourceAction->getType() == types::TY_PP_Asm) {
6188 // You might think that it would be ok to set DebugInfoKind outside of
6189 // the guard for source type, however there is a test which asserts
6190 // that some assembler invocation receives no -debug-info-kind,
6191 // and it's not clear whether that test is just overly restrictive.
6192 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6193 : codegenoptions::NoDebugInfo);
6194 // Add the -fdebug-compilation-dir flag if needed.
Hans Wennborg999f8a72019-09-05 08:43:00 +00006195 addDebugCompDirArg(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00006196
Paul Robinson9b292b42018-07-10 15:15:24 +00006197 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6198
David L. Jonesf561aba2017-03-08 01:02:16 +00006199 // Set the AT_producer to the clang version when using the integrated
6200 // assembler on assembly source files.
6201 CmdArgs.push_back("-dwarf-debug-producer");
6202 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6203
6204 // And pass along -I options
6205 Args.AddAllArgs(CmdArgs, options::OPT_I);
6206 }
6207 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6208 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00006209 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00006210
David L. Jonesf561aba2017-03-08 01:02:16 +00006211
6212 // Handle -fPIC et al -- the relocation-model affects the assembler
6213 // for some targets.
6214 llvm::Reloc::Model RelocationModel;
6215 unsigned PICLevel;
6216 bool IsPIE;
6217 std::tie(RelocationModel, PICLevel, IsPIE) =
6218 ParsePICArgs(getToolChain(), Args);
6219
6220 const char *RMName = RelocationModelName(RelocationModel);
6221 if (RMName) {
6222 CmdArgs.push_back("-mrelocation-model");
6223 CmdArgs.push_back(RMName);
6224 }
6225
6226 // Optionally embed the -cc1as level arguments into the debug info, for build
6227 // analysis.
6228 if (getToolChain().UseDwarfDebugFlags()) {
6229 ArgStringList OriginalArgs;
6230 for (const auto &Arg : Args)
6231 Arg->render(Args, OriginalArgs);
6232
6233 SmallString<256> Flags;
6234 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6235 Flags += Exec;
6236 for (const char *OriginalArg : OriginalArgs) {
6237 SmallString<128> EscapedArg;
6238 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6239 Flags += " ";
6240 Flags += EscapedArg;
6241 }
6242 CmdArgs.push_back("-dwarf-debug-flags");
6243 CmdArgs.push_back(Args.MakeArgString(Flags));
6244 }
6245
6246 // FIXME: Add -static support, once we have it.
6247
6248 // Add target specific flags.
6249 switch (getToolChain().getArch()) {
6250 default:
6251 break;
6252
6253 case llvm::Triple::mips:
6254 case llvm::Triple::mipsel:
6255 case llvm::Triple::mips64:
6256 case llvm::Triple::mips64el:
6257 AddMIPSTargetArgs(Args, CmdArgs);
6258 break;
6259
6260 case llvm::Triple::x86:
6261 case llvm::Triple::x86_64:
6262 AddX86TargetArgs(Args, CmdArgs);
6263 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00006264
6265 case llvm::Triple::arm:
6266 case llvm::Triple::armeb:
6267 case llvm::Triple::thumb:
6268 case llvm::Triple::thumbeb:
6269 // This isn't in AddARMTargetArgs because we want to do this for assembly
6270 // only, not C/C++.
6271 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6272 options::OPT_mno_default_build_attributes, true)) {
6273 CmdArgs.push_back("-mllvm");
6274 CmdArgs.push_back("-arm-add-build-attributes");
6275 }
6276 break;
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006277
6278 case llvm::Triple::riscv32:
6279 case llvm::Triple::riscv64:
6280 AddRISCVTargetArgs(Args, CmdArgs);
6281 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00006282 }
6283
6284 // Consume all the warning flags. Usually this would be handled more
6285 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6286 // doesn't handle that so rather than warning about unused flags that are
6287 // actually used, we'll lie by omission instead.
6288 // FIXME: Stop lying and consume only the appropriate driver flags
6289 Args.ClaimAllArgs(options::OPT_W_Group);
6290
6291 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6292 getToolChain().getDriver());
6293
6294 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6295
6296 assert(Output.isFilename() && "Unexpected lipo output.");
6297 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00006298 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006299
Petr Hosekd3265352018-10-15 21:30:32 +00006300 const llvm::Triple &T = getToolChain().getTriple();
George Rimar91829ee2018-11-14 09:22:16 +00006301 Arg *A;
Fangrui Songee957e02019-03-28 08:24:00 +00006302 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6303 T.isOSBinFormatELF()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00006304 CmdArgs.push_back("-split-dwarf-output");
George Rimar36d71da2019-03-27 11:00:03 +00006305 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
Peter Collingbourne91d02842018-05-22 18:52:37 +00006306 }
6307
David L. Jonesf561aba2017-03-08 01:02:16 +00006308 assert(Input.isFilename() && "Invalid input.");
Martin Storsjob547ef22018-10-26 08:33:29 +00006309 CmdArgs.push_back(Input.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006310
6311 const char *Exec = getToolChain().getDriver().getClangProgramPath();
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00006312 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00006313}
6314
6315// Begin OffloadBundler
6316
6317void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6318 const InputInfo &Output,
6319 const InputInfoList &Inputs,
6320 const llvm::opt::ArgList &TCArgs,
6321 const char *LinkingOutput) const {
6322 // The version with only one output is expected to refer to a bundling job.
6323 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6324
6325 // The bundling command looks like this:
6326 // clang-offload-bundler -type=bc
6327 // -targets=host-triple,openmp-triple1,openmp-triple2
6328 // -outputs=input_file
6329 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6330
6331 ArgStringList CmdArgs;
6332
6333 // Get the type.
6334 CmdArgs.push_back(TCArgs.MakeArgString(
6335 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6336
6337 assert(JA.getInputs().size() == Inputs.size() &&
6338 "Not have inputs for all dependence actions??");
6339
6340 // Get the targets.
6341 SmallString<128> Triples;
6342 Triples += "-targets=";
6343 for (unsigned I = 0; I < Inputs.size(); ++I) {
6344 if (I)
6345 Triples += ',';
6346
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006347 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00006348 Action::OffloadKind CurKind = Action::OFK_Host;
6349 const ToolChain *CurTC = &getToolChain();
6350 const Action *CurDep = JA.getInputs()[I];
6351
6352 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006353 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00006354 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006355 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00006356 CurKind = A->getOffloadingDeviceKind();
6357 CurTC = TC;
6358 });
6359 }
6360 Triples += Action::GetOffloadKindName(CurKind);
6361 Triples += '-';
6362 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006363 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6364 Triples += '-';
6365 Triples += CurDep->getOffloadingArch();
6366 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006367 }
6368 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6369
6370 // Get bundled file command.
6371 CmdArgs.push_back(
6372 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6373
6374 // Get unbundled files command.
6375 SmallString<128> UB;
6376 UB += "-inputs=";
6377 for (unsigned I = 0; I < Inputs.size(); ++I) {
6378 if (I)
6379 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006380
6381 // Find ToolChain for this input.
6382 const ToolChain *CurTC = &getToolChain();
6383 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6384 CurTC = nullptr;
6385 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6386 assert(CurTC == nullptr && "Expected one dependence!");
6387 CurTC = TC;
6388 });
6389 }
6390 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006391 }
6392 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6393
6394 // All the inputs are encoded as commands.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00006395 C.addCommand(std::make_unique<Command>(
David L. Jonesf561aba2017-03-08 01:02:16 +00006396 JA, *this,
6397 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6398 CmdArgs, None));
6399}
6400
6401void OffloadBundler::ConstructJobMultipleOutputs(
6402 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6403 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6404 const char *LinkingOutput) const {
6405 // The version with multiple outputs is expected to refer to a unbundling job.
6406 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6407
6408 // The unbundling command looks like this:
6409 // clang-offload-bundler -type=bc
6410 // -targets=host-triple,openmp-triple1,openmp-triple2
6411 // -inputs=input_file
6412 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6413 // -unbundle
6414
6415 ArgStringList CmdArgs;
6416
6417 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6418 InputInfo Input = Inputs.front();
6419
6420 // Get the type.
6421 CmdArgs.push_back(TCArgs.MakeArgString(
6422 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6423
6424 // Get the targets.
6425 SmallString<128> Triples;
6426 Triples += "-targets=";
6427 auto DepInfo = UA.getDependentActionsInfo();
6428 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6429 if (I)
6430 Triples += ',';
6431
6432 auto &Dep = DepInfo[I];
6433 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6434 Triples += '-';
6435 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006436 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6437 !Dep.DependentBoundArch.empty()) {
6438 Triples += '-';
6439 Triples += Dep.DependentBoundArch;
6440 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006441 }
6442
6443 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6444
6445 // Get bundled file command.
6446 CmdArgs.push_back(
6447 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6448
6449 // Get unbundled files command.
6450 SmallString<128> UB;
6451 UB += "-outputs=";
6452 for (unsigned I = 0; I < Outputs.size(); ++I) {
6453 if (I)
6454 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006455 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006456 }
6457 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6458 CmdArgs.push_back("-unbundle");
6459
6460 // All the inputs are encoded as commands.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00006461 C.addCommand(std::make_unique<Command>(
David L. Jonesf561aba2017-03-08 01:02:16 +00006462 JA, *this,
6463 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6464 CmdArgs, None));
6465}