blob: bac6cff62f0b44a9d46e9d540a2639708ee2aecc [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:
339 riscv::getRISCVTargetFeatures(D, Args, Features);
340 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) {
Fangrui Songdc039662019-07-12 02:01:51 +0000583 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
584 options::OPT_fno_omit_frame_pointer);
585 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
586 bool NoOmitFP =
587 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
588 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
589 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
590 if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
591 options::OPT_mno_omit_leaf_frame_pointer,
592 Triple.isPS4CPU()))
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000593 return CodeGenOptions::FramePointerKind::NonLeaf;
594 return CodeGenOptions::FramePointerKind::All;
Fangrui Songdc039662019-07-12 02:01:51 +0000595 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000596 return CodeGenOptions::FramePointerKind::None;
David L. Jonesf561aba2017-03-08 01:02:16 +0000597}
598
599/// Add a CC1 option to specify the debug compilation directory.
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000600static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
601 const llvm::vfs::FileSystem &VFS) {
Nico Weber37b75332019-06-17 12:10:40 +0000602 if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
603 CmdArgs.push_back("-fdebug-compilation-dir");
604 CmdArgs.push_back(A->getValue());
605 } else if (llvm::ErrorOr<std::string> CWD =
606 VFS.getCurrentWorkingDirectory()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000607 CmdArgs.push_back("-fdebug-compilation-dir");
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000608 CmdArgs.push_back(Args.MakeArgString(*CWD));
David L. Jonesf561aba2017-03-08 01:02:16 +0000609 }
610}
611
Paul Robinson9b292b42018-07-10 15:15:24 +0000612/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
613static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
614 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
615 StringRef Map = A->getValue();
616 if (Map.find('=') == StringRef::npos)
617 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
618 else
619 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
620 A->claim();
621 }
622}
623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000624/// Vectorize at all optimization levels greater than 1 except for -Oz.
Nico Weber37b75332019-06-17 12:10:40 +0000625/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
626/// enabled.
David L. Jonesf561aba2017-03-08 01:02:16 +0000627static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
628 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
629 if (A->getOption().matches(options::OPT_O4) ||
630 A->getOption().matches(options::OPT_Ofast))
631 return true;
632
633 if (A->getOption().matches(options::OPT_O0))
634 return false;
635
636 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
637
638 // Vectorize -Os.
639 StringRef S(A->getValue());
640 if (S == "s")
641 return true;
642
643 // Don't vectorize -Oz, unless it's the slp vectorizer.
644 if (S == "z")
645 return isSlpVec;
646
647 unsigned OptLevel = 0;
648 if (S.getAsInteger(10, OptLevel))
649 return false;
650
651 return OptLevel > 1;
652 }
653
654 return false;
655}
656
657/// Add -x lang to \p CmdArgs for \p Input.
658static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
659 ArgStringList &CmdArgs) {
660 // When using -verify-pch, we don't want to provide the type
661 // 'precompiled-header' if it was inferred from the file extension
662 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
663 return;
664
665 CmdArgs.push_back("-x");
666 if (Args.hasArg(options::OPT_rewrite_objc))
667 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000668 else {
669 // Map the driver type to the frontend type. This is mostly an identity
670 // mapping, except that the distinction between module interface units
671 // and other source files does not exist at the frontend layer.
672 const char *ClangType;
673 switch (Input.getType()) {
674 case types::TY_CXXModule:
675 ClangType = "c++";
676 break;
677 case types::TY_PP_CXXModule:
678 ClangType = "c++-cpp-output";
679 break;
680 default:
681 ClangType = types::getTypeName(Input.getType());
682 break;
683 }
684 CmdArgs.push_back(ClangType);
685 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000686}
687
688static void appendUserToPath(SmallVectorImpl<char> &Result) {
689#ifdef LLVM_ON_UNIX
690 const char *Username = getenv("LOGNAME");
691#else
692 const char *Username = getenv("USERNAME");
693#endif
694 if (Username) {
695 // Validate that LoginName can be used in a path, and get its length.
696 size_t Len = 0;
697 for (const char *P = Username; *P; ++P, ++Len) {
698 if (!clang::isAlphanumeric(*P) && *P != '_') {
699 Username = nullptr;
700 break;
701 }
702 }
703
704 if (Username && Len > 0) {
705 Result.append(Username, Username + Len);
706 return;
707 }
708 }
709
710// Fallback to user id.
711#ifdef LLVM_ON_UNIX
712 std::string UID = llvm::utostr(getuid());
713#else
714 // FIXME: Windows seems to have an 'SID' that might work.
715 std::string UID = "9999";
716#endif
717 Result.append(UID.begin(), UID.end());
718}
719
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000720static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
721 const Driver &D, const InputInfo &Output,
722 const ArgList &Args,
David L. Jonesf561aba2017-03-08 01:02:16 +0000723 ArgStringList &CmdArgs) {
724
725 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
726 options::OPT_fprofile_generate_EQ,
727 options::OPT_fno_profile_generate);
728 if (PGOGenerateArg &&
729 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
730 PGOGenerateArg = nullptr;
731
Rong Xua4a09b22019-03-04 20:21:31 +0000732 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
733 options::OPT_fcs_profile_generate_EQ,
734 options::OPT_fno_profile_generate);
735 if (CSPGOGenerateArg &&
736 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
737 CSPGOGenerateArg = nullptr;
738
David L. Jonesf561aba2017-03-08 01:02:16 +0000739 auto *ProfileGenerateArg = Args.getLastArg(
740 options::OPT_fprofile_instr_generate,
741 options::OPT_fprofile_instr_generate_EQ,
742 options::OPT_fno_profile_instr_generate);
743 if (ProfileGenerateArg &&
744 ProfileGenerateArg->getOption().matches(
745 options::OPT_fno_profile_instr_generate))
746 ProfileGenerateArg = nullptr;
747
748 if (PGOGenerateArg && ProfileGenerateArg)
749 D.Diag(diag::err_drv_argument_not_allowed_with)
750 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
751
752 auto *ProfileUseArg = getLastProfileUseArg(Args);
753
754 if (PGOGenerateArg && ProfileUseArg)
755 D.Diag(diag::err_drv_argument_not_allowed_with)
756 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
757
758 if (ProfileGenerateArg && ProfileUseArg)
759 D.Diag(diag::err_drv_argument_not_allowed_with)
760 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
761
Rong Xua4a09b22019-03-04 20:21:31 +0000762 if (CSPGOGenerateArg && PGOGenerateArg)
763 D.Diag(diag::err_drv_argument_not_allowed_with)
764 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
765
David L. Jonesf561aba2017-03-08 01:02:16 +0000766 if (ProfileGenerateArg) {
767 if (ProfileGenerateArg->getOption().matches(
768 options::OPT_fprofile_instr_generate_EQ))
769 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
770 ProfileGenerateArg->getValue()));
771 // The default is to use Clang Instrumentation.
772 CmdArgs.push_back("-fprofile-instrument=clang");
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000773 if (TC.getTriple().isWindowsMSVCEnvironment()) {
774 // Add dependent lib for clang_rt.profile
775 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
776 TC.getCompilerRT(Args, "profile")));
777 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000778 }
779
Rong Xua4a09b22019-03-04 20:21:31 +0000780 Arg *PGOGenArg = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +0000781 if (PGOGenerateArg) {
Rong Xua4a09b22019-03-04 20:21:31 +0000782 assert(!CSPGOGenerateArg);
783 PGOGenArg = PGOGenerateArg;
David L. Jonesf561aba2017-03-08 01:02:16 +0000784 CmdArgs.push_back("-fprofile-instrument=llvm");
Rong Xua4a09b22019-03-04 20:21:31 +0000785 }
786 if (CSPGOGenerateArg) {
787 assert(!PGOGenerateArg);
788 PGOGenArg = CSPGOGenerateArg;
789 CmdArgs.push_back("-fprofile-instrument=csllvm");
790 }
791 if (PGOGenArg) {
Russell Gallop72fea1d2019-05-22 10:06:49 +0000792 if (TC.getTriple().isWindowsMSVCEnvironment()) {
793 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
794 TC.getCompilerRT(Args, "profile")));
795 }
Rong Xua4a09b22019-03-04 20:21:31 +0000796 if (PGOGenArg->getOption().matches(
797 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
798 : options::OPT_fcs_profile_generate_EQ)) {
799 SmallString<128> Path(PGOGenArg->getValue());
David L. Jonesf561aba2017-03-08 01:02:16 +0000800 llvm::sys::path::append(Path, "default_%m.profraw");
801 CmdArgs.push_back(
802 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
803 }
804 }
805
806 if (ProfileUseArg) {
807 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
808 CmdArgs.push_back(Args.MakeArgString(
809 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
810 else if ((ProfileUseArg->getOption().matches(
811 options::OPT_fprofile_use_EQ) ||
812 ProfileUseArg->getOption().matches(
813 options::OPT_fprofile_instr_use))) {
814 SmallString<128> Path(
815 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
816 if (Path.empty() || llvm::sys::fs::is_directory(Path))
817 llvm::sys::path::append(Path, "default.profdata");
818 CmdArgs.push_back(
819 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
820 }
821 }
822
823 if (Args.hasArg(options::OPT_ftest_coverage) ||
824 Args.hasArg(options::OPT_coverage))
825 CmdArgs.push_back("-femit-coverage-notes");
826 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
827 false) ||
828 Args.hasArg(options::OPT_coverage))
829 CmdArgs.push_back("-femit-coverage-data");
830
831 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000832 options::OPT_fno_coverage_mapping, false)) {
833 if (!ProfileGenerateArg)
834 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
835 << "-fcoverage-mapping"
836 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000837
David L. Jonesf561aba2017-03-08 01:02:16 +0000838 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000839 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000840
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000841 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
842 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
843 if (!Args.hasArg(options::OPT_coverage))
844 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
845 << "-fprofile-exclude-files="
846 << "--coverage";
847
848 StringRef v = Arg->getValue();
849 CmdArgs.push_back(
850 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
851 }
852
853 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
854 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
855 if (!Args.hasArg(options::OPT_coverage))
856 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
857 << "-fprofile-filter-files="
858 << "--coverage";
859
860 StringRef v = Arg->getValue();
861 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
862 }
863
David L. Jonesf561aba2017-03-08 01:02:16 +0000864 if (C.getArgs().hasArg(options::OPT_c) ||
865 C.getArgs().hasArg(options::OPT_S)) {
866 if (Output.isFilename()) {
867 CmdArgs.push_back("-coverage-notes-file");
868 SmallString<128> OutputFilename;
869 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
870 OutputFilename = FinalOutput->getValue();
871 else
872 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
873 SmallString<128> CoverageFilename = OutputFilename;
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000874 if (llvm::sys::path::is_relative(CoverageFilename))
875 (void)D.getVFS().makeAbsolute(CoverageFilename);
David L. Jonesf561aba2017-03-08 01:02:16 +0000876 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
877 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
878
879 // Leave -fprofile-dir= an unused argument unless .gcda emission is
880 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
881 // the flag used. There is no -fno-profile-dir, so the user has no
882 // targeted way to suppress the warning.
883 if (Args.hasArg(options::OPT_fprofile_arcs) ||
884 Args.hasArg(options::OPT_coverage)) {
885 CmdArgs.push_back("-coverage-data-file");
886 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
887 CoverageFilename = FProfileDir->getValue();
888 llvm::sys::path::append(CoverageFilename, OutputFilename);
889 }
890 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
891 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
892 }
893 }
894 }
895}
896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000897/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000898static bool ContainsCompileAction(const Action *A) {
899 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
900 return true;
901
902 for (const auto &AI : A->inputs())
903 if (ContainsCompileAction(AI))
904 return true;
905
906 return false;
907}
908
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000909/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000910/// This is done by default when compiling non-assembler source with -O0.
911static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
912 bool RelaxDefault = true;
913
914 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
915 RelaxDefault = A->getOption().matches(options::OPT_O0);
916
917 if (RelaxDefault) {
918 RelaxDefault = false;
919 for (const auto &Act : C.getActions()) {
920 if (ContainsCompileAction(Act)) {
921 RelaxDefault = true;
922 break;
923 }
924 }
925 }
926
927 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
928 RelaxDefault);
929}
930
931// Extract the integer N from a string spelled "-dwarf-N", returning 0
932// on mismatch. The StringRef input (rather than an Arg) allows
933// for use by the "-Xassembler" option parser.
934static unsigned DwarfVersionNum(StringRef ArgValue) {
935 return llvm::StringSwitch<unsigned>(ArgValue)
936 .Case("-gdwarf-2", 2)
937 .Case("-gdwarf-3", 3)
938 .Case("-gdwarf-4", 4)
939 .Case("-gdwarf-5", 5)
940 .Default(0);
941}
942
943static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
944 codegenoptions::DebugInfoKind DebugInfoKind,
945 unsigned DwarfVersion,
946 llvm::DebuggerKind DebuggerTuning) {
947 switch (DebugInfoKind) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000948 case codegenoptions::DebugDirectivesOnly:
949 CmdArgs.push_back("-debug-info-kind=line-directives-only");
950 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000951 case codegenoptions::DebugLineTablesOnly:
952 CmdArgs.push_back("-debug-info-kind=line-tables-only");
953 break;
954 case codegenoptions::LimitedDebugInfo:
955 CmdArgs.push_back("-debug-info-kind=limited");
956 break;
957 case codegenoptions::FullDebugInfo:
958 CmdArgs.push_back("-debug-info-kind=standalone");
959 break;
960 default:
961 break;
962 }
963 if (DwarfVersion > 0)
964 CmdArgs.push_back(
965 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
966 switch (DebuggerTuning) {
967 case llvm::DebuggerKind::GDB:
968 CmdArgs.push_back("-debugger-tuning=gdb");
969 break;
970 case llvm::DebuggerKind::LLDB:
971 CmdArgs.push_back("-debugger-tuning=lldb");
972 break;
973 case llvm::DebuggerKind::SCE:
974 CmdArgs.push_back("-debugger-tuning=sce");
975 break;
976 default:
977 break;
978 }
979}
980
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000981static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
982 const Driver &D, const ToolChain &TC) {
983 assert(A && "Expected non-nullptr argument.");
984 if (TC.supportsDebugInfoOption(A))
985 return true;
986 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
987 << A->getAsString(Args) << TC.getTripleString();
988 return false;
989}
990
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000991static void RenderDebugInfoCompressionArgs(const ArgList &Args,
992 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000993 const Driver &D,
994 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000995 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
996 if (!A)
997 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000998 if (checkDebugInfoOption(A, Args, D, TC)) {
999 if (A->getOption().getID() == options::OPT_gz) {
1000 if (llvm::zlib::isAvailable())
Fangrui Songbaabc872019-05-11 01:14:50 +00001001 CmdArgs.push_back("--compress-debug-sections");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001002 else
1003 D.Diag(diag::warn_debug_compression_unavailable);
1004 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001005 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001006
1007 StringRef Value = A->getValue();
1008 if (Value == "none") {
Fangrui Songbaabc872019-05-11 01:14:50 +00001009 CmdArgs.push_back("--compress-debug-sections=none");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001010 } else if (Value == "zlib" || Value == "zlib-gnu") {
1011 if (llvm::zlib::isAvailable()) {
1012 CmdArgs.push_back(
Fangrui Songbaabc872019-05-11 01:14:50 +00001013 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001014 } else {
1015 D.Diag(diag::warn_debug_compression_unavailable);
1016 }
1017 } else {
1018 D.Diag(diag::err_drv_unsupported_option_argument)
1019 << A->getOption().getName() << Value;
1020 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001021 }
1022}
1023
David L. Jonesf561aba2017-03-08 01:02:16 +00001024static const char *RelocationModelName(llvm::Reloc::Model Model) {
1025 switch (Model) {
1026 case llvm::Reloc::Static:
1027 return "static";
1028 case llvm::Reloc::PIC_:
1029 return "pic";
1030 case llvm::Reloc::DynamicNoPIC:
1031 return "dynamic-no-pic";
1032 case llvm::Reloc::ROPI:
1033 return "ropi";
1034 case llvm::Reloc::RWPI:
1035 return "rwpi";
1036 case llvm::Reloc::ROPI_RWPI:
1037 return "ropi-rwpi";
1038 }
1039 llvm_unreachable("Unknown Reloc::Model kind");
1040}
1041
1042void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1043 const Driver &D, const ArgList &Args,
1044 ArgStringList &CmdArgs,
1045 const InputInfo &Output,
1046 const InputInfoList &Inputs) const {
1047 Arg *A;
1048 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1049
1050 CheckPreprocessingOptions(D, Args);
1051
1052 Args.AddLastArg(CmdArgs, options::OPT_C);
1053 Args.AddLastArg(CmdArgs, options::OPT_CC);
1054
1055 // Handle dependency file generation.
1056 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1057 (A = Args.getLastArg(options::OPT_MD)) ||
1058 (A = Args.getLastArg(options::OPT_MMD))) {
1059 // Determine the output location.
1060 const char *DepFile;
1061 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1062 DepFile = MF->getValue();
1063 C.addFailureResultFile(DepFile, &JA);
1064 } else if (Output.getType() == types::TY_Dependencies) {
1065 DepFile = Output.getFilename();
1066 } else if (A->getOption().matches(options::OPT_M) ||
1067 A->getOption().matches(options::OPT_MM)) {
1068 DepFile = "-";
1069 } else {
1070 DepFile = getDependencyFileName(Args, Inputs);
1071 C.addFailureResultFile(DepFile, &JA);
1072 }
1073 CmdArgs.push_back("-dependency-file");
1074 CmdArgs.push_back(DepFile);
1075
1076 // Add a default target if one wasn't specified.
1077 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1078 const char *DepTarget;
1079
1080 // If user provided -o, that is the dependency target, except
1081 // when we are only generating a dependency file.
1082 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1083 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1084 DepTarget = OutputOpt->getValue();
1085 } else {
1086 // Otherwise derive from the base input.
1087 //
1088 // FIXME: This should use the computed output file location.
1089 SmallString<128> P(Inputs[0].getBaseInput());
1090 llvm::sys::path::replace_extension(P, "o");
1091 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1092 }
1093
Yuka Takahashicdb53482017-06-16 16:01:13 +00001094 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1095 CmdArgs.push_back("-w");
1096 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001097 CmdArgs.push_back("-MT");
1098 SmallString<128> Quoted;
1099 QuoteTarget(DepTarget, Quoted);
1100 CmdArgs.push_back(Args.MakeArgString(Quoted));
1101 }
1102
1103 if (A->getOption().matches(options::OPT_M) ||
1104 A->getOption().matches(options::OPT_MD))
1105 CmdArgs.push_back("-sys-header-deps");
1106 if ((isa<PrecompileJobAction>(JA) &&
1107 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1108 Args.hasArg(options::OPT_fmodule_file_deps))
1109 CmdArgs.push_back("-module-file-deps");
1110 }
1111
1112 if (Args.hasArg(options::OPT_MG)) {
1113 if (!A || A->getOption().matches(options::OPT_MD) ||
1114 A->getOption().matches(options::OPT_MMD))
1115 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1116 CmdArgs.push_back("-MG");
1117 }
1118
1119 Args.AddLastArg(CmdArgs, options::OPT_MP);
1120 Args.AddLastArg(CmdArgs, options::OPT_MV);
1121
1122 // Convert all -MQ <target> args to -MT <quoted target>
1123 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1124 A->claim();
1125
1126 if (A->getOption().matches(options::OPT_MQ)) {
1127 CmdArgs.push_back("-MT");
1128 SmallString<128> Quoted;
1129 QuoteTarget(A->getValue(), Quoted);
1130 CmdArgs.push_back(Args.MakeArgString(Quoted));
1131
1132 // -MT flag - no change
1133 } else {
1134 A->render(Args, CmdArgs);
1135 }
1136 }
1137
1138 // Add offload include arguments specific for CUDA. This must happen before
1139 // we -I or -include anything else, because we must pick up the CUDA headers
1140 // from the particular CUDA installation, rather than from e.g.
1141 // /usr/local/include.
1142 if (JA.isOffloading(Action::OFK_Cuda))
1143 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1144
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001145 // If we are offloading to a target via OpenMP we need to include the
1146 // openmp_wrappers folder which contains alternative system headers.
1147 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1148 getToolChain().getTriple().isNVPTX()){
1149 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1150 // Add openmp_wrappers/* to our system include path. This lets us wrap
1151 // standard library headers.
1152 SmallString<128> P(D.ResourceDir);
1153 llvm::sys::path::append(P, "include");
1154 llvm::sys::path::append(P, "openmp_wrappers");
1155 CmdArgs.push_back("-internal-isystem");
1156 CmdArgs.push_back(Args.MakeArgString(P));
1157 }
1158
1159 CmdArgs.push_back("-include");
Gheorghe-Teodor Bercea94695712019-05-13 22:11:44 +00001160 CmdArgs.push_back("__clang_openmp_math_declares.h");
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001161 }
1162
David L. Jonesf561aba2017-03-08 01:02:16 +00001163 // Add -i* options, and automatically translate to
1164 // -include-pch/-include-pth for transparent PCH support. It's
1165 // wonky, but we include looking for .gch so we can support seamless
1166 // replacement into a build system already set up to be generating
1167 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001168
1169 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001170 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1171 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001172 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1173 JA.getKind() <= Action::AssembleJobClass) {
1174 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001175 }
Erich Keane76675de2018-07-05 17:22:13 +00001176 if (YcArg || YuArg) {
1177 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1178 if (!isa<PrecompileJobAction>(JA)) {
1179 CmdArgs.push_back("-include-pch");
Mike Rice58df1af2018-09-11 17:10:44 +00001180 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1181 C, !ThroughHeader.empty()
1182 ? ThroughHeader
1183 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
Erich Keane76675de2018-07-05 17:22:13 +00001184 }
Mike Rice58df1af2018-09-11 17:10:44 +00001185
1186 if (ThroughHeader.empty()) {
1187 CmdArgs.push_back(Args.MakeArgString(
1188 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1189 } else {
1190 CmdArgs.push_back(
1191 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1192 }
Erich Keane76675de2018-07-05 17:22:13 +00001193 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001194 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001195
1196 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001197 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001198 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001199 // Handling of gcc-style gch precompiled headers.
1200 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1201 RenderedImplicitInclude = true;
1202
David L. Jonesf561aba2017-03-08 01:02:16 +00001203 bool FoundPCH = false;
1204 SmallString<128> P(A->getValue());
1205 // We want the files to have a name like foo.h.pch. Add a dummy extension
1206 // so that replace_extension does the right thing.
1207 P += ".dummy";
Erich Keane0a6b5b62018-12-04 14:34:09 +00001208 llvm::sys::path::replace_extension(P, "pch");
1209 if (llvm::sys::fs::exists(P))
1210 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001211
1212 if (!FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001213 llvm::sys::path::replace_extension(P, "gch");
1214 if (llvm::sys::fs::exists(P)) {
Erich Keane0a6b5b62018-12-04 14:34:09 +00001215 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001216 }
1217 }
1218
Erich Keane0a6b5b62018-12-04 14:34:09 +00001219 if (FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001220 if (IsFirstImplicitInclude) {
1221 A->claim();
Erich Keane0a6b5b62018-12-04 14:34:09 +00001222 CmdArgs.push_back("-include-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00001223 CmdArgs.push_back(Args.MakeArgString(P));
1224 continue;
1225 } else {
1226 // Ignore the PCH if not first on command line and emit warning.
1227 D.Diag(diag::warn_drv_pch_not_first_include) << P
1228 << A->getAsString(Args);
1229 }
1230 }
1231 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1232 // Handling of paths which must come late. These entries are handled by
1233 // the toolchain itself after the resource dir is inserted in the right
1234 // search order.
1235 // Do not claim the argument so that the use of the argument does not
1236 // silently go unnoticed on toolchains which do not honour the option.
1237 continue;
Shoaib Meenaib50e8c52019-08-06 06:48:43 +00001238 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1239 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1240 continue;
David L. Jonesf561aba2017-03-08 01:02:16 +00001241 }
1242
1243 // Not translated, render as usual.
1244 A->claim();
1245 A->render(Args, CmdArgs);
1246 }
1247
1248 Args.AddAllArgs(CmdArgs,
1249 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1250 options::OPT_F, options::OPT_index_header_map});
1251
1252 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1253
1254 // FIXME: There is a very unfortunate problem here, some troubled
1255 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1256 // really support that we would have to parse and then translate
1257 // those options. :(
1258 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1259 options::OPT_Xpreprocessor);
1260
1261 // -I- is a deprecated GCC feature, reject it.
1262 if (Arg *A = Args.getLastArg(options::OPT_I_))
1263 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1264
1265 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1266 // -isysroot to the CC1 invocation.
1267 StringRef sysroot = C.getSysRoot();
1268 if (sysroot != "") {
1269 if (!Args.hasArg(options::OPT_isysroot)) {
1270 CmdArgs.push_back("-isysroot");
1271 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1272 }
1273 }
1274
1275 // Parse additional include paths from environment variables.
1276 // FIXME: We should probably sink the logic for handling these from the
1277 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1278 // CPATH - included following the user specified includes (but prior to
1279 // builtin and standard includes).
1280 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1281 // C_INCLUDE_PATH - system includes enabled when compiling C.
1282 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1283 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1284 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1285 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1286 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1287 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1288 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1289
1290 // While adding the include arguments, we also attempt to retrieve the
1291 // arguments of related offloading toolchains or arguments that are specific
1292 // of an offloading programming model.
1293
1294 // Add C++ include arguments, if needed.
Shoaib Meenaib50e8c52019-08-06 06:48:43 +00001295 if (types::isCXX(Inputs[0].getType())) {
1296 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1297 forAllAssociatedToolChains(
1298 C, JA, getToolChain(),
1299 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1300 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1301 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1302 });
1303 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001304
1305 // Add system include arguments for all targets but IAMCU.
1306 if (!IsIAMCU)
1307 forAllAssociatedToolChains(C, JA, getToolChain(),
1308 [&Args, &CmdArgs](const ToolChain &TC) {
1309 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1310 });
1311 else {
1312 // For IAMCU add special include arguments.
1313 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1314 }
1315}
1316
1317// FIXME: Move to target hook.
1318static bool isSignedCharDefault(const llvm::Triple &Triple) {
1319 switch (Triple.getArch()) {
1320 default:
1321 return true;
1322
1323 case llvm::Triple::aarch64:
1324 case llvm::Triple::aarch64_be:
1325 case llvm::Triple::arm:
1326 case llvm::Triple::armeb:
1327 case llvm::Triple::thumb:
1328 case llvm::Triple::thumbeb:
1329 if (Triple.isOSDarwin() || Triple.isOSWindows())
1330 return true;
1331 return false;
1332
1333 case llvm::Triple::ppc:
1334 case llvm::Triple::ppc64:
1335 if (Triple.isOSDarwin())
1336 return true;
1337 return false;
1338
1339 case llvm::Triple::hexagon:
1340 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001341 case llvm::Triple::riscv32:
1342 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001343 case llvm::Triple::systemz:
1344 case llvm::Triple::xcore:
1345 return false;
1346 }
1347}
1348
1349static bool isNoCommonDefault(const llvm::Triple &Triple) {
1350 switch (Triple.getArch()) {
1351 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001352 if (Triple.isOSFuchsia())
1353 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001354 return false;
1355
1356 case llvm::Triple::xcore:
1357 case llvm::Triple::wasm32:
1358 case llvm::Triple::wasm64:
1359 return true;
1360 }
1361}
1362
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001363namespace {
1364void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1365 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001366 // Select the ABI to use.
1367 // FIXME: Support -meabi.
1368 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1369 const char *ABIName = nullptr;
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001370 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001371 ABIName = A->getValue();
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001372 } else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001373 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001374 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001375 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001376
David L. Jonesf561aba2017-03-08 01:02:16 +00001377 CmdArgs.push_back("-target-abi");
1378 CmdArgs.push_back(ABIName);
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001379}
1380}
1381
1382void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1383 ArgStringList &CmdArgs, bool KernelOrKext) const {
1384 RenderARMABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001385
1386 // Determine floating point ABI from the options & target defaults.
1387 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1388 if (ABI == arm::FloatABI::Soft) {
1389 // Floating point operations and argument passing are soft.
1390 // FIXME: This changes CPP defines, we need -target-soft-float.
1391 CmdArgs.push_back("-msoft-float");
1392 CmdArgs.push_back("-mfloat-abi");
1393 CmdArgs.push_back("soft");
1394 } else if (ABI == arm::FloatABI::SoftFP) {
1395 // Floating point operations are hard, but argument passing is soft.
1396 CmdArgs.push_back("-mfloat-abi");
1397 CmdArgs.push_back("soft");
1398 } else {
1399 // Floating point operations and argument passing are hard.
1400 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1401 CmdArgs.push_back("-mfloat-abi");
1402 CmdArgs.push_back("hard");
1403 }
1404
1405 // Forward the -mglobal-merge option for explicit control over the pass.
1406 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1407 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001408 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001409 if (A->getOption().matches(options::OPT_mno_global_merge))
1410 CmdArgs.push_back("-arm-global-merge=false");
1411 else
1412 CmdArgs.push_back("-arm-global-merge=true");
1413 }
1414
1415 if (!Args.hasFlag(options::OPT_mimplicit_float,
1416 options::OPT_mno_implicit_float, true))
1417 CmdArgs.push_back("-no-implicit-float");
Javed Absar603a2ba2019-05-21 14:21:26 +00001418
1419 if (Args.getLastArg(options::OPT_mcmse))
1420 CmdArgs.push_back("-mcmse");
David L. Jonesf561aba2017-03-08 01:02:16 +00001421}
1422
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001423void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1424 const ArgList &Args, bool KernelOrKext,
1425 ArgStringList &CmdArgs) const {
1426 const ToolChain &TC = getToolChain();
1427
1428 // Add the target features
1429 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1430
1431 // Add target specific flags.
1432 switch (TC.getArch()) {
1433 default:
1434 break;
1435
1436 case llvm::Triple::arm:
1437 case llvm::Triple::armeb:
1438 case llvm::Triple::thumb:
1439 case llvm::Triple::thumbeb:
1440 // Use the effective triple, which takes into account the deployment target.
1441 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1442 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1443 break;
1444
1445 case llvm::Triple::aarch64:
1446 case llvm::Triple::aarch64_be:
1447 AddAArch64TargetArgs(Args, CmdArgs);
1448 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1449 break;
1450
1451 case llvm::Triple::mips:
1452 case llvm::Triple::mipsel:
1453 case llvm::Triple::mips64:
1454 case llvm::Triple::mips64el:
1455 AddMIPSTargetArgs(Args, CmdArgs);
1456 break;
1457
1458 case llvm::Triple::ppc:
1459 case llvm::Triple::ppc64:
1460 case llvm::Triple::ppc64le:
1461 AddPPCTargetArgs(Args, CmdArgs);
1462 break;
1463
Alex Bradbury71f45452018-01-11 13:36:56 +00001464 case llvm::Triple::riscv32:
1465 case llvm::Triple::riscv64:
1466 AddRISCVTargetArgs(Args, CmdArgs);
1467 break;
1468
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001469 case llvm::Triple::sparc:
1470 case llvm::Triple::sparcel:
1471 case llvm::Triple::sparcv9:
1472 AddSparcTargetArgs(Args, CmdArgs);
1473 break;
1474
1475 case llvm::Triple::systemz:
1476 AddSystemZTargetArgs(Args, CmdArgs);
1477 break;
1478
1479 case llvm::Triple::x86:
1480 case llvm::Triple::x86_64:
1481 AddX86TargetArgs(Args, CmdArgs);
1482 break;
1483
1484 case llvm::Triple::lanai:
1485 AddLanaiTargetArgs(Args, CmdArgs);
1486 break;
1487
1488 case llvm::Triple::hexagon:
1489 AddHexagonTargetArgs(Args, CmdArgs);
1490 break;
1491
1492 case llvm::Triple::wasm32:
1493 case llvm::Triple::wasm64:
1494 AddWebAssemblyTargetArgs(Args, CmdArgs);
1495 break;
1496 }
1497}
1498
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001499// Parse -mbranch-protection=<protection>[+<protection>]* where
1500// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1501// Returns a triple of (return address signing Scope, signing key, require
1502// landing pads)
1503static std::tuple<StringRef, StringRef, bool>
1504ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1505 const Arg *A) {
1506 StringRef Scope = "none";
1507 StringRef Key = "a_key";
1508 bool IndirectBranches = false;
1509
1510 StringRef Value = A->getValue();
1511 // This maps onto -mbranch-protection=<scope>+<key>
1512
1513 if (Value.equals("standard")) {
1514 Scope = "non-leaf";
1515 Key = "a_key";
1516 IndirectBranches = true;
1517
1518 } else if (!Value.equals("none")) {
1519 SmallVector<StringRef, 4> BranchProtection;
1520 StringRef(A->getValue()).split(BranchProtection, '+');
1521
1522 auto Protection = BranchProtection.begin();
1523 while (Protection != BranchProtection.end()) {
1524 if (Protection->equals("bti"))
1525 IndirectBranches = true;
1526 else if (Protection->equals("pac-ret")) {
1527 Scope = "non-leaf";
1528 while (++Protection != BranchProtection.end()) {
1529 // Inner loop as "leaf" and "b-key" options must only appear attached
1530 // to pac-ret.
1531 if (Protection->equals("leaf"))
1532 Scope = "all";
1533 else if (Protection->equals("b-key"))
1534 Key = "b_key";
1535 else
1536 break;
1537 }
1538 Protection--;
1539 } else
1540 D.Diag(diag::err_invalid_branch_protection)
1541 << *Protection << A->getAsString(Args);
1542 Protection++;
1543 }
1544 }
1545
1546 return std::make_tuple(Scope, Key, IndirectBranches);
1547}
1548
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001549namespace {
1550void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1551 ArgStringList &CmdArgs) {
1552 const char *ABIName = nullptr;
1553 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1554 ABIName = A->getValue();
1555 else if (Triple.isOSDarwin())
1556 ABIName = "darwinpcs";
1557 else
1558 ABIName = "aapcs";
1559
1560 CmdArgs.push_back("-target-abi");
1561 CmdArgs.push_back(ABIName);
1562}
1563}
1564
David L. Jonesf561aba2017-03-08 01:02:16 +00001565void Clang::AddAArch64TargetArgs(const ArgList &Args,
1566 ArgStringList &CmdArgs) const {
1567 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1568
1569 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1570 Args.hasArg(options::OPT_mkernel) ||
1571 Args.hasArg(options::OPT_fapple_kext))
1572 CmdArgs.push_back("-disable-red-zone");
1573
1574 if (!Args.hasFlag(options::OPT_mimplicit_float,
1575 options::OPT_mno_implicit_float, true))
1576 CmdArgs.push_back("-no-implicit-float");
1577
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001578 RenderAArch64ABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001579
1580 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1581 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001582 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001583 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1584 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1585 else
1586 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1587 } else if (Triple.isAndroid()) {
1588 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001589 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001590 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1591 }
1592
1593 // Forward the -mglobal-merge option for explicit control over the pass.
1594 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1595 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001596 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001597 if (A->getOption().matches(options::OPT_mno_global_merge))
1598 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1599 else
1600 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1601 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001602
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001603 // Enable/disable return address signing and indirect branch targets.
1604 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1605 options::OPT_mbranch_protection_EQ)) {
1606
1607 const Driver &D = getToolChain().getDriver();
1608
1609 StringRef Scope, Key;
1610 bool IndirectBranches;
1611
1612 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1613 Scope = A->getValue();
1614 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1615 !Scope.equals("all"))
1616 D.Diag(diag::err_invalid_branch_protection)
1617 << Scope << A->getAsString(Args);
1618 Key = "a_key";
1619 IndirectBranches = false;
1620 } else
1621 std::tie(Scope, Key, IndirectBranches) =
1622 ParseAArch64BranchProtection(D, Args, A);
1623
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001624 CmdArgs.push_back(
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001625 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1626 CmdArgs.push_back(
1627 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1628 if (IndirectBranches)
1629 CmdArgs.push_back("-mbranch-target-enforce");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001630 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001631}
1632
1633void Clang::AddMIPSTargetArgs(const ArgList &Args,
1634 ArgStringList &CmdArgs) const {
1635 const Driver &D = getToolChain().getDriver();
1636 StringRef CPUName;
1637 StringRef ABIName;
1638 const llvm::Triple &Triple = getToolChain().getTriple();
1639 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1640
1641 CmdArgs.push_back("-target-abi");
1642 CmdArgs.push_back(ABIName.data());
1643
1644 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1645 if (ABI == mips::FloatABI::Soft) {
1646 // Floating point operations and argument passing are soft.
1647 CmdArgs.push_back("-msoft-float");
1648 CmdArgs.push_back("-mfloat-abi");
1649 CmdArgs.push_back("soft");
1650 } else {
1651 // Floating point operations and argument passing are hard.
1652 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1653 CmdArgs.push_back("-mfloat-abi");
1654 CmdArgs.push_back("hard");
1655 }
1656
1657 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1658 if (A->getOption().matches(options::OPT_mxgot)) {
1659 CmdArgs.push_back("-mllvm");
1660 CmdArgs.push_back("-mxgot");
1661 }
1662 }
1663
1664 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1665 options::OPT_mno_ldc1_sdc1)) {
1666 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1667 CmdArgs.push_back("-mllvm");
1668 CmdArgs.push_back("-mno-ldc1-sdc1");
1669 }
1670 }
1671
1672 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1673 options::OPT_mno_check_zero_division)) {
1674 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1675 CmdArgs.push_back("-mllvm");
1676 CmdArgs.push_back("-mno-check-zero-division");
1677 }
1678 }
1679
1680 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1681 StringRef v = A->getValue();
1682 CmdArgs.push_back("-mllvm");
1683 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1684 A->claim();
1685 }
1686
Simon Dardis31636a12017-07-20 14:04:12 +00001687 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1688 Arg *ABICalls =
1689 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1690
1691 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1692 // -mgpopt is the default for static, -fno-pic environments but these two
1693 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1694 // the only case where -mllvm -mgpopt is passed.
1695 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1696 // passed explicitly when compiling something with -mabicalls
1697 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001698 //
1699 // When the ABI in use is N64, we also need to determine the PIC mode that
1700 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001701 bool NoABICalls =
1702 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001703
1704 llvm::Reloc::Model RelocationModel;
1705 unsigned PICLevel;
1706 bool IsPIE;
1707 std::tie(RelocationModel, PICLevel, IsPIE) =
1708 ParsePICArgs(getToolChain(), Args);
1709
1710 NoABICalls = NoABICalls ||
1711 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1712
Simon Dardis31636a12017-07-20 14:04:12 +00001713 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1714 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1715 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1716 CmdArgs.push_back("-mllvm");
1717 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001718
1719 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1720 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001721 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001722 options::OPT_mno_extern_sdata);
1723 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1724 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001725 if (LocalSData) {
1726 CmdArgs.push_back("-mllvm");
1727 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1728 CmdArgs.push_back("-mlocal-sdata=1");
1729 } else {
1730 CmdArgs.push_back("-mlocal-sdata=0");
1731 }
1732 LocalSData->claim();
1733 }
1734
Simon Dardis7d318782017-07-24 14:02:09 +00001735 if (ExternSData) {
1736 CmdArgs.push_back("-mllvm");
1737 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1738 CmdArgs.push_back("-mextern-sdata=1");
1739 } else {
1740 CmdArgs.push_back("-mextern-sdata=0");
1741 }
1742 ExternSData->claim();
1743 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001744
1745 if (EmbeddedData) {
1746 CmdArgs.push_back("-mllvm");
1747 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1748 CmdArgs.push_back("-membedded-data=1");
1749 } else {
1750 CmdArgs.push_back("-membedded-data=0");
1751 }
1752 EmbeddedData->claim();
1753 }
1754
Simon Dardis31636a12017-07-20 14:04:12 +00001755 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1756 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1757
1758 if (GPOpt)
1759 GPOpt->claim();
1760
David L. Jonesf561aba2017-03-08 01:02:16 +00001761 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1762 StringRef Val = StringRef(A->getValue());
1763 if (mips::hasCompactBranches(CPUName)) {
1764 if (Val == "never" || Val == "always" || Val == "optimal") {
1765 CmdArgs.push_back("-mllvm");
1766 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1767 } else
1768 D.Diag(diag::err_drv_unsupported_option_argument)
1769 << A->getOption().getName() << Val;
1770 } else
1771 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1772 }
Vladimir Stefanovic99113a02019-01-18 19:54:51 +00001773
1774 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1775 options::OPT_mno_relax_pic_calls)) {
1776 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1777 CmdArgs.push_back("-mllvm");
1778 CmdArgs.push_back("-mips-jalr-reloc=0");
1779 }
1780 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001781}
1782
1783void Clang::AddPPCTargetArgs(const ArgList &Args,
1784 ArgStringList &CmdArgs) const {
1785 // Select the ABI to use.
1786 const char *ABIName = nullptr;
1787 if (getToolChain().getTriple().isOSLinux())
1788 switch (getToolChain().getArch()) {
1789 case llvm::Triple::ppc64: {
1790 // When targeting a processor that supports QPX, or if QPX is
1791 // specifically enabled, default to using the ABI that supports QPX (so
1792 // long as it is not specifically disabled).
1793 bool HasQPX = false;
1794 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1795 HasQPX = A->getValue() == StringRef("a2q");
1796 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1797 if (HasQPX) {
1798 ABIName = "elfv1-qpx";
1799 break;
1800 }
1801
1802 ABIName = "elfv1";
1803 break;
1804 }
1805 case llvm::Triple::ppc64le:
1806 ABIName = "elfv2";
1807 break;
1808 default:
1809 break;
1810 }
1811
Fangrui Song6bd02a42019-07-15 07:25:11 +00001812 bool IEEELongDouble = false;
1813 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1814 StringRef V = A->getValue();
1815 if (V == "ieeelongdouble")
1816 IEEELongDouble = true;
1817 else if (V == "ibmlongdouble")
1818 IEEELongDouble = false;
1819 else if (V != "altivec")
1820 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1821 // the option if given as we don't have backend support for any targets
1822 // that don't use the altivec abi.
David L. Jonesf561aba2017-03-08 01:02:16 +00001823 ABIName = A->getValue();
Fangrui Song6bd02a42019-07-15 07:25:11 +00001824 }
1825 if (IEEELongDouble)
1826 CmdArgs.push_back("-mabi=ieeelongdouble");
David L. Jonesf561aba2017-03-08 01:02:16 +00001827
1828 ppc::FloatABI FloatABI =
1829 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1830
1831 if (FloatABI == ppc::FloatABI::Soft) {
1832 // Floating point operations and argument passing are soft.
1833 CmdArgs.push_back("-msoft-float");
1834 CmdArgs.push_back("-mfloat-abi");
1835 CmdArgs.push_back("soft");
1836 } else {
1837 // Floating point operations and argument passing are hard.
1838 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1839 CmdArgs.push_back("-mfloat-abi");
1840 CmdArgs.push_back("hard");
1841 }
1842
1843 if (ABIName) {
1844 CmdArgs.push_back("-target-abi");
1845 CmdArgs.push_back(ABIName);
1846 }
1847}
1848
Alex Bradbury71f45452018-01-11 13:36:56 +00001849void Clang::AddRISCVTargetArgs(const ArgList &Args,
1850 ArgStringList &CmdArgs) const {
1851 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001852 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001853 const char *ABIName = nullptr;
1854 const llvm::Triple &Triple = getToolChain().getTriple();
1855 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1856 ABIName = A->getValue();
1857 else if (Triple.getArch() == llvm::Triple::riscv32)
1858 ABIName = "ilp32";
1859 else if (Triple.getArch() == llvm::Triple::riscv64)
1860 ABIName = "lp64";
1861 else
1862 llvm_unreachable("Unexpected triple!");
1863
1864 CmdArgs.push_back("-target-abi");
1865 CmdArgs.push_back(ABIName);
1866}
1867
David L. Jonesf561aba2017-03-08 01:02:16 +00001868void Clang::AddSparcTargetArgs(const ArgList &Args,
1869 ArgStringList &CmdArgs) const {
1870 sparc::FloatABI FloatABI =
1871 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1872
1873 if (FloatABI == sparc::FloatABI::Soft) {
1874 // Floating point operations and argument passing are soft.
1875 CmdArgs.push_back("-msoft-float");
1876 CmdArgs.push_back("-mfloat-abi");
1877 CmdArgs.push_back("soft");
1878 } else {
1879 // Floating point operations and argument passing are hard.
1880 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1881 CmdArgs.push_back("-mfloat-abi");
1882 CmdArgs.push_back("hard");
1883 }
1884}
1885
1886void Clang::AddSystemZTargetArgs(const ArgList &Args,
1887 ArgStringList &CmdArgs) const {
1888 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1889 CmdArgs.push_back("-mbackchain");
1890}
1891
1892void Clang::AddX86TargetArgs(const ArgList &Args,
1893 ArgStringList &CmdArgs) const {
1894 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1895 Args.hasArg(options::OPT_mkernel) ||
1896 Args.hasArg(options::OPT_fapple_kext))
1897 CmdArgs.push_back("-disable-red-zone");
1898
Kristina Brooks7f569b72018-10-18 14:07:02 +00001899 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1900 options::OPT_mno_tls_direct_seg_refs, true))
1901 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1902
David L. Jonesf561aba2017-03-08 01:02:16 +00001903 // Default to avoid implicit floating-point for kernel/kext code, but allow
1904 // that to be overridden with -mno-soft-float.
1905 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1906 Args.hasArg(options::OPT_fapple_kext));
1907 if (Arg *A = Args.getLastArg(
1908 options::OPT_msoft_float, options::OPT_mno_soft_float,
1909 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1910 const Option &O = A->getOption();
1911 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1912 O.matches(options::OPT_msoft_float));
1913 }
1914 if (NoImplicitFloat)
1915 CmdArgs.push_back("-no-implicit-float");
1916
1917 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1918 StringRef Value = A->getValue();
1919 if (Value == "intel" || Value == "att") {
1920 CmdArgs.push_back("-mllvm");
1921 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1922 } else {
1923 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1924 << A->getOption().getName() << Value;
1925 }
Nico Webere3712cf2018-01-17 13:34:20 +00001926 } else if (getToolChain().getDriver().IsCLMode()) {
1927 CmdArgs.push_back("-mllvm");
1928 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001929 }
1930
1931 // Set flags to support MCU ABI.
1932 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1933 CmdArgs.push_back("-mfloat-abi");
1934 CmdArgs.push_back("soft");
1935 CmdArgs.push_back("-mstack-alignment=4");
1936 }
1937}
1938
1939void Clang::AddHexagonTargetArgs(const ArgList &Args,
1940 ArgStringList &CmdArgs) const {
1941 CmdArgs.push_back("-mqdsp6-compat");
1942 CmdArgs.push_back("-Wreturn-type");
1943
1944 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001945 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001946 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1947 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001948 }
1949
1950 if (!Args.hasArg(options::OPT_fno_short_enums))
1951 CmdArgs.push_back("-fshort-enums");
1952 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1953 CmdArgs.push_back("-mllvm");
1954 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1955 }
1956 CmdArgs.push_back("-mllvm");
1957 CmdArgs.push_back("-machine-sink-split=0");
1958}
1959
1960void Clang::AddLanaiTargetArgs(const ArgList &Args,
1961 ArgStringList &CmdArgs) const {
1962 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1963 StringRef CPUName = A->getValue();
1964
1965 CmdArgs.push_back("-target-cpu");
1966 CmdArgs.push_back(Args.MakeArgString(CPUName));
1967 }
1968 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1969 StringRef Value = A->getValue();
1970 // Only support mregparm=4 to support old usage. Report error for all other
1971 // cases.
1972 int Mregparm;
1973 if (Value.getAsInteger(10, Mregparm)) {
1974 if (Mregparm != 4) {
1975 getToolChain().getDriver().Diag(
1976 diag::err_drv_unsupported_option_argument)
1977 << A->getOption().getName() << Value;
1978 }
1979 }
1980 }
1981}
1982
1983void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1984 ArgStringList &CmdArgs) const {
1985 // Default to "hidden" visibility.
1986 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1987 options::OPT_fvisibility_ms_compat)) {
1988 CmdArgs.push_back("-fvisibility");
1989 CmdArgs.push_back("hidden");
1990 }
1991}
1992
1993void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1994 StringRef Target, const InputInfo &Output,
1995 const InputInfo &Input, const ArgList &Args) const {
1996 // If this is a dry run, do not create the compilation database file.
1997 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1998 return;
1999
2000 using llvm::yaml::escape;
2001 const Driver &D = getToolChain().getDriver();
2002
2003 if (!CompilationDatabase) {
2004 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00002005 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC,
2006 llvm::sys::fs::OF_Text);
David L. Jonesf561aba2017-03-08 01:02:16 +00002007 if (EC) {
2008 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2009 << EC.message();
2010 return;
2011 }
2012 CompilationDatabase = std::move(File);
2013 }
2014 auto &CDB = *CompilationDatabase;
2015 SmallString<128> Buf;
2016 if (llvm::sys::fs::current_path(Buf))
2017 Buf = ".";
2018 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
2019 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2020 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2021 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2022 Buf = "-x";
2023 Buf += types::getTypeName(Input.getType());
2024 CDB << ", \"" << escape(Buf) << "\"";
2025 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2026 Buf = "--sysroot=";
2027 Buf += D.SysRoot;
2028 CDB << ", \"" << escape(Buf) << "\"";
2029 }
2030 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2031 for (auto &A: Args) {
2032 auto &O = A->getOption();
2033 // Skip language selection, which is positional.
2034 if (O.getID() == options::OPT_x)
2035 continue;
2036 // Skip writing dependency output and the compilation database itself.
2037 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2038 continue;
2039 // Skip inputs.
2040 if (O.getKind() == Option::InputClass)
2041 continue;
2042 // All other arguments are quoted and appended.
2043 ArgStringList ASL;
2044 A->render(Args, ASL);
2045 for (auto &it: ASL)
2046 CDB << ", \"" << escape(it) << "\"";
2047 }
2048 Buf = "--target=";
2049 Buf += Target;
2050 CDB << ", \"" << escape(Buf) << "\"]},\n";
2051}
2052
2053static void CollectArgsForIntegratedAssembler(Compilation &C,
2054 const ArgList &Args,
2055 ArgStringList &CmdArgs,
2056 const Driver &D) {
2057 if (UseRelaxAll(C, Args))
2058 CmdArgs.push_back("-mrelax-all");
2059
2060 // Only default to -mincremental-linker-compatible if we think we are
2061 // targeting the MSVC linker.
2062 bool DefaultIncrementalLinkerCompatible =
2063 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2064 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2065 options::OPT_mno_incremental_linker_compatible,
2066 DefaultIncrementalLinkerCompatible))
2067 CmdArgs.push_back("-mincremental-linker-compatible");
2068
2069 switch (C.getDefaultToolChain().getArch()) {
2070 case llvm::Triple::arm:
2071 case llvm::Triple::armeb:
2072 case llvm::Triple::thumb:
2073 case llvm::Triple::thumbeb:
2074 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2075 StringRef Value = A->getValue();
2076 if (Value == "always" || Value == "never" || Value == "arm" ||
2077 Value == "thumb") {
2078 CmdArgs.push_back("-mllvm");
2079 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2080 } else {
2081 D.Diag(diag::err_drv_unsupported_option_argument)
2082 << A->getOption().getName() << Value;
2083 }
2084 }
2085 break;
2086 default:
2087 break;
2088 }
2089
Nico Weberb28ffd82019-07-27 01:13:00 +00002090 // If you add more args here, also add them to the block below that
2091 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2092
David L. Jonesf561aba2017-03-08 01:02:16 +00002093 // When passing -I arguments to the assembler we sometimes need to
2094 // unconditionally take the next argument. For example, when parsing
2095 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2096 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2097 // arg after parsing the '-I' arg.
2098 bool TakeNextArg = false;
2099
Petr Hosek5668d832017-11-22 01:38:31 +00002100 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
Dan Albert2715b282019-03-28 18:08:28 +00002101 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00002102 const char *MipsTargetFeature = nullptr;
2103 for (const Arg *A :
2104 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2105 A->claim();
2106
2107 for (StringRef Value : A->getValues()) {
2108 if (TakeNextArg) {
2109 CmdArgs.push_back(Value.data());
2110 TakeNextArg = false;
2111 continue;
2112 }
2113
2114 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2115 Value == "-mbig-obj")
2116 continue; // LLVM handles bigobj automatically
2117
2118 switch (C.getDefaultToolChain().getArch()) {
2119 default:
2120 break;
Peter Smith3947cb32017-11-20 13:43:55 +00002121 case llvm::Triple::thumb:
2122 case llvm::Triple::thumbeb:
2123 case llvm::Triple::arm:
2124 case llvm::Triple::armeb:
2125 if (Value == "-mthumb")
2126 // -mthumb has already been processed in ComputeLLVMTriple()
2127 // recognize but skip over here.
2128 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00002129 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00002130 case llvm::Triple::mips:
2131 case llvm::Triple::mipsel:
2132 case llvm::Triple::mips64:
2133 case llvm::Triple::mips64el:
2134 if (Value == "--trap") {
2135 CmdArgs.push_back("-target-feature");
2136 CmdArgs.push_back("+use-tcc-in-div");
2137 continue;
2138 }
2139 if (Value == "--break") {
2140 CmdArgs.push_back("-target-feature");
2141 CmdArgs.push_back("-use-tcc-in-div");
2142 continue;
2143 }
2144 if (Value.startswith("-msoft-float")) {
2145 CmdArgs.push_back("-target-feature");
2146 CmdArgs.push_back("+soft-float");
2147 continue;
2148 }
2149 if (Value.startswith("-mhard-float")) {
2150 CmdArgs.push_back("-target-feature");
2151 CmdArgs.push_back("-soft-float");
2152 continue;
2153 }
2154
2155 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2156 .Case("-mips1", "+mips1")
2157 .Case("-mips2", "+mips2")
2158 .Case("-mips3", "+mips3")
2159 .Case("-mips4", "+mips4")
2160 .Case("-mips5", "+mips5")
2161 .Case("-mips32", "+mips32")
2162 .Case("-mips32r2", "+mips32r2")
2163 .Case("-mips32r3", "+mips32r3")
2164 .Case("-mips32r5", "+mips32r5")
2165 .Case("-mips32r6", "+mips32r6")
2166 .Case("-mips64", "+mips64")
2167 .Case("-mips64r2", "+mips64r2")
2168 .Case("-mips64r3", "+mips64r3")
2169 .Case("-mips64r5", "+mips64r5")
2170 .Case("-mips64r6", "+mips64r6")
2171 .Default(nullptr);
2172 if (MipsTargetFeature)
2173 continue;
2174 }
2175
2176 if (Value == "-force_cpusubtype_ALL") {
2177 // Do nothing, this is the default and we don't support anything else.
2178 } else if (Value == "-L") {
2179 CmdArgs.push_back("-msave-temp-labels");
2180 } else if (Value == "--fatal-warnings") {
2181 CmdArgs.push_back("-massembler-fatal-warnings");
2182 } else if (Value == "--noexecstack") {
Dan Albert2715b282019-03-28 18:08:28 +00002183 UseNoExecStack = true;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002184 } else if (Value.startswith("-compress-debug-sections") ||
2185 Value.startswith("--compress-debug-sections") ||
2186 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002187 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002188 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002189 } else if (Value == "-mrelax-relocations=yes" ||
2190 Value == "--mrelax-relocations=yes") {
2191 UseRelaxRelocations = true;
2192 } else if (Value == "-mrelax-relocations=no" ||
2193 Value == "--mrelax-relocations=no") {
2194 UseRelaxRelocations = false;
2195 } else if (Value.startswith("-I")) {
2196 CmdArgs.push_back(Value.data());
2197 // We need to consume the next argument if the current arg is a plain
2198 // -I. The next arg will be the include directory.
2199 if (Value == "-I")
2200 TakeNextArg = true;
2201 } else if (Value.startswith("-gdwarf-")) {
2202 // "-gdwarf-N" options are not cc1as options.
2203 unsigned DwarfVersion = DwarfVersionNum(Value);
2204 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2205 CmdArgs.push_back(Value.data());
2206 } else {
2207 RenderDebugEnablingArgs(Args, CmdArgs,
2208 codegenoptions::LimitedDebugInfo,
2209 DwarfVersion, llvm::DebuggerKind::Default);
2210 }
2211 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2212 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2213 // Do nothing, we'll validate it later.
2214 } else if (Value == "-defsym") {
2215 if (A->getNumValues() != 2) {
2216 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2217 break;
2218 }
2219 const char *S = A->getValue(1);
2220 auto Pair = StringRef(S).split('=');
2221 auto Sym = Pair.first;
2222 auto SVal = Pair.second;
2223
2224 if (Sym.empty() || SVal.empty()) {
2225 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2226 break;
2227 }
2228 int64_t IVal;
2229 if (SVal.getAsInteger(0, IVal)) {
2230 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2231 break;
2232 }
2233 CmdArgs.push_back(Value.data());
2234 TakeNextArg = true;
Nico Weber4c9fa4a2018-12-06 18:50:39 +00002235 } else if (Value == "-fdebug-compilation-dir") {
2236 CmdArgs.push_back("-fdebug-compilation-dir");
2237 TakeNextArg = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002238 } else {
2239 D.Diag(diag::err_drv_unsupported_option_argument)
2240 << A->getOption().getName() << Value;
2241 }
2242 }
2243 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002244 if (UseRelaxRelocations)
2245 CmdArgs.push_back("--mrelax-relocations");
Dan Albert2715b282019-03-28 18:08:28 +00002246 if (UseNoExecStack)
2247 CmdArgs.push_back("-mnoexecstack");
David L. Jonesf561aba2017-03-08 01:02:16 +00002248 if (MipsTargetFeature != nullptr) {
2249 CmdArgs.push_back("-target-feature");
2250 CmdArgs.push_back(MipsTargetFeature);
2251 }
Steven Wu098742f2018-12-12 17:30:16 +00002252
2253 // forward -fembed-bitcode to assmebler
2254 if (C.getDriver().embedBitcodeEnabled() ||
2255 C.getDriver().embedBitcodeMarkerOnly())
2256 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00002257}
2258
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002259static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2260 bool OFastEnabled, const ArgList &Args,
2261 ArgStringList &CmdArgs) {
2262 // Handle various floating point optimization flags, mapping them to the
2263 // appropriate LLVM code generation flags. This is complicated by several
2264 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002265 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002266 // LLVM flags based on the final state.
2267 bool HonorINFs = true;
2268 bool HonorNaNs = true;
2269 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2270 bool MathErrno = TC.IsMathErrnoDefault();
2271 bool AssociativeMath = false;
2272 bool ReciprocalMath = false;
2273 bool SignedZeros = true;
2274 bool TrappingMath = true;
2275 StringRef DenormalFPMath = "";
2276 StringRef FPContract = "";
2277
Saleem Abdulrasool258e4f62018-09-18 21:12:39 +00002278 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2279 CmdArgs.push_back("-mlimit-float-precision");
2280 CmdArgs.push_back(A->getValue());
2281 }
2282
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002283 for (const Arg *A : Args) {
2284 switch (A->getOption().getID()) {
2285 // If this isn't an FP option skip the claim below
2286 default: continue;
2287
2288 // Options controlling individual features
2289 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2290 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2291 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2292 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2293 case options::OPT_fmath_errno: MathErrno = true; break;
2294 case options::OPT_fno_math_errno: MathErrno = false; break;
2295 case options::OPT_fassociative_math: AssociativeMath = true; break;
2296 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2297 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2298 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2299 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2300 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2301 case options::OPT_ftrapping_math: TrappingMath = true; break;
2302 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2303
2304 case options::OPT_fdenormal_fp_math_EQ:
2305 DenormalFPMath = A->getValue();
2306 break;
2307
2308 // Validate and pass through -fp-contract option.
2309 case options::OPT_ffp_contract: {
2310 StringRef Val = A->getValue();
2311 if (Val == "fast" || Val == "on" || Val == "off")
2312 FPContract = Val;
2313 else
2314 D.Diag(diag::err_drv_unsupported_option_argument)
2315 << A->getOption().getName() << Val;
2316 break;
2317 }
2318
2319 case options::OPT_ffinite_math_only:
2320 HonorINFs = false;
2321 HonorNaNs = false;
2322 break;
2323 case options::OPT_fno_finite_math_only:
2324 HonorINFs = true;
2325 HonorNaNs = true;
2326 break;
2327
2328 case options::OPT_funsafe_math_optimizations:
2329 AssociativeMath = true;
2330 ReciprocalMath = true;
2331 SignedZeros = false;
2332 TrappingMath = false;
2333 break;
2334 case options::OPT_fno_unsafe_math_optimizations:
2335 AssociativeMath = false;
2336 ReciprocalMath = false;
2337 SignedZeros = true;
2338 TrappingMath = true;
2339 // -fno_unsafe_math_optimizations restores default denormal handling
2340 DenormalFPMath = "";
2341 break;
2342
2343 case options::OPT_Ofast:
2344 // If -Ofast is the optimization level, then -ffast-math should be enabled
2345 if (!OFastEnabled)
2346 continue;
2347 LLVM_FALLTHROUGH;
2348 case options::OPT_ffast_math:
2349 HonorINFs = false;
2350 HonorNaNs = false;
2351 MathErrno = false;
2352 AssociativeMath = true;
2353 ReciprocalMath = true;
2354 SignedZeros = false;
2355 TrappingMath = false;
2356 // If fast-math is set then set the fp-contract mode to fast.
2357 FPContract = "fast";
2358 break;
2359 case options::OPT_fno_fast_math:
2360 HonorINFs = true;
2361 HonorNaNs = true;
2362 // Turning on -ffast-math (with either flag) removes the need for
2363 // MathErrno. However, turning *off* -ffast-math merely restores the
2364 // toolchain default (which may be false).
2365 MathErrno = TC.IsMathErrnoDefault();
2366 AssociativeMath = false;
2367 ReciprocalMath = false;
2368 SignedZeros = true;
2369 TrappingMath = true;
2370 // -fno_fast_math restores default denormal and fpcontract handling
2371 DenormalFPMath = "";
2372 FPContract = "";
2373 break;
2374 }
2375
2376 // If we handled this option claim it
2377 A->claim();
2378 }
2379
2380 if (!HonorINFs)
2381 CmdArgs.push_back("-menable-no-infs");
2382
2383 if (!HonorNaNs)
2384 CmdArgs.push_back("-menable-no-nans");
2385
2386 if (MathErrno)
2387 CmdArgs.push_back("-fmath-errno");
2388
2389 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2390 !TrappingMath)
2391 CmdArgs.push_back("-menable-unsafe-fp-math");
2392
2393 if (!SignedZeros)
2394 CmdArgs.push_back("-fno-signed-zeros");
2395
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002396 if (AssociativeMath && !SignedZeros && !TrappingMath)
2397 CmdArgs.push_back("-mreassociate");
2398
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002399 if (ReciprocalMath)
2400 CmdArgs.push_back("-freciprocal-math");
2401
2402 if (!TrappingMath)
2403 CmdArgs.push_back("-fno-trapping-math");
2404
2405 if (!DenormalFPMath.empty())
2406 CmdArgs.push_back(
2407 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2408
2409 if (!FPContract.empty())
2410 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2411
2412 ParseMRecip(D, Args, CmdArgs);
2413
2414 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2415 // individual features enabled by -ffast-math instead of the option itself as
2416 // that's consistent with gcc's behaviour.
2417 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2418 ReciprocalMath && !SignedZeros && !TrappingMath)
2419 CmdArgs.push_back("-ffast-math");
2420
2421 // Handle __FINITE_MATH_ONLY__ similarly.
2422 if (!HonorINFs && !HonorNaNs)
2423 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002424
2425 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2426 CmdArgs.push_back("-mfpmath");
2427 CmdArgs.push_back(A->getValue());
2428 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002429
2430 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002431 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2432 options::OPT_fstrict_float_cast_overflow, false))
2433 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002434}
2435
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002436static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2437 const llvm::Triple &Triple,
2438 const InputInfo &Input) {
2439 // Enable region store model by default.
2440 CmdArgs.push_back("-analyzer-store=region");
2441
2442 // Treat blocks as analysis entry points.
2443 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2444
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002445 // Add default argument set.
2446 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2447 CmdArgs.push_back("-analyzer-checker=core");
2448 CmdArgs.push_back("-analyzer-checker=apiModeling");
2449
2450 if (!Triple.isWindowsMSVCEnvironment()) {
2451 CmdArgs.push_back("-analyzer-checker=unix");
2452 } else {
2453 // Enable "unix" checkers that also work on Windows.
2454 CmdArgs.push_back("-analyzer-checker=unix.API");
2455 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2456 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2457 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2458 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2459 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2460 }
2461
2462 // Disable some unix checkers for PS4.
2463 if (Triple.isPS4CPU()) {
2464 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2465 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2466 }
2467
2468 if (Triple.isOSDarwin())
2469 CmdArgs.push_back("-analyzer-checker=osx");
2470
2471 CmdArgs.push_back("-analyzer-checker=deadcode");
2472
2473 if (types::isCXX(Input.getType()))
2474 CmdArgs.push_back("-analyzer-checker=cplusplus");
2475
2476 if (!Triple.isPS4CPU()) {
2477 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2478 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2479 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2480 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2481 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2482 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2483 }
2484
2485 // Default nullability checks.
2486 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2487 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2488 }
2489
2490 // Set the output format. The default is plist, for (lame) historical reasons.
2491 CmdArgs.push_back("-analyzer-output");
2492 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2493 CmdArgs.push_back(A->getValue());
2494 else
2495 CmdArgs.push_back("plist");
2496
2497 // Disable the presentation of standard compiler warnings when using
2498 // --analyze. We only want to show static analyzer diagnostics or frontend
2499 // errors.
2500 CmdArgs.push_back("-w");
2501
2502 // Add -Xanalyzer arguments when running as analyzer.
2503 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2504}
2505
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002506static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002507 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002508 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2509
2510 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2511 // doesn't even have a stack!
2512 if (EffectiveTriple.isNVPTX())
2513 return;
2514
2515 // -stack-protector=0 is default.
2516 unsigned StackProtectorLevel = 0;
2517 unsigned DefaultStackProtectorLevel =
2518 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2519
2520 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2521 options::OPT_fstack_protector_all,
2522 options::OPT_fstack_protector_strong,
2523 options::OPT_fstack_protector)) {
2524 if (A->getOption().matches(options::OPT_fstack_protector))
2525 StackProtectorLevel =
2526 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2527 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2528 StackProtectorLevel = LangOptions::SSPStrong;
2529 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2530 StackProtectorLevel = LangOptions::SSPReq;
2531 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002532 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002533 }
2534
2535 if (StackProtectorLevel) {
2536 CmdArgs.push_back("-stack-protector");
2537 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2538 }
2539
2540 // --param ssp-buffer-size=
2541 for (const Arg *A : Args.filtered(options::OPT__param)) {
2542 StringRef Str(A->getValue());
2543 if (Str.startswith("ssp-buffer-size=")) {
2544 if (StackProtectorLevel) {
2545 CmdArgs.push_back("-stack-protector-buffer-size");
2546 // FIXME: Verify the argument is a valid integer.
2547 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2548 }
2549 A->claim();
2550 }
2551 }
2552}
2553
JF Bastien14daa202018-12-18 05:12:21 +00002554static void RenderTrivialAutoVarInitOptions(const Driver &D,
2555 const ToolChain &TC,
2556 const ArgList &Args,
2557 ArgStringList &CmdArgs) {
2558 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2559 StringRef TrivialAutoVarInit = "";
2560
2561 for (const Arg *A : Args) {
2562 switch (A->getOption().getID()) {
2563 default:
2564 continue;
2565 case options::OPT_ftrivial_auto_var_init: {
2566 A->claim();
2567 StringRef Val = A->getValue();
2568 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2569 TrivialAutoVarInit = Val;
2570 else
2571 D.Diag(diag::err_drv_unsupported_option_argument)
2572 << A->getOption().getName() << Val;
2573 break;
2574 }
2575 }
2576 }
2577
2578 if (TrivialAutoVarInit.empty())
2579 switch (DefaultTrivialAutoVarInit) {
2580 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2581 break;
2582 case LangOptions::TrivialAutoVarInitKind::Pattern:
2583 TrivialAutoVarInit = "pattern";
2584 break;
2585 case LangOptions::TrivialAutoVarInitKind::Zero:
2586 TrivialAutoVarInit = "zero";
2587 break;
2588 }
2589
2590 if (!TrivialAutoVarInit.empty()) {
2591 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2592 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2593 CmdArgs.push_back(
2594 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2595 }
2596}
2597
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002598static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2599 const unsigned ForwardedArguments[] = {
2600 options::OPT_cl_opt_disable,
2601 options::OPT_cl_strict_aliasing,
2602 options::OPT_cl_single_precision_constant,
2603 options::OPT_cl_finite_math_only,
2604 options::OPT_cl_kernel_arg_info,
2605 options::OPT_cl_unsafe_math_optimizations,
2606 options::OPT_cl_fast_relaxed_math,
2607 options::OPT_cl_mad_enable,
2608 options::OPT_cl_no_signed_zeros,
2609 options::OPT_cl_denorms_are_zero,
2610 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002611 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002612 };
2613
2614 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2615 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2616 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2617 }
2618
2619 for (const auto &Arg : ForwardedArguments)
2620 if (const auto *A = Args.getLastArg(Arg))
2621 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2622}
2623
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002624static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2625 ArgStringList &CmdArgs) {
2626 bool ARCMTEnabled = false;
2627 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2628 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2629 options::OPT_ccc_arcmt_modify,
2630 options::OPT_ccc_arcmt_migrate)) {
2631 ARCMTEnabled = true;
2632 switch (A->getOption().getID()) {
2633 default: llvm_unreachable("missed a case");
2634 case options::OPT_ccc_arcmt_check:
2635 CmdArgs.push_back("-arcmt-check");
2636 break;
2637 case options::OPT_ccc_arcmt_modify:
2638 CmdArgs.push_back("-arcmt-modify");
2639 break;
2640 case options::OPT_ccc_arcmt_migrate:
2641 CmdArgs.push_back("-arcmt-migrate");
2642 CmdArgs.push_back("-mt-migrate-directory");
2643 CmdArgs.push_back(A->getValue());
2644
2645 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2646 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2647 break;
2648 }
2649 }
2650 } else {
2651 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2652 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2653 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2654 }
2655
2656 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2657 if (ARCMTEnabled)
2658 D.Diag(diag::err_drv_argument_not_allowed_with)
2659 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2660
2661 CmdArgs.push_back("-mt-migrate-directory");
2662 CmdArgs.push_back(A->getValue());
2663
2664 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2665 options::OPT_objcmt_migrate_subscripting,
2666 options::OPT_objcmt_migrate_property)) {
2667 // None specified, means enable them all.
2668 CmdArgs.push_back("-objcmt-migrate-literals");
2669 CmdArgs.push_back("-objcmt-migrate-subscripting");
2670 CmdArgs.push_back("-objcmt-migrate-property");
2671 } else {
2672 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2673 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2674 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2675 }
2676 } else {
2677 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2678 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2679 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2680 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2681 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2682 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2683 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2684 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2685 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2686 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2687 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2688 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2689 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2690 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2691 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2692 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2693 }
2694}
2695
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002696static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2697 const ArgList &Args, ArgStringList &CmdArgs) {
2698 // -fbuiltin is default unless -mkernel is used.
2699 bool UseBuiltins =
2700 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2701 !Args.hasArg(options::OPT_mkernel));
2702 if (!UseBuiltins)
2703 CmdArgs.push_back("-fno-builtin");
2704
2705 // -ffreestanding implies -fno-builtin.
2706 if (Args.hasArg(options::OPT_ffreestanding))
2707 UseBuiltins = false;
2708
2709 // Process the -fno-builtin-* options.
2710 for (const auto &Arg : Args) {
2711 const Option &O = Arg->getOption();
2712 if (!O.matches(options::OPT_fno_builtin_))
2713 continue;
2714
2715 Arg->claim();
2716
2717 // If -fno-builtin is specified, then there's no need to pass the option to
2718 // the frontend.
2719 if (!UseBuiltins)
2720 continue;
2721
2722 StringRef FuncName = Arg->getValue();
2723 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2724 }
2725
2726 // le32-specific flags:
2727 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2728 // by default.
2729 if (TC.getArch() == llvm::Triple::le32)
2730 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002731}
2732
Adrian Prantl70599032018-02-09 18:43:10 +00002733void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2734 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2735 llvm::sys::path::append(Result, "org.llvm.clang.");
2736 appendUserToPath(Result);
2737 llvm::sys::path::append(Result, "ModuleCache");
2738}
2739
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002740static void RenderModulesOptions(Compilation &C, const Driver &D,
2741 const ArgList &Args, const InputInfo &Input,
2742 const InputInfo &Output,
2743 ArgStringList &CmdArgs, bool &HaveModules) {
2744 // -fmodules enables the use of precompiled modules (off by default).
2745 // Users can pass -fno-cxx-modules to turn off modules support for
2746 // C++/Objective-C++ programs.
2747 bool HaveClangModules = false;
2748 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2749 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2750 options::OPT_fno_cxx_modules, true);
2751 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2752 CmdArgs.push_back("-fmodules");
2753 HaveClangModules = true;
2754 }
2755 }
2756
Richard Smithb1b580e2019-04-14 11:11:37 +00002757 HaveModules |= HaveClangModules;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002758 if (Args.hasArg(options::OPT_fmodules_ts)) {
2759 CmdArgs.push_back("-fmodules-ts");
2760 HaveModules = true;
2761 }
2762
2763 // -fmodule-maps enables implicit reading of module map files. By default,
2764 // this is enabled if we are using Clang's flavor of precompiled modules.
2765 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2766 options::OPT_fno_implicit_module_maps, HaveClangModules))
2767 CmdArgs.push_back("-fimplicit-module-maps");
2768
2769 // -fmodules-decluse checks that modules used are declared so (off by default)
2770 if (Args.hasFlag(options::OPT_fmodules_decluse,
2771 options::OPT_fno_modules_decluse, false))
2772 CmdArgs.push_back("-fmodules-decluse");
2773
2774 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2775 // all #included headers are part of modules.
2776 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2777 options::OPT_fno_modules_strict_decluse, false))
2778 CmdArgs.push_back("-fmodules-strict-decluse");
2779
2780 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002781 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002782 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2783 options::OPT_fno_implicit_modules, HaveClangModules)) {
2784 if (HaveModules)
2785 CmdArgs.push_back("-fno-implicit-modules");
2786 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002787 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002788 // -fmodule-cache-path specifies where our implicitly-built module files
2789 // should be written.
2790 SmallString<128> Path;
2791 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2792 Path = A->getValue();
2793
2794 if (C.isForDiagnostics()) {
2795 // When generating crash reports, we want to emit the modules along with
2796 // the reproduction sources, so we ignore any provided module path.
2797 Path = Output.getFilename();
2798 llvm::sys::path::replace_extension(Path, ".cache");
2799 llvm::sys::path::append(Path, "modules");
2800 } else if (Path.empty()) {
2801 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002802 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002803 }
2804
2805 const char Arg[] = "-fmodules-cache-path=";
2806 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2807 CmdArgs.push_back(Args.MakeArgString(Path));
2808 }
2809
2810 if (HaveModules) {
2811 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2812 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2813 CmdArgs.push_back(Args.MakeArgString(
2814 std::string("-fprebuilt-module-path=") + A->getValue()));
2815 A->claim();
2816 }
2817 }
2818
2819 // -fmodule-name specifies the module that is currently being built (or
2820 // used for header checking by -fmodule-maps).
2821 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2822
2823 // -fmodule-map-file can be used to specify files containing module
2824 // definitions.
2825 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2826
2827 // -fbuiltin-module-map can be used to load the clang
2828 // builtin headers modulemap file.
2829 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2830 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2831 llvm::sys::path::append(BuiltinModuleMap, "include");
2832 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2833 if (llvm::sys::fs::exists(BuiltinModuleMap))
2834 CmdArgs.push_back(
2835 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2836 }
2837
2838 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2839 // names to precompiled module files (the module is loaded only if used).
2840 // The -fmodule-file=<file> form can be used to unconditionally load
2841 // precompiled module files (whether used or not).
2842 if (HaveModules)
2843 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2844 else
2845 Args.ClaimAllArgs(options::OPT_fmodule_file);
2846
2847 // When building modules and generating crashdumps, we need to dump a module
2848 // dependency VFS alongside the output.
2849 if (HaveClangModules && C.isForDiagnostics()) {
2850 SmallString<128> VFSDir(Output.getFilename());
2851 llvm::sys::path::replace_extension(VFSDir, ".cache");
2852 // Add the cache directory as a temp so the crash diagnostics pick it up.
2853 C.addTempFile(Args.MakeArgString(VFSDir));
2854
2855 llvm::sys::path::append(VFSDir, "vfs");
2856 CmdArgs.push_back("-module-dependency-dir");
2857 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2858 }
2859
2860 if (HaveClangModules)
2861 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2862
2863 // Pass through all -fmodules-ignore-macro arguments.
2864 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2865 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2866 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2867
2868 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2869
2870 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2871 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2872 D.Diag(diag::err_drv_argument_not_allowed_with)
2873 << A->getAsString(Args) << "-fbuild-session-timestamp";
2874
2875 llvm::sys::fs::file_status Status;
2876 if (llvm::sys::fs::status(A->getValue(), Status))
2877 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2878 CmdArgs.push_back(
2879 Args.MakeArgString("-fbuild-session-timestamp=" +
2880 Twine((uint64_t)Status.getLastModificationTime()
2881 .time_since_epoch()
2882 .count())));
2883 }
2884
2885 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2886 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2887 options::OPT_fbuild_session_file))
2888 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2889
2890 Args.AddLastArg(CmdArgs,
2891 options::OPT_fmodules_validate_once_per_build_session);
2892 }
2893
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002894 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2895 options::OPT_fno_modules_validate_system_headers,
2896 ImplicitModules))
2897 CmdArgs.push_back("-fmodules-validate-system-headers");
2898
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002899 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2900}
2901
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002902static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2903 ArgStringList &CmdArgs) {
2904 // -fsigned-char is default.
2905 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2906 options::OPT_fno_signed_char,
2907 options::OPT_funsigned_char,
2908 options::OPT_fno_unsigned_char)) {
2909 if (A->getOption().matches(options::OPT_funsigned_char) ||
2910 A->getOption().matches(options::OPT_fno_signed_char)) {
2911 CmdArgs.push_back("-fno-signed-char");
2912 }
2913 } else if (!isSignedCharDefault(T)) {
2914 CmdArgs.push_back("-fno-signed-char");
2915 }
2916
Richard Smith28ddb912018-11-14 21:04:34 +00002917 // The default depends on the language standard.
Nico Weber908b6972019-06-26 17:51:47 +00002918 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
Richard Smith3a8244d2018-05-01 05:02:45 +00002919
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002920 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2921 options::OPT_fno_short_wchar)) {
2922 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2923 CmdArgs.push_back("-fwchar-type=short");
2924 CmdArgs.push_back("-fno-signed-wchar");
2925 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002926 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002927 CmdArgs.push_back("-fwchar-type=int");
Michal Gorny5a409d02018-12-20 13:09:30 +00002928 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2929 T.isOSOpenBSD()))
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002930 CmdArgs.push_back("-fno-signed-wchar");
2931 else
2932 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002933 }
2934 }
2935}
2936
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002937static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2938 const llvm::Triple &T, const ArgList &Args,
2939 ObjCRuntime &Runtime, bool InferCovariantReturns,
2940 const InputInfo &Input, ArgStringList &CmdArgs) {
2941 const llvm::Triple::ArchType Arch = TC.getArch();
2942
2943 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2944 // is the default. Except for deployment target of 10.5, next runtime is
2945 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2946 if (Runtime.isNonFragile()) {
2947 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2948 options::OPT_fno_objc_legacy_dispatch,
2949 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2950 if (TC.UseObjCMixedDispatch())
2951 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2952 else
2953 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2954 }
2955 }
2956
2957 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2958 // to do Array/Dictionary subscripting by default.
2959 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002960 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2961 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2962
2963 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2964 // NOTE: This logic is duplicated in ToolChains.cpp.
2965 if (isObjCAutoRefCount(Args)) {
2966 TC.CheckObjCARC();
2967
2968 CmdArgs.push_back("-fobjc-arc");
2969
2970 // FIXME: It seems like this entire block, and several around it should be
2971 // wrapped in isObjC, but for now we just use it here as this is where it
2972 // was being used previously.
2973 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2974 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2975 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2976 else
2977 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2978 }
2979
2980 // Allow the user to enable full exceptions code emission.
2981 // We default off for Objective-C, on for Objective-C++.
2982 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2983 options::OPT_fno_objc_arc_exceptions,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002984 /*Default=*/types::isCXX(Input.getType())))
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002985 CmdArgs.push_back("-fobjc-arc-exceptions");
2986 }
2987
2988 // Silence warning for full exception code emission options when explicitly
2989 // set to use no ARC.
2990 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2991 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2992 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2993 }
2994
Pete Coopere3886802018-12-08 05:13:50 +00002995 // Allow the user to control whether messages can be converted to runtime
2996 // functions.
2997 if (types::isObjC(Input.getType())) {
2998 auto *Arg = Args.getLastArg(
2999 options::OPT_fobjc_convert_messages_to_runtime_calls,
3000 options::OPT_fno_objc_convert_messages_to_runtime_calls);
3001 if (Arg &&
3002 Arg->getOption().matches(
3003 options::OPT_fno_objc_convert_messages_to_runtime_calls))
3004 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3005 }
3006
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00003007 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3008 // rewriter.
3009 if (InferCovariantReturns)
3010 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3011
3012 // Pass down -fobjc-weak or -fno-objc-weak if present.
3013 if (types::isObjC(Input.getType())) {
3014 auto WeakArg =
3015 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3016 if (!WeakArg) {
3017 // nothing to do
3018 } else if (!Runtime.allowsWeak()) {
3019 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3020 D.Diag(diag::err_objc_weak_unsupported);
3021 } else {
3022 WeakArg->render(Args, CmdArgs);
3023 }
3024 }
3025}
3026
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00003027static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3028 ArgStringList &CmdArgs) {
3029 bool CaretDefault = true;
3030 bool ColumnDefault = true;
3031
3032 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3033 options::OPT__SLASH_diagnostics_column,
3034 options::OPT__SLASH_diagnostics_caret)) {
3035 switch (A->getOption().getID()) {
3036 case options::OPT__SLASH_diagnostics_caret:
3037 CaretDefault = true;
3038 ColumnDefault = true;
3039 break;
3040 case options::OPT__SLASH_diagnostics_column:
3041 CaretDefault = false;
3042 ColumnDefault = true;
3043 break;
3044 case options::OPT__SLASH_diagnostics_classic:
3045 CaretDefault = false;
3046 ColumnDefault = false;
3047 break;
3048 }
3049 }
3050
3051 // -fcaret-diagnostics is default.
3052 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3053 options::OPT_fno_caret_diagnostics, CaretDefault))
3054 CmdArgs.push_back("-fno-caret-diagnostics");
3055
3056 // -fdiagnostics-fixit-info is default, only pass non-default.
3057 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3058 options::OPT_fno_diagnostics_fixit_info))
3059 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3060
3061 // Enable -fdiagnostics-show-option by default.
3062 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3063 options::OPT_fno_diagnostics_show_option))
3064 CmdArgs.push_back("-fdiagnostics-show-option");
3065
3066 if (const Arg *A =
3067 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3068 CmdArgs.push_back("-fdiagnostics-show-category");
3069 CmdArgs.push_back(A->getValue());
3070 }
3071
3072 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3073 options::OPT_fno_diagnostics_show_hotness, false))
3074 CmdArgs.push_back("-fdiagnostics-show-hotness");
3075
3076 if (const Arg *A =
3077 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3078 std::string Opt =
3079 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3080 CmdArgs.push_back(Args.MakeArgString(Opt));
3081 }
3082
3083 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3084 CmdArgs.push_back("-fdiagnostics-format");
3085 CmdArgs.push_back(A->getValue());
3086 }
3087
3088 if (const Arg *A = Args.getLastArg(
3089 options::OPT_fdiagnostics_show_note_include_stack,
3090 options::OPT_fno_diagnostics_show_note_include_stack)) {
3091 const Option &O = A->getOption();
3092 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3093 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3094 else
3095 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3096 }
3097
3098 // Color diagnostics are parsed by the driver directly from argv and later
3099 // re-parsed to construct this job; claim any possible color diagnostic here
3100 // to avoid warn_drv_unused_argument and diagnose bad
3101 // OPT_fdiagnostics_color_EQ values.
3102 for (const Arg *A : Args) {
3103 const Option &O = A->getOption();
3104 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3105 !O.matches(options::OPT_fdiagnostics_color) &&
3106 !O.matches(options::OPT_fno_color_diagnostics) &&
3107 !O.matches(options::OPT_fno_diagnostics_color) &&
3108 !O.matches(options::OPT_fdiagnostics_color_EQ))
3109 continue;
3110
3111 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3112 StringRef Value(A->getValue());
3113 if (Value != "always" && Value != "never" && Value != "auto")
3114 D.Diag(diag::err_drv_clang_unsupported)
3115 << ("-fdiagnostics-color=" + Value).str();
3116 }
3117 A->claim();
3118 }
3119
3120 if (D.getDiags().getDiagnosticOptions().ShowColors)
3121 CmdArgs.push_back("-fcolor-diagnostics");
3122
3123 if (Args.hasArg(options::OPT_fansi_escape_codes))
3124 CmdArgs.push_back("-fansi-escape-codes");
3125
3126 if (!Args.hasFlag(options::OPT_fshow_source_location,
3127 options::OPT_fno_show_source_location))
3128 CmdArgs.push_back("-fno-show-source-location");
3129
3130 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3131 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3132
3133 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3134 ColumnDefault))
3135 CmdArgs.push_back("-fno-show-column");
3136
3137 if (!Args.hasFlag(options::OPT_fspell_checking,
3138 options::OPT_fno_spell_checking))
3139 CmdArgs.push_back("-fno-spell-checking");
3140}
3141
George Rimar91829ee2018-11-14 09:22:16 +00003142enum class DwarfFissionKind { None, Split, Single };
3143
3144static DwarfFissionKind getDebugFissionKind(const Driver &D,
3145 const ArgList &Args, Arg *&Arg) {
3146 Arg =
3147 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3148 if (!Arg)
3149 return DwarfFissionKind::None;
3150
3151 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3152 return DwarfFissionKind::Split;
3153
3154 StringRef Value = Arg->getValue();
3155 if (Value == "split")
3156 return DwarfFissionKind::Split;
3157 if (Value == "single")
3158 return DwarfFissionKind::Single;
3159
3160 D.Diag(diag::err_drv_unsupported_option_argument)
3161 << Arg->getOption().getName() << Arg->getValue();
3162 return DwarfFissionKind::None;
3163}
3164
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003165static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3166 const llvm::Triple &T, const ArgList &Args,
3167 bool EmitCodeView, bool IsWindowsMSVC,
3168 ArgStringList &CmdArgs,
3169 codegenoptions::DebugInfoKind &DebugInfoKind,
George Rimar91829ee2018-11-14 09:22:16 +00003170 DwarfFissionKind &DwarfFission) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003171 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003172 options::OPT_fno_debug_info_for_profiling, false) &&
3173 checkDebugInfoOption(
3174 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003175 CmdArgs.push_back("-fdebug-info-for-profiling");
3176
3177 // The 'g' groups options involve a somewhat intricate sequence of decisions
3178 // about what to pass from the driver to the frontend, but by the time they
3179 // reach cc1 they've been factored into three well-defined orthogonal choices:
3180 // * what level of debug info to generate
3181 // * what dwarf version to write
3182 // * what debugger tuning to use
3183 // This avoids having to monkey around further in cc1 other than to disable
3184 // codeview if not running in a Windows environment. Perhaps even that
3185 // decision should be made in the driver as well though.
3186 unsigned DWARFVersion = 0;
3187 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3188
3189 bool SplitDWARFInlining =
3190 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3191 options::OPT_fno_split_dwarf_inlining, true);
3192
3193 Args.ClaimAllArgs(options::OPT_g_Group);
3194
George Rimar91829ee2018-11-14 09:22:16 +00003195 Arg* SplitDWARFArg;
3196 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003197
George Rimar91829ee2018-11-14 09:22:16 +00003198 if (DwarfFission != DwarfFissionKind::None &&
3199 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3200 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003201 SplitDWARFInlining = false;
3202 }
3203
Fangrui Songe3576b02019-04-17 01:46:27 +00003204 if (const Arg *A =
3205 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3206 options::OPT_gsplit_dwarf_EQ)) {
3207 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3208
3209 // If the last option explicitly specified a debug-info level, use it.
3210 if (checkDebugInfoOption(A, Args, D, TC) &&
3211 A->getOption().matches(options::OPT_gN_Group)) {
3212 DebugInfoKind = DebugLevelToInfoKind(*A);
3213 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3214 // complicated if you've disabled inline info in the skeleton CUs
3215 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3216 // line-tables-only, so let those compose naturally in that case.
3217 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3218 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3219 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3220 SplitDWARFInlining))
3221 DwarfFission = DwarfFissionKind::None;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003222 }
3223 }
3224
3225 // If a debugger tuning argument appeared, remember it.
3226 if (const Arg *A =
3227 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003228 if (checkDebugInfoOption(A, Args, D, TC)) {
3229 if (A->getOption().matches(options::OPT_glldb))
3230 DebuggerTuning = llvm::DebuggerKind::LLDB;
3231 else if (A->getOption().matches(options::OPT_gsce))
3232 DebuggerTuning = llvm::DebuggerKind::SCE;
3233 else
3234 DebuggerTuning = llvm::DebuggerKind::GDB;
3235 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003236 }
3237
3238 // If a -gdwarf argument appeared, remember it.
3239 if (const Arg *A =
3240 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3241 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003242 if (checkDebugInfoOption(A, Args, D, TC))
3243 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003244
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003245 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3246 if (checkDebugInfoOption(A, Args, D, TC))
3247 EmitCodeView = true;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003248 }
3249
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003250 // If the user asked for debug info but did not explicitly specify -gcodeview
3251 // or -gdwarf, ask the toolchain for the default format.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003252 if (!EmitCodeView && DWARFVersion == 0 &&
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003253 DebugInfoKind != codegenoptions::NoDebugInfo) {
3254 switch (TC.getDefaultDebugFormat()) {
3255 case codegenoptions::DIF_CodeView:
3256 EmitCodeView = true;
3257 break;
3258 case codegenoptions::DIF_DWARF:
3259 DWARFVersion = TC.GetDefaultDwarfVersion();
3260 break;
3261 }
3262 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003263
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003264 // -gline-directives-only supported only for the DWARF debug info.
3265 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3266 DebugInfoKind = codegenoptions::NoDebugInfo;
3267
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003268 // We ignore flag -gstrict-dwarf for now.
3269 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3270 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3271
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003272 // Column info is included by default for everything except SCE and
3273 // CodeView. Clang doesn't track end columns, just starting columns, which,
3274 // in theory, is fine for CodeView (and PDB). In practice, however, the
3275 // Microsoft debuggers don't handle missing end columns well, so it's better
3276 // not to include any column info.
3277 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3278 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003279 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003280 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003281 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003282 CmdArgs.push_back("-dwarf-column-info");
3283
3284 // FIXME: Move backend command line options to the module.
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003285 // If -gline-tables-only or -gline-directives-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003286 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3287 if (checkDebugInfoOption(A, Args, D, TC)) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003288 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3289 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003290 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3291 CmdArgs.push_back("-dwarf-ext-refs");
3292 CmdArgs.push_back("-fmodule-format=obj");
3293 }
3294 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003295
Aaron Puchertb207bae2019-06-26 21:36:35 +00003296 if (T.isOSBinFormatELF() && !SplitDWARFInlining)
3297 CmdArgs.push_back("-fno-split-dwarf-inlining");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003298
3299 // After we've dealt with all combinations of things that could
3300 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3301 // figure out if we need to "upgrade" it to standalone debug info.
3302 // We parse these two '-f' options whether or not they will be used,
3303 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
David Blaikieb068f922019-04-16 00:16:29 +00003304 bool NeedFullDebug = Args.hasFlag(
3305 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3306 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3307 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003308 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3309 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003310 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3311 DebugInfoKind = codegenoptions::FullDebugInfo;
3312
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003313 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3314 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003315 // Source embedding is a vendor extension to DWARF v5. By now we have
3316 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003317 // fallen back to the target default, so if this is still not at least 5
3318 // we emit an error.
3319 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003320 if (DWARFVersion < 5)
3321 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003322 << A->getAsString(Args) << "-gdwarf-5";
3323 else if (checkDebugInfoOption(A, Args, D, TC))
3324 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003325 }
3326
Reid Kleckner75557712018-11-16 18:47:41 +00003327 if (EmitCodeView) {
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003328 CmdArgs.push_back("-gcodeview");
3329
Reid Kleckner75557712018-11-16 18:47:41 +00003330 // Emit codeview type hashes if requested.
3331 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3332 options::OPT_gno_codeview_ghash, false)) {
3333 CmdArgs.push_back("-gcodeview-ghash");
3334 }
3335 }
3336
Alexey Bataevc92fc3c2018-12-12 14:52:27 +00003337 // Adjust the debug info kind for the given toolchain.
3338 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3339
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003340 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3341 DebuggerTuning);
3342
3343 // -fdebug-macro turns on macro debug info generation.
3344 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3345 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003346 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3347 D, TC))
3348 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003349
3350 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003351 const auto *PubnamesArg =
3352 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3353 options::OPT_gpubnames, options::OPT_gno_pubnames);
George Rimar91829ee2018-11-14 09:22:16 +00003354 if (DwarfFission != DwarfFissionKind::None ||
3355 DebuggerTuning == llvm::DebuggerKind::LLDB ||
David Blaikie65864522018-08-20 20:14:08 +00003356 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3357 if (!PubnamesArg ||
3358 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3359 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3360 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3361 options::OPT_gpubnames)
3362 ? "-gpubnames"
3363 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003364
David Blaikie27692de2018-11-13 20:08:13 +00003365 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3366 options::OPT_fno_debug_ranges_base_address, false)) {
3367 CmdArgs.push_back("-fdebug-ranges-base-address");
3368 }
3369
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003370 // -gdwarf-aranges turns on the emission of the aranges section in the
3371 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003372 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003373 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3374 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3375 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3376 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003377 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003378 CmdArgs.push_back("-generate-arange-section");
3379 }
3380
3381 if (Args.hasFlag(options::OPT_fdebug_types_section,
3382 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003383 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003384 D.Diag(diag::err_drv_unsupported_opt_for_target)
3385 << Args.getLastArg(options::OPT_fdebug_types_section)
3386 ->getAsString(Args)
3387 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003388 } else if (checkDebugInfoOption(
3389 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3390 TC)) {
3391 CmdArgs.push_back("-mllvm");
3392 CmdArgs.push_back("-generate-type-units");
3393 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003394 }
3395
Paul Robinson1787f812017-09-28 18:37:02 +00003396 // Decide how to render forward declarations of template instantiations.
3397 // SCE wants full descriptions, others just get them in the name.
3398 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3399 CmdArgs.push_back("-debug-forward-template-params");
3400
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003401 // Do we need to explicitly import anonymous namespaces into the parent
3402 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003403 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3404 CmdArgs.push_back("-dwarf-explicit-import");
3405
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003406 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003407}
3408
David L. Jonesf561aba2017-03-08 01:02:16 +00003409void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3410 const InputInfo &Output, const InputInfoList &Inputs,
3411 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003412 const auto &TC = getToolChain();
3413 const llvm::Triple &RawTriple = TC.getTriple();
3414 const llvm::Triple &Triple = TC.getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003415 const std::string &TripleStr = Triple.getTriple();
3416
3417 bool KernelOrKext =
3418 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003419 const Driver &D = TC.getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00003420 ArgStringList CmdArgs;
3421
3422 // Check number of inputs for sanity. We need at least one input.
3423 assert(Inputs.size() >= 1 && "Must have at least one input.");
Yaxun Liu398612b2018-05-08 21:02:12 +00003424 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003425 // device-side compilations). OpenMP device jobs also take the host IR as a
Richard Smithcd35eff2018-09-15 01:21:16 +00003426 // second input. Module precompilation accepts a list of header files to
3427 // include as part of the module. All other jobs are expected to have exactly
3428 // one input.
David L. Jonesf561aba2017-03-08 01:02:16 +00003429 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003430 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003431 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Richard Smithcd35eff2018-09-15 01:21:16 +00003432 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3433
3434 // A header module compilation doesn't have a main input file, so invent a
3435 // fake one as a placeholder.
Richard Smithcd35eff2018-09-15 01:21:16 +00003436 const char *ModuleName = [&]{
3437 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3438 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3439 }();
Benjamin Kramer5904c412018-11-05 12:46:02 +00003440 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
Richard Smithcd35eff2018-09-15 01:21:16 +00003441
3442 const InputInfo &Input =
3443 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3444
3445 InputInfoList ModuleHeaderInputs;
3446 const InputInfo *CudaDeviceInput = nullptr;
3447 const InputInfo *OpenMPDeviceInput = nullptr;
3448 for (const InputInfo &I : Inputs) {
3449 if (&I == &Input) {
3450 // This is the primary input.
Benjamin Kramer5904c412018-11-05 12:46:02 +00003451 } else if (IsHeaderModulePrecompile &&
Richard Smithcd35eff2018-09-15 01:21:16 +00003452 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
Benjamin Kramer5904c412018-11-05 12:46:02 +00003453 types::ID Expected = HeaderModuleInput.getType();
Richard Smithcd35eff2018-09-15 01:21:16 +00003454 if (I.getType() != Expected) {
3455 D.Diag(diag::err_drv_module_header_wrong_kind)
3456 << I.getFilename() << types::getTypeName(I.getType())
3457 << types::getTypeName(Expected);
3458 }
3459 ModuleHeaderInputs.push_back(I);
3460 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3461 CudaDeviceInput = &I;
3462 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3463 OpenMPDeviceInput = &I;
3464 } else {
3465 llvm_unreachable("unexpectedly given multiple inputs");
3466 }
3467 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003468
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003469 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003470 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003471 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003472
Yaxun Liu398612b2018-05-08 21:02:12 +00003473 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3474 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3475 // Windows), we need to pass Windows-specific flags to cc1.
Fangrui Songe6e09562019-07-12 13:21:58 +00003476 if (IsCuda || IsHIP)
David L. Jonesf561aba2017-03-08 01:02:16 +00003477 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
David L. Jonesf561aba2017-03-08 01:02:16 +00003478
3479 // C++ is not supported for IAMCU.
3480 if (IsIAMCU && types::isCXX(Input.getType()))
3481 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3482
3483 // Invoke ourselves in -cc1 mode.
3484 //
3485 // FIXME: Implement custom jobs for internal actions.
3486 CmdArgs.push_back("-cc1");
3487
3488 // Add the "effective" target triple.
3489 CmdArgs.push_back("-triple");
3490 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3491
3492 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3493 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3494 Args.ClaimAllArgs(options::OPT_MJ);
3495 }
3496
Yaxun Liu398612b2018-05-08 21:02:12 +00003497 if (IsCuda || IsHIP) {
3498 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3499 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003500 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003501 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3502 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003503 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3504 ->getTriple()
3505 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003506 else {
3507 // Host-side compilation.
Yaxun Liu398612b2018-05-08 21:02:12 +00003508 NormalizedTriple =
3509 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3510 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3511 ->getTriple()
3512 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003513 if (IsCuda) {
3514 // We need to figure out which CUDA version we're compiling for, as that
3515 // determines how we load and launch GPU kernels.
3516 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3517 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3518 assert(CTC && "Expected valid CUDA Toolchain.");
3519 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3520 CmdArgs.push_back(Args.MakeArgString(
3521 Twine("-target-sdk-version=") +
3522 CudaVersionToString(CTC->CudaInstallation.version())));
3523 }
3524 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003525 CmdArgs.push_back("-aux-triple");
3526 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3527 }
3528
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003529 if (IsOpenMPDevice) {
3530 // We have to pass the triple of the host if compiling for an OpenMP device.
3531 std::string NormalizedTriple =
3532 C.getSingleOffloadToolChain<Action::OFK_Host>()
3533 ->getTriple()
3534 .normalize();
3535 CmdArgs.push_back("-aux-triple");
3536 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3537 }
3538
David L. Jonesf561aba2017-03-08 01:02:16 +00003539 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3540 Triple.getArch() == llvm::Triple::thumb)) {
3541 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3542 unsigned Version;
3543 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3544 if (Version < 7)
3545 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3546 << TripleStr;
3547 }
3548
3549 // Push all default warning arguments that are specific to
3550 // the given target. These come before user provided warning options
3551 // are provided.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003552 TC.addClangWarningOptions(CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003553
3554 // Select the appropriate action.
3555 RewriteKind rewriteKind = RK_None;
3556
Nico Weberb28ffd82019-07-27 01:13:00 +00003557 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
3558 // it claims when not running an assembler. Otherwise, clang would emit
3559 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
3560 // flags while debugging something. That'd be somewhat inconvenient, and it's
3561 // also inconsistent with most other flags -- we don't warn on
3562 // -ffunction-sections not being used in -E mode either for example, even
3563 // though it's not really used either.
3564 if (!isa<AssembleJobAction>(JA)) {
3565 // The args claimed here should match the args used in
3566 // CollectArgsForIntegratedAssembler().
3567 if (TC.useIntegratedAs()) {
3568 Args.ClaimAllArgs(options::OPT_mrelax_all);
3569 Args.ClaimAllArgs(options::OPT_mno_relax_all);
3570 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
3571 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
3572 switch (C.getDefaultToolChain().getArch()) {
3573 case llvm::Triple::arm:
3574 case llvm::Triple::armeb:
3575 case llvm::Triple::thumb:
3576 case llvm::Triple::thumbeb:
3577 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
Bjorn Pettersson60c1ee22019-07-27 17:09:08 +00003578 break;
Nico Weberb28ffd82019-07-27 01:13:00 +00003579 default:
3580 break;
3581 }
3582 }
3583 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
3584 Args.ClaimAllArgs(options::OPT_Xassembler);
3585 }
3586
David L. Jonesf561aba2017-03-08 01:02:16 +00003587 if (isa<AnalyzeJobAction>(JA)) {
3588 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3589 CmdArgs.push_back("-analyze");
3590 } else if (isa<MigrateJobAction>(JA)) {
3591 CmdArgs.push_back("-migrate");
3592 } else if (isa<PreprocessJobAction>(JA)) {
3593 if (Output.getType() == types::TY_Dependencies)
3594 CmdArgs.push_back("-Eonly");
3595 else {
3596 CmdArgs.push_back("-E");
3597 if (Args.hasArg(options::OPT_rewrite_objc) &&
3598 !Args.hasArg(options::OPT_g_Group))
3599 CmdArgs.push_back("-P");
3600 }
3601 } else if (isa<AssembleJobAction>(JA)) {
3602 CmdArgs.push_back("-emit-obj");
3603
3604 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3605
3606 // Also ignore explicit -force_cpusubtype_ALL option.
3607 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3608 } else if (isa<PrecompileJobAction>(JA)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003609 if (JA.getType() == types::TY_Nothing)
3610 CmdArgs.push_back("-fsyntax-only");
3611 else if (JA.getType() == types::TY_ModuleFile)
Richard Smithcd35eff2018-09-15 01:21:16 +00003612 CmdArgs.push_back(IsHeaderModulePrecompile
3613 ? "-emit-header-module"
3614 : "-emit-module-interface");
David L. Jonesf561aba2017-03-08 01:02:16 +00003615 else
Erich Keane0a6b5b62018-12-04 14:34:09 +00003616 CmdArgs.push_back("-emit-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00003617 } else if (isa<VerifyPCHJobAction>(JA)) {
3618 CmdArgs.push_back("-verify-pch");
3619 } else {
3620 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3621 "Invalid action for clang tool.");
3622 if (JA.getType() == types::TY_Nothing) {
3623 CmdArgs.push_back("-fsyntax-only");
3624 } else if (JA.getType() == types::TY_LLVM_IR ||
3625 JA.getType() == types::TY_LTO_IR) {
3626 CmdArgs.push_back("-emit-llvm");
3627 } else if (JA.getType() == types::TY_LLVM_BC ||
3628 JA.getType() == types::TY_LTO_BC) {
3629 CmdArgs.push_back("-emit-llvm-bc");
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003630 } else if (JA.getType() == types::TY_IFS) {
3631 StringRef StubFormat =
3632 llvm::StringSwitch<StringRef>(
3633 Args.hasArg(options::OPT_iterface_stub_version_EQ)
3634 ? Args.getLastArgValue(options::OPT_iterface_stub_version_EQ)
3635 : "")
3636 .Case("experimental-yaml-elf-v1", "experimental-yaml-elf-v1")
3637 .Case("experimental-tapi-elf-v1", "experimental-tapi-elf-v1")
3638 .Default("");
3639
3640 if (StubFormat.empty())
3641 D.Diag(diag::err_drv_invalid_value)
3642 << "Must specify a valid interface stub format type using "
3643 << "-interface-stub-version=<experimental-tapi-elf-v1 | "
3644 "experimental-yaml-elf-v1>";
3645
3646 CmdArgs.push_back("-emit-interface-stubs");
3647 CmdArgs.push_back(
3648 Args.MakeArgString(Twine("-interface-stub-version=") + StubFormat));
David L. Jonesf561aba2017-03-08 01:02:16 +00003649 } else if (JA.getType() == types::TY_PP_Asm) {
3650 CmdArgs.push_back("-S");
3651 } else if (JA.getType() == types::TY_AST) {
3652 CmdArgs.push_back("-emit-pch");
3653 } else if (JA.getType() == types::TY_ModuleFile) {
3654 CmdArgs.push_back("-module-file-info");
3655 } else if (JA.getType() == types::TY_RewrittenObjC) {
3656 CmdArgs.push_back("-rewrite-objc");
3657 rewriteKind = RK_NonFragile;
3658 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3659 CmdArgs.push_back("-rewrite-objc");
3660 rewriteKind = RK_Fragile;
3661 } else {
3662 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3663 }
3664
3665 // Preserve use-list order by default when emitting bitcode, so that
3666 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3667 // same result as running passes here. For LTO, we don't need to preserve
3668 // the use-list order, since serialization to bitcode is part of the flow.
3669 if (JA.getType() == types::TY_LLVM_BC)
3670 CmdArgs.push_back("-emit-llvm-uselists");
3671
Artem Belevichecb178b2018-03-21 22:22:59 +00003672 // Device-side jobs do not support LTO.
3673 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3674 JA.isDeviceOffloading(Action::OFK_Host));
3675
3676 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003677 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3678
Paul Robinsond23f2a82017-07-13 21:25:47 +00003679 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3680 // does not support LTO unit features (CFI, whole program vtable opt)
3681 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003682 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003683 D.getLTOMode() == LTOK_Full)
3684 CmdArgs.push_back("-flto-unit");
3685 }
3686 }
3687
3688 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3689 if (!types::isLLVMIR(Input.getType()))
Bob Haarman79434642019-07-15 20:51:44 +00003690 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003691 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3692 }
3693
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003694 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003695 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3696
David L. Jonesf561aba2017-03-08 01:02:16 +00003697 // Embed-bitcode option.
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003698 // Only white-listed flags below are allowed to be embedded.
David L. Jonesf561aba2017-03-08 01:02:16 +00003699 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3700 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3701 // Add flags implied by -fembed-bitcode.
3702 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3703 // Disable all llvm IR level optimizations.
3704 CmdArgs.push_back("-disable-llvm-passes");
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003705
Fangrui Song2632ebb2019-05-30 02:30:04 +00003706 // Render target options such as -fuse-init-array on modern ELF platforms.
3707 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3708
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003709 // reject options that shouldn't be supported in bitcode
3710 // also reject kernel/kext
3711 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3712 options::OPT_mkernel,
3713 options::OPT_fapple_kext,
3714 options::OPT_ffunction_sections,
3715 options::OPT_fno_function_sections,
3716 options::OPT_fdata_sections,
3717 options::OPT_fno_data_sections,
3718 options::OPT_funique_section_names,
3719 options::OPT_fno_unique_section_names,
3720 options::OPT_mrestrict_it,
3721 options::OPT_mno_restrict_it,
3722 options::OPT_mstackrealign,
3723 options::OPT_mno_stackrealign,
3724 options::OPT_mstack_alignment,
3725 options::OPT_mcmodel_EQ,
3726 options::OPT_mlong_calls,
3727 options::OPT_mno_long_calls,
3728 options::OPT_ggnu_pubnames,
3729 options::OPT_gdwarf_aranges,
3730 options::OPT_fdebug_types_section,
3731 options::OPT_fno_debug_types_section,
3732 options::OPT_fdwarf_directory_asm,
3733 options::OPT_fno_dwarf_directory_asm,
3734 options::OPT_mrelax_all,
3735 options::OPT_mno_relax_all,
3736 options::OPT_ftrap_function_EQ,
3737 options::OPT_ffixed_r9,
3738 options::OPT_mfix_cortex_a53_835769,
3739 options::OPT_mno_fix_cortex_a53_835769,
3740 options::OPT_ffixed_x18,
3741 options::OPT_mglobal_merge,
3742 options::OPT_mno_global_merge,
3743 options::OPT_mred_zone,
3744 options::OPT_mno_red_zone,
3745 options::OPT_Wa_COMMA,
3746 options::OPT_Xassembler,
3747 options::OPT_mllvm,
3748 };
3749 for (const auto &A : Args)
Fangrui Song75e74e02019-03-31 08:48:19 +00003750 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003751 std::end(kBitcodeOptionBlacklist))
3752 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3753
3754 // Render the CodeGen options that need to be passed.
3755 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3756 options::OPT_fno_optimize_sibling_calls))
3757 CmdArgs.push_back("-mdisable-tail-calls");
3758
3759 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3760 CmdArgs);
3761
3762 // Render ABI arguments
3763 switch (TC.getArch()) {
3764 default: break;
3765 case llvm::Triple::arm:
3766 case llvm::Triple::armeb:
3767 case llvm::Triple::thumbeb:
3768 RenderARMABI(Triple, Args, CmdArgs);
3769 break;
3770 case llvm::Triple::aarch64:
3771 case llvm::Triple::aarch64_be:
3772 RenderAArch64ABI(Triple, Args, CmdArgs);
3773 break;
3774 }
3775
3776 // Optimization level for CodeGen.
3777 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3778 if (A->getOption().matches(options::OPT_O4)) {
3779 CmdArgs.push_back("-O3");
3780 D.Diag(diag::warn_O4_is_O3);
3781 } else {
3782 A->render(Args, CmdArgs);
3783 }
3784 }
3785
3786 // Input/Output file.
3787 if (Output.getType() == types::TY_Dependencies) {
3788 // Handled with other dependency code.
3789 } else if (Output.isFilename()) {
3790 CmdArgs.push_back("-o");
3791 CmdArgs.push_back(Output.getFilename());
3792 } else {
3793 assert(Output.isNothing() && "Input output.");
3794 }
3795
3796 for (const auto &II : Inputs) {
3797 addDashXForInput(Args, II, CmdArgs);
3798 if (II.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00003799 CmdArgs.push_back(II.getFilename());
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003800 else
3801 II.getInputArg().renderAsInput(Args, CmdArgs);
3802 }
3803
3804 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3805 CmdArgs, Inputs));
3806 return;
David L. Jonesf561aba2017-03-08 01:02:16 +00003807 }
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003808
David L. Jonesf561aba2017-03-08 01:02:16 +00003809 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3810 CmdArgs.push_back("-fembed-bitcode=marker");
3811
3812 // We normally speed up the clang process a bit by skipping destructors at
3813 // exit, but when we're generating diagnostics we can rely on some of the
3814 // cleanup.
3815 if (!C.isForDiagnostics())
3816 CmdArgs.push_back("-disable-free");
3817
David L. Jonesf561aba2017-03-08 01:02:16 +00003818#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003819 const bool IsAssertBuild = false;
3820#else
3821 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003822#endif
3823
Eric Fiselier123c7492018-02-07 18:36:51 +00003824 // Disable the verification pass in -asserts builds.
3825 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003826 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003827
3828 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003829 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3830 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003831 CmdArgs.push_back("-discard-value-names");
3832
David L. Jonesf561aba2017-03-08 01:02:16 +00003833 // Set the main file name, so that debug info works even with
3834 // -save-temps.
3835 CmdArgs.push_back("-main-file-name");
3836 CmdArgs.push_back(getBaseInputName(Args, Input));
3837
3838 // Some flags which affect the language (via preprocessor
3839 // defines).
3840 if (Args.hasArg(options::OPT_static))
3841 CmdArgs.push_back("-static-define");
3842
Martin Storsjo434ef832018-08-06 19:48:44 +00003843 if (Args.hasArg(options::OPT_municode))
3844 CmdArgs.push_back("-DUNICODE");
3845
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003846 if (isa<AnalyzeJobAction>(JA))
3847 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003848
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003849 // Enable compatilibily mode to avoid analyzer-config related errors.
3850 // Since we can't access frontend flags through hasArg, let's manually iterate
3851 // through them.
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003852 bool FoundAnalyzerConfig = false;
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003853 for (auto Arg : Args.filtered(options::OPT_Xclang))
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003854 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3855 FoundAnalyzerConfig = true;
3856 break;
3857 }
3858 if (!FoundAnalyzerConfig)
3859 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3860 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3861 FoundAnalyzerConfig = true;
3862 break;
3863 }
3864 if (FoundAnalyzerConfig)
3865 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003866
David L. Jonesf561aba2017-03-08 01:02:16 +00003867 CheckCodeGenerationOptions(D, Args);
3868
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003869 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003870 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3871 if (FunctionAlignment) {
3872 CmdArgs.push_back("-function-alignment");
3873 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3874 }
3875
David L. Jonesf561aba2017-03-08 01:02:16 +00003876 llvm::Reloc::Model RelocationModel;
3877 unsigned PICLevel;
3878 bool IsPIE;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003879 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003880
3881 const char *RMName = RelocationModelName(RelocationModel);
3882
3883 if ((RelocationModel == llvm::Reloc::ROPI ||
3884 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3885 types::isCXX(Input.getType()) &&
3886 !Args.hasArg(options::OPT_fallow_unsupported))
3887 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3888
3889 if (RMName) {
3890 CmdArgs.push_back("-mrelocation-model");
3891 CmdArgs.push_back(RMName);
3892 }
3893 if (PICLevel > 0) {
3894 CmdArgs.push_back("-pic-level");
3895 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3896 if (IsPIE)
3897 CmdArgs.push_back("-pic-is-pie");
3898 }
3899
Oliver Stannarde3c8ce82019-02-18 12:39:47 +00003900 if (RelocationModel == llvm::Reloc::ROPI ||
3901 RelocationModel == llvm::Reloc::ROPI_RWPI)
3902 CmdArgs.push_back("-fropi");
3903 if (RelocationModel == llvm::Reloc::RWPI ||
3904 RelocationModel == llvm::Reloc::ROPI_RWPI)
3905 CmdArgs.push_back("-frwpi");
3906
David L. Jonesf561aba2017-03-08 01:02:16 +00003907 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3908 CmdArgs.push_back("-meabi");
3909 CmdArgs.push_back(A->getValue());
3910 }
3911
3912 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003913 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003914 if (!TC.isThreadModelSupported(A->getValue()))
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003915 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3916 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003917 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003918 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003919 else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00003920 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003921
3922 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3923
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003924 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3925 options::OPT_fno_merge_all_constants, false))
3926 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003927
Manoj Guptada08f6a2018-07-19 00:44:52 +00003928 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3929 options::OPT_fdelete_null_pointer_checks, false))
3930 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3931
David L. Jonesf561aba2017-03-08 01:02:16 +00003932 // LLVM Code Generator Options.
3933
3934 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3935 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3936 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3937 options::OPT_frewrite_map_file_EQ)) {
3938 StringRef Map = A->getValue();
3939 if (!llvm::sys::fs::exists(Map)) {
3940 D.Diag(diag::err_drv_no_such_file) << Map;
3941 } else {
3942 CmdArgs.push_back("-frewrite-map-file");
3943 CmdArgs.push_back(A->getValue());
3944 A->claim();
3945 }
3946 }
3947 }
3948
3949 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3950 StringRef v = A->getValue();
3951 CmdArgs.push_back("-mllvm");
3952 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3953 A->claim();
3954 }
3955
3956 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3957 true))
3958 CmdArgs.push_back("-fno-jump-tables");
3959
Dehao Chen5e97f232017-08-24 21:37:33 +00003960 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3961 options::OPT_fno_profile_sample_accurate, false))
3962 CmdArgs.push_back("-fprofile-sample-accurate");
3963
David L. Jonesf561aba2017-03-08 01:02:16 +00003964 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3965 options::OPT_fno_preserve_as_comments, true))
3966 CmdArgs.push_back("-fno-preserve-as-comments");
3967
3968 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3969 CmdArgs.push_back("-mregparm");
3970 CmdArgs.push_back(A->getValue());
3971 }
3972
3973 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3974 options::OPT_freg_struct_return)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003975 if (TC.getArch() != llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003976 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003977 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003978 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3979 CmdArgs.push_back("-fpcc-struct-return");
3980 } else {
3981 assert(A->getOption().matches(options::OPT_freg_struct_return));
3982 CmdArgs.push_back("-freg-struct-return");
3983 }
3984 }
3985
3986 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3987 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3988
Yuanfang Chenff22ec32019-07-20 22:50:50 +00003989 CodeGenOptions::FramePointerKind FPKeepKind =
3990 getFramePointerKind(Args, RawTriple);
3991 const char *FPKeepKindStr = nullptr;
3992 switch (FPKeepKind) {
3993 case CodeGenOptions::FramePointerKind::None:
3994 FPKeepKindStr = "-mframe-pointer=none";
3995 break;
3996 case CodeGenOptions::FramePointerKind::NonLeaf:
3997 FPKeepKindStr = "-mframe-pointer=non-leaf";
3998 break;
3999 case CodeGenOptions::FramePointerKind::All:
4000 FPKeepKindStr = "-mframe-pointer=all";
4001 break;
Fangrui Songdc039662019-07-12 02:01:51 +00004002 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +00004003 assert(FPKeepKindStr && "unknown FramePointerKind");
4004 CmdArgs.push_back(FPKeepKindStr);
4005
David L. Jonesf561aba2017-03-08 01:02:16 +00004006 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4007 options::OPT_fno_zero_initialized_in_bss))
4008 CmdArgs.push_back("-mno-zero-initialized-in-bss");
4009
4010 bool OFastEnabled = isOptimizationLevelFast(Args);
4011 // If -Ofast is the optimization level, then -fstrict-aliasing should be
4012 // enabled. This alias option is being used to simplify the hasFlag logic.
4013 OptSpecifier StrictAliasingAliasOption =
4014 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4015 // We turn strict aliasing off by default if we're in CL mode, since MSVC
4016 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004017 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004018 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4019 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4020 CmdArgs.push_back("-relaxed-aliasing");
4021 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4022 options::OPT_fno_struct_path_tbaa))
4023 CmdArgs.push_back("-no-struct-path-tbaa");
4024 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4025 false))
4026 CmdArgs.push_back("-fstrict-enums");
4027 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4028 true))
4029 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00004030 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
4031 options::OPT_fno_allow_editor_placeholders, false))
4032 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00004033 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4034 options::OPT_fno_strict_vtable_pointers,
4035 false))
4036 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00004037 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
4038 options::OPT_fno_force_emit_vtables,
4039 false))
4040 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00004041 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4042 options::OPT_fno_optimize_sibling_calls))
4043 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00004044 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00004045 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00004046 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00004047
Wei Mi9b3d6272017-10-16 16:50:27 +00004048 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4049 options::OPT_fno_fine_grained_bitfield_accesses);
4050
David L. Jonesf561aba2017-03-08 01:02:16 +00004051 // Handle segmented stacks.
4052 if (Args.hasArg(options::OPT_fsplit_stack))
4053 CmdArgs.push_back("-split-stacks");
4054
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004055 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004056
Fangrui Songc46d78d2019-07-12 02:32:15 +00004057 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_64,
4058 options::OPT_mlong_double_128)) {
Fangrui Song11cb39c2019-07-09 00:27:43 +00004059 if (TC.getArch() == llvm::Triple::x86 ||
4060 TC.getArch() == llvm::Triple::x86_64 ||
Fangrui Songc46d78d2019-07-12 02:32:15 +00004061 TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64())
4062 A->render(Args, CmdArgs);
4063 else
Fangrui Song11cb39c2019-07-09 00:27:43 +00004064 D.Diag(diag::err_drv_unsupported_opt_for_target)
4065 << A->getAsString(Args) << TripleStr;
Fangrui Song11cb39c2019-07-09 00:27:43 +00004066 }
4067
David L. Jonesf561aba2017-03-08 01:02:16 +00004068 // Decide whether to use verbose asm. Verbose assembly is the default on
4069 // toolchains which have the integrated assembler on by default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004070 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00004071 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4072 IsIntegratedAssemblerDefault) ||
4073 Args.hasArg(options::OPT_dA))
4074 CmdArgs.push_back("-masm-verbose");
4075
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004076 if (!TC.useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00004077 CmdArgs.push_back("-no-integrated-as");
4078
4079 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4080 CmdArgs.push_back("-mdebug-pass");
4081 CmdArgs.push_back("Structure");
4082 }
4083 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4084 CmdArgs.push_back("-mdebug-pass");
4085 CmdArgs.push_back("Arguments");
4086 }
4087
4088 // Enable -mconstructor-aliases except on darwin, where we have to work around
4089 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4090 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004091 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00004092 CmdArgs.push_back("-mconstructor-aliases");
4093
4094 // Darwin's kernel doesn't support guard variables; just die if we
4095 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004096 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00004097 CmdArgs.push_back("-fforbid-guard-variables");
4098
4099 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4100 false)) {
4101 CmdArgs.push_back("-mms-bitfields");
4102 }
4103
4104 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4105 options::OPT_mno_pie_copy_relocations,
4106 false)) {
4107 CmdArgs.push_back("-mpie-copy-relocations");
4108 }
4109
Sriraman Tallam5c651482017-11-07 19:37:51 +00004110 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4111 CmdArgs.push_back("-fno-plt");
4112 }
4113
Vedant Kumardf502592017-09-12 22:51:53 +00004114 // -fhosted is default.
4115 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4116 // use Freestanding.
4117 bool Freestanding =
4118 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4119 KernelOrKext;
4120 if (Freestanding)
4121 CmdArgs.push_back("-ffreestanding");
4122
David L. Jonesf561aba2017-03-08 01:02:16 +00004123 // This is a coarse approximation of what llvm-gcc actually does, both
4124 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4125 // complicated ways.
4126 bool AsynchronousUnwindTables =
4127 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4128 options::OPT_fno_asynchronous_unwind_tables,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004129 (TC.IsUnwindTablesDefault(Args) ||
4130 TC.getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00004131 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00004132 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4133 AsynchronousUnwindTables))
4134 CmdArgs.push_back("-munwind-tables");
4135
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004136 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00004137
David L. Jonesf561aba2017-03-08 01:02:16 +00004138 // FIXME: Handle -mtune=.
4139 (void)Args.hasArg(options::OPT_mtune_EQ);
4140
4141 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4142 CmdArgs.push_back("-mcode-model");
4143 CmdArgs.push_back(A->getValue());
4144 }
4145
4146 // Add the target cpu
4147 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4148 if (!CPU.empty()) {
4149 CmdArgs.push_back("-target-cpu");
4150 CmdArgs.push_back(Args.MakeArgString(CPU));
4151 }
4152
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00004153 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004154
David L. Jonesf561aba2017-03-08 01:02:16 +00004155 // These two are potentially updated by AddClangCLArgs.
4156 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4157 bool EmitCodeView = false;
4158
4159 // Add clang-cl arguments.
4160 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004161 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00004162 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4163
George Rimar91829ee2018-11-14 09:22:16 +00004164 DwarfFissionKind DwarfFission;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004165 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
George Rimar91829ee2018-11-14 09:22:16 +00004166 CmdArgs, DebugInfoKind, DwarfFission);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004167
4168 // Add the split debug info name to the command lines here so we
4169 // can propagate it to the backend.
George Rimar91829ee2018-11-14 09:22:16 +00004170 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
Fangrui Songee957e02019-03-28 08:24:00 +00004171 TC.getTriple().isOSBinFormatELF() &&
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004172 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4173 isa<BackendJobAction>(JA));
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004174 if (SplitDWARF) {
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004175 const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
4176 CmdArgs.push_back("-split-dwarf-file");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004177 CmdArgs.push_back(SplitDWARFOut);
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004178 if (DwarfFission == DwarfFissionKind::Split) {
4179 CmdArgs.push_back("-split-dwarf-output");
4180 CmdArgs.push_back(SplitDWARFOut);
4181 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004182 }
4183
David L. Jonesf561aba2017-03-08 01:02:16 +00004184 // Pass the linker version in use.
4185 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4186 CmdArgs.push_back("-target-linker-version");
4187 CmdArgs.push_back(A->getValue());
4188 }
4189
David L. Jonesf561aba2017-03-08 01:02:16 +00004190 // Explicitly error on some things we know we don't support and can't just
4191 // ignore.
4192 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4193 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004194 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004195 TC.getArch() == llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004196 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4197 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4198 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4199 << Unsupported->getOption().getName();
4200 }
Eric Christopher758aad72017-03-21 22:06:18 +00004201 // The faltivec option has been superseded by the maltivec option.
4202 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4203 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4204 << Unsupported->getOption().getName()
4205 << "please use -maltivec and include altivec.h explicitly";
4206 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4207 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4208 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00004209 }
4210
4211 Args.AddAllArgs(CmdArgs, options::OPT_v);
4212 Args.AddLastArg(CmdArgs, options::OPT_H);
4213 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4214 CmdArgs.push_back("-header-include-file");
4215 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4216 : "-");
4217 }
4218 Args.AddLastArg(CmdArgs, options::OPT_P);
4219 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4220
4221 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4222 CmdArgs.push_back("-diagnostic-log-file");
4223 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4224 : "-");
4225 }
4226
David L. Jonesf561aba2017-03-08 01:02:16 +00004227 bool UseSeparateSections = isUseSeparateSections(Triple);
4228
4229 if (Args.hasFlag(options::OPT_ffunction_sections,
4230 options::OPT_fno_function_sections, UseSeparateSections)) {
4231 CmdArgs.push_back("-ffunction-sections");
4232 }
4233
4234 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4235 UseSeparateSections)) {
4236 CmdArgs.push_back("-fdata-sections");
4237 }
4238
4239 if (!Args.hasFlag(options::OPT_funique_section_names,
4240 options::OPT_fno_unique_section_names, true))
4241 CmdArgs.push_back("-fno-unique-section-names");
4242
Nico Weber908b6972019-06-26 17:51:47 +00004243 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
4244 options::OPT_finstrument_functions_after_inlining,
4245 options::OPT_finstrument_function_entry_bare);
David L. Jonesf561aba2017-03-08 01:02:16 +00004246
Artem Belevichc30bcad2018-01-24 17:41:02 +00004247 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4248 // sampling, overhead of call arc collection is way too high and there's no
4249 // way to collect the output.
4250 if (!Triple.isNVPTX())
Russell Gallop7a9ccf82019-05-14 14:01:40 +00004251 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004252
Nico Weber908b6972019-06-26 17:51:47 +00004253 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
Richard Smithf667ad52017-08-26 01:04:35 +00004254
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004255 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
Pierre Gousseau53b5cfb2018-12-18 17:03:35 +00004256 if (RawTriple.isPS4CPU() &&
4257 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004258 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4259 PS4cpu::addSanitizerArgs(TC, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004260 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004261
4262 // Pass options for controlling the default header search paths.
4263 if (Args.hasArg(options::OPT_nostdinc)) {
4264 CmdArgs.push_back("-nostdsysteminc");
4265 CmdArgs.push_back("-nobuiltininc");
4266 } else {
4267 if (Args.hasArg(options::OPT_nostdlibinc))
4268 CmdArgs.push_back("-nostdsysteminc");
4269 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4270 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4271 }
4272
4273 // Pass the path to compiler resource files.
4274 CmdArgs.push_back("-resource-dir");
4275 CmdArgs.push_back(D.ResourceDir.c_str());
4276
4277 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4278
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00004279 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004280
4281 // Add preprocessing options like -I, -D, etc. if we are using the
4282 // preprocessor.
4283 //
4284 // FIXME: Support -fpreprocessed
4285 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4286 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4287
4288 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4289 // that "The compiler can only warn and ignore the option if not recognized".
4290 // When building with ccache, it will pass -D options to clang even on
4291 // preprocessed inputs and configure concludes that -fPIC is not supported.
4292 Args.ClaimAllArgs(options::OPT_D);
4293
4294 // Manually translate -O4 to -O3; let clang reject others.
4295 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4296 if (A->getOption().matches(options::OPT_O4)) {
4297 CmdArgs.push_back("-O3");
4298 D.Diag(diag::warn_O4_is_O3);
4299 } else {
4300 A->render(Args, CmdArgs);
4301 }
4302 }
4303
4304 // Warn about ignored options to clang.
4305 for (const Arg *A :
4306 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4307 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4308 A->claim();
4309 }
4310
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00004311 for (const Arg *A :
4312 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4313 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4314 A->claim();
4315 }
4316
David L. Jonesf561aba2017-03-08 01:02:16 +00004317 claimNoWarnArgs(Args);
4318
4319 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4320
4321 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4322 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4323 CmdArgs.push_back("-pedantic");
4324 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4325 Args.AddLastArg(CmdArgs, options::OPT_w);
4326
Leonard Chanf921d852018-06-04 16:07:52 +00004327 // Fixed point flags
4328 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4329 /*Default=*/false))
4330 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4331
David L. Jonesf561aba2017-03-08 01:02:16 +00004332 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4333 // (-ansi is equivalent to -std=c89 or -std=c++98).
4334 //
4335 // If a std is supplied, only add -trigraphs if it follows the
4336 // option.
4337 bool ImplyVCPPCXXVer = false;
Richard Smithb1b580e2019-04-14 11:11:37 +00004338 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
4339 if (Std) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004340 if (Std->getOption().matches(options::OPT_ansi))
4341 if (types::isCXX(InputType))
4342 CmdArgs.push_back("-std=c++98");
4343 else
4344 CmdArgs.push_back("-std=c89");
4345 else
4346 Std->render(Args, CmdArgs);
4347
4348 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4349 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4350 options::OPT_ftrigraphs,
4351 options::OPT_fno_trigraphs))
4352 if (A != Std)
4353 A->render(Args, CmdArgs);
4354 } else {
4355 // Honor -std-default.
4356 //
4357 // FIXME: Clang doesn't correctly handle -std= when the input language
4358 // doesn't match. For the time being just ignore this for C++ inputs;
4359 // eventually we want to do all the standard defaulting here instead of
4360 // splitting it between the driver and clang -cc1.
4361 if (!types::isCXX(InputType))
4362 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4363 /*Joined=*/true);
4364 else if (IsWindowsMSVC)
4365 ImplyVCPPCXXVer = true;
4366
4367 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4368 options::OPT_fno_trigraphs);
4369 }
4370
4371 // GCC's behavior for -Wwrite-strings is a bit strange:
4372 // * In C, this "warning flag" changes the types of string literals from
4373 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4374 // for the discarded qualifier.
4375 // * In C++, this is just a normal warning flag.
4376 //
4377 // Implementing this warning correctly in C is hard, so we follow GCC's
4378 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4379 // a non-const char* in C, rather than using this crude hack.
4380 if (!types::isCXX(InputType)) {
4381 // FIXME: This should behave just like a warning flag, and thus should also
4382 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4383 Arg *WriteStrings =
4384 Args.getLastArg(options::OPT_Wwrite_strings,
4385 options::OPT_Wno_write_strings, options::OPT_w);
4386 if (WriteStrings &&
4387 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4388 CmdArgs.push_back("-fconst-strings");
4389 }
4390
4391 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4392 // during C++ compilation, which it is by default. GCC keeps this define even
4393 // in the presence of '-w', match this behavior bug-for-bug.
4394 if (types::isCXX(InputType) &&
4395 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4396 true)) {
4397 CmdArgs.push_back("-fdeprecated-macro");
4398 }
4399
4400 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4401 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4402 if (Asm->getOption().matches(options::OPT_fasm))
4403 CmdArgs.push_back("-fgnu-keywords");
4404 else
4405 CmdArgs.push_back("-fno-gnu-keywords");
4406 }
4407
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004408 if (ShouldDisableDwarfDirectory(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004409 CmdArgs.push_back("-fno-dwarf-directory-asm");
4410
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004411 if (ShouldDisableAutolink(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004412 CmdArgs.push_back("-fno-autolink");
4413
4414 // Add in -fdebug-compilation-dir if necessary.
Michael J. Spencer7e48b402019-05-28 22:21:47 +00004415 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
David L. Jonesf561aba2017-03-08 01:02:16 +00004416
Paul Robinson9b292b42018-07-10 15:15:24 +00004417 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004418
4419 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4420 options::OPT_ftemplate_depth_EQ)) {
4421 CmdArgs.push_back("-ftemplate-depth");
4422 CmdArgs.push_back(A->getValue());
4423 }
4424
4425 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4426 CmdArgs.push_back("-foperator-arrow-depth");
4427 CmdArgs.push_back(A->getValue());
4428 }
4429
4430 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4431 CmdArgs.push_back("-fconstexpr-depth");
4432 CmdArgs.push_back(A->getValue());
4433 }
4434
4435 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4436 CmdArgs.push_back("-fconstexpr-steps");
4437 CmdArgs.push_back(A->getValue());
4438 }
4439
4440 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4441 CmdArgs.push_back("-fbracket-depth");
4442 CmdArgs.push_back(A->getValue());
4443 }
4444
4445 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4446 options::OPT_Wlarge_by_value_copy_def)) {
4447 if (A->getNumValues()) {
4448 StringRef bytes = A->getValue();
4449 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4450 } else
4451 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4452 }
4453
4454 if (Args.hasArg(options::OPT_relocatable_pch))
4455 CmdArgs.push_back("-relocatable-pch");
4456
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004457 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4458 static const char *kCFABIs[] = {
4459 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4460 };
4461
4462 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4463 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4464 else
4465 A->render(Args, CmdArgs);
4466 }
4467
David L. Jonesf561aba2017-03-08 01:02:16 +00004468 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4469 CmdArgs.push_back("-fconstant-string-class");
4470 CmdArgs.push_back(A->getValue());
4471 }
4472
4473 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4474 CmdArgs.push_back("-ftabstop");
4475 CmdArgs.push_back(A->getValue());
4476 }
4477
Sean Eveson5110d4f2018-01-08 13:42:26 +00004478 if (Args.hasFlag(options::OPT_fstack_size_section,
4479 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4480 CmdArgs.push_back("-fstack-size-section");
4481
David L. Jonesf561aba2017-03-08 01:02:16 +00004482 CmdArgs.push_back("-ferror-limit");
4483 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4484 CmdArgs.push_back(A->getValue());
4485 else
4486 CmdArgs.push_back("19");
4487
4488 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4489 CmdArgs.push_back("-fmacro-backtrace-limit");
4490 CmdArgs.push_back(A->getValue());
4491 }
4492
4493 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4494 CmdArgs.push_back("-ftemplate-backtrace-limit");
4495 CmdArgs.push_back(A->getValue());
4496 }
4497
4498 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4499 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4500 CmdArgs.push_back(A->getValue());
4501 }
4502
4503 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4504 CmdArgs.push_back("-fspell-checking-limit");
4505 CmdArgs.push_back(A->getValue());
4506 }
4507
4508 // Pass -fmessage-length=.
4509 CmdArgs.push_back("-fmessage-length");
4510 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4511 CmdArgs.push_back(A->getValue());
4512 } else {
4513 // If -fmessage-length=N was not specified, determine whether this is a
4514 // terminal and, if so, implicitly define -fmessage-length appropriately.
4515 unsigned N = llvm::sys::Process::StandardErrColumns();
4516 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4517 }
4518
4519 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4520 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4521 options::OPT_fvisibility_ms_compat)) {
4522 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4523 CmdArgs.push_back("-fvisibility");
4524 CmdArgs.push_back(A->getValue());
4525 } else {
4526 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4527 CmdArgs.push_back("-fvisibility");
4528 CmdArgs.push_back("hidden");
4529 CmdArgs.push_back("-ftype-visibility");
4530 CmdArgs.push_back("default");
4531 }
4532 }
4533
4534 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
Petr Hosek821b38f2018-12-04 03:25:25 +00004535 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
David L. Jonesf561aba2017-03-08 01:02:16 +00004536
4537 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4538
David L. Jonesf561aba2017-03-08 01:02:16 +00004539 // Forward -f (flag) options which we can pass directly.
4540 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4541 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004542 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004543 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004544 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4545 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004546 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004547
David L. Jonesf561aba2017-03-08 01:02:16 +00004548 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004549 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004550 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004551
David L. Jonesf561aba2017-03-08 01:02:16 +00004552 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4553 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4554
4555 // Forward flags for OpenMP. We don't do this if the current action is an
4556 // device offloading action other than OpenMP.
4557 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4558 options::OPT_fno_openmp, false) &&
4559 (JA.isDeviceOffloading(Action::OFK_None) ||
4560 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004561 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004562 case Driver::OMPRT_OMP:
4563 case Driver::OMPRT_IOMP5:
4564 // Clang can generate useful OpenMP code for these two runtime libraries.
4565 CmdArgs.push_back("-fopenmp");
4566
4567 // If no option regarding the use of TLS in OpenMP codegeneration is
4568 // given, decide a default based on the target. Otherwise rely on the
4569 // options and pass the right information to the frontend.
4570 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4571 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4572 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004573 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4574 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004575 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Alexey Bataeve4090182018-11-02 14:54:07 +00004576 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4577 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004578 Args.AddAllArgs(CmdArgs,
4579 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004580 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4581 options::OPT_fno_openmp_optimistic_collapse,
4582 /*Default=*/false))
4583 CmdArgs.push_back("-fopenmp-optimistic-collapse");
Carlo Bertolli79712092018-02-28 20:48:35 +00004584
4585 // When in OpenMP offloading mode with NVPTX target, forward
4586 // cuda-mode flag
Alexey Bataev80a9a612018-08-30 14:45:24 +00004587 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4588 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4589 CmdArgs.push_back("-fopenmp-cuda-mode");
4590
4591 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4592 // is required.
4593 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4594 options::OPT_fno_openmp_cuda_force_full_runtime,
4595 /*Default=*/false))
4596 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
David L. Jonesf561aba2017-03-08 01:02:16 +00004597 break;
4598 default:
4599 // By default, if Clang doesn't know how to generate useful OpenMP code
4600 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4601 // down to the actual compilation.
4602 // FIXME: It would be better to have a mode which *only* omits IR
4603 // generation based on the OpenMP support so that we get consistent
4604 // semantic analysis, etc.
4605 break;
4606 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004607 } else {
4608 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4609 options::OPT_fno_openmp_simd);
4610 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004611 }
4612
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004613 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4614 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
David L. Jonesf561aba2017-03-08 01:02:16 +00004615
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004616 const XRayArgs &XRay = TC.getXRayArgs();
4617 XRay.addArgs(TC, Args, CmdArgs, InputType);
Dean Michael Berris835832d2017-03-30 00:29:36 +00004618
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004619 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004620 Args.AddLastArg(CmdArgs, options::OPT_pg);
4621
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004622 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004623 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4624
4625 // -flax-vector-conversions is default.
4626 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4627 options::OPT_fno_lax_vector_conversions))
4628 CmdArgs.push_back("-fno-lax-vector-conversions");
4629
4630 if (Args.getLastArg(options::OPT_fapple_kext) ||
4631 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4632 CmdArgs.push_back("-fapple-kext");
4633
4634 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4635 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4636 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4637 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
Anton Afanasyevd880de22019-03-30 08:42:48 +00004638 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +00004639 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004640 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
Craig Topper3205dbb2019-03-21 20:07:24 +00004641 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
David L. Jonesf561aba2017-03-08 01:02:16 +00004642
4643 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4644 CmdArgs.push_back("-ftrapv-handler");
4645 CmdArgs.push_back(A->getValue());
4646 }
4647
4648 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4649
4650 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4651 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4652 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4653 if (A->getOption().matches(options::OPT_fwrapv))
4654 CmdArgs.push_back("-fwrapv");
4655 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4656 options::OPT_fno_strict_overflow)) {
4657 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4658 CmdArgs.push_back("-fwrapv");
4659 }
4660
4661 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4662 options::OPT_fno_reroll_loops))
4663 if (A->getOption().matches(options::OPT_freroll_loops))
4664 CmdArgs.push_back("-freroll-loops");
4665
4666 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4667 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4668 options::OPT_fno_unroll_loops);
4669
4670 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4671
Zola Bridgesc8666792018-11-26 18:13:31 +00004672 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4673 false))
4674 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
Chandler Carruth664aa862018-09-04 12:38:00 +00004675
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004676 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
JF Bastien14daa202018-12-18 05:12:21 +00004677 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004678
4679 // Translate -mstackrealign
4680 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4681 false))
4682 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4683
4684 if (Args.hasArg(options::OPT_mstack_alignment)) {
4685 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4686 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4687 }
4688
4689 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4690 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4691
4692 if (!Size.empty())
4693 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4694 else
4695 CmdArgs.push_back("-mstack-probe-size=0");
4696 }
4697
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004698 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4699 options::OPT_mno_stack_arg_probe, true))
4700 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4701
David L. Jonesf561aba2017-03-08 01:02:16 +00004702 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4703 options::OPT_mno_restrict_it)) {
4704 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004705 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004706 CmdArgs.push_back("-arm-restrict-it");
4707 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004708 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004709 CmdArgs.push_back("-arm-no-restrict-it");
4710 }
4711 } else if (Triple.isOSWindows() &&
4712 (Triple.getArch() == llvm::Triple::arm ||
4713 Triple.getArch() == llvm::Triple::thumb)) {
4714 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004715 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004716 CmdArgs.push_back("-arm-restrict-it");
4717 }
4718
4719 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004720 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004721
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004722 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4723 CmdArgs.push_back(
4724 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4725 }
4726
David L. Jonesf561aba2017-03-08 01:02:16 +00004727 // Forward -f options with positive and negative forms; we translate
4728 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004729 if (Arg *A = getLastProfileSampleUseArg(Args)) {
Rong Xua4a09b22019-03-04 20:21:31 +00004730 auto *PGOArg = Args.getLastArg(
4731 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4732 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4733 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4734 if (PGOArg)
4735 D.Diag(diag::err_drv_argument_not_allowed_with)
4736 << "SampleUse with PGO options";
4737
David L. Jonesf561aba2017-03-08 01:02:16 +00004738 StringRef fname = A->getValue();
4739 if (!llvm::sys::fs::exists(fname))
4740 D.Diag(diag::err_drv_no_such_file) << fname;
4741 else
4742 A->render(Args, CmdArgs);
4743 }
Richard Smith8654ae52018-10-10 23:13:35 +00004744 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004745
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004746 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004747
4748 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4749 options::OPT_fno_assume_sane_operator_new))
4750 CmdArgs.push_back("-fno-assume-sane-operator-new");
4751
4752 // -fblocks=0 is default.
4753 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004754 TC.IsBlocksDefault()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004755 (Args.hasArg(options::OPT_fgnu_runtime) &&
4756 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4757 !Args.hasArg(options::OPT_fno_blocks))) {
4758 CmdArgs.push_back("-fblocks");
4759
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004760 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
David L. Jonesf561aba2017-03-08 01:02:16 +00004761 CmdArgs.push_back("-fblocks-runtime-optional");
4762 }
4763
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004764 // -fencode-extended-block-signature=1 is default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004765 if (TC.IsEncodeExtendedBlockSignatureDefault())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004766 CmdArgs.push_back("-fencode-extended-block-signature");
4767
David L. Jonesf561aba2017-03-08 01:02:16 +00004768 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4769 false) &&
4770 types::isCXX(InputType)) {
4771 CmdArgs.push_back("-fcoroutines-ts");
4772 }
4773
Aaron Ballman61736552017-10-21 20:28:58 +00004774 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4775 options::OPT_fno_double_square_bracket_attributes);
4776
David L. Jonesf561aba2017-03-08 01:02:16 +00004777 // -faccess-control is default.
4778 if (Args.hasFlag(options::OPT_fno_access_control,
4779 options::OPT_faccess_control, false))
4780 CmdArgs.push_back("-fno-access-control");
4781
4782 // -felide-constructors is the default.
4783 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4784 options::OPT_felide_constructors, false))
4785 CmdArgs.push_back("-fno-elide-constructors");
4786
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004787 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004788
4789 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004790 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004791 CmdArgs.push_back("-fno-rtti");
4792
4793 // -fshort-enums=0 is default for all architectures except Hexagon.
4794 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004795 TC.getArch() == llvm::Triple::hexagon))
David L. Jonesf561aba2017-03-08 01:02:16 +00004796 CmdArgs.push_back("-fshort-enums");
4797
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004798 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004799
4800 // -fuse-cxa-atexit is default.
4801 if (!Args.hasFlag(
4802 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004803 !RawTriple.isOSWindows() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004804 TC.getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004805 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4806 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004807 KernelOrKext)
4808 CmdArgs.push_back("-fno-use-cxa-atexit");
4809
Akira Hatanaka617e2612018-04-17 18:41:52 +00004810 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4811 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004812 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004813 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4814
David L. Jonesf561aba2017-03-08 01:02:16 +00004815 // -fms-extensions=0 is default.
4816 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4817 IsWindowsMSVC))
4818 CmdArgs.push_back("-fms-extensions");
4819
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004820 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004821 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004822 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004823 CmdArgs.push_back("-fuse-line-directives");
4824
4825 // -fms-compatibility=0 is default.
4826 if (Args.hasFlag(options::OPT_fms_compatibility,
4827 options::OPT_fno_ms_compatibility,
4828 (IsWindowsMSVC &&
4829 Args.hasFlag(options::OPT_fms_extensions,
4830 options::OPT_fno_ms_extensions, true))))
4831 CmdArgs.push_back("-fms-compatibility");
4832
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004833 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004834 if (!MSVT.empty())
4835 CmdArgs.push_back(
4836 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4837
4838 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4839 if (ImplyVCPPCXXVer) {
4840 StringRef LanguageStandard;
4841 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
Richard Smithb1b580e2019-04-14 11:11:37 +00004842 Std = StdArg;
David L. Jonesf561aba2017-03-08 01:02:16 +00004843 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4844 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004845 .Case("c++17", "-std=c++17")
4846 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004847 .Default("");
4848 if (LanguageStandard.empty())
4849 D.Diag(clang::diag::warn_drv_unused_argument)
4850 << StdArg->getAsString(Args);
4851 }
4852
4853 if (LanguageStandard.empty()) {
4854 if (IsMSVC2015Compatible)
4855 LanguageStandard = "-std=c++14";
4856 else
4857 LanguageStandard = "-std=c++11";
4858 }
4859
4860 CmdArgs.push_back(LanguageStandard.data());
4861 }
4862
4863 // -fno-borland-extensions is default.
4864 if (Args.hasFlag(options::OPT_fborland_extensions,
4865 options::OPT_fno_borland_extensions, false))
4866 CmdArgs.push_back("-fborland-extensions");
4867
4868 // -fno-declspec is default, except for PS4.
4869 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004870 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004871 CmdArgs.push_back("-fdeclspec");
4872 else if (Args.hasArg(options::OPT_fno_declspec))
4873 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4874
4875 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4876 // than 19.
4877 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4878 options::OPT_fno_threadsafe_statics,
4879 !IsWindowsMSVC || IsMSVC2015Compatible))
4880 CmdArgs.push_back("-fno-threadsafe-statics");
4881
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004882 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004883 // Many old Windows SDK versions require this to parse.
4884 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4885 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004886 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4887 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4888 CmdArgs.push_back("-fdelayed-template-parsing");
4889
4890 // -fgnu-keywords default varies depending on language; only pass if
4891 // specified.
Nico Weber908b6972019-06-26 17:51:47 +00004892 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
4893 options::OPT_fno_gnu_keywords);
David L. Jonesf561aba2017-03-08 01:02:16 +00004894
4895 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4896 false))
4897 CmdArgs.push_back("-fgnu89-inline");
4898
4899 if (Args.hasArg(options::OPT_fno_inline))
4900 CmdArgs.push_back("-fno-inline");
4901
Nico Weber908b6972019-06-26 17:51:47 +00004902 Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
4903 options::OPT_finline_hint_functions,
4904 options::OPT_fno_inline_functions);
David L. Jonesf561aba2017-03-08 01:02:16 +00004905
Richard Smithb1b580e2019-04-14 11:11:37 +00004906 // FIXME: Find a better way to determine whether the language has modules
4907 // support by default, or just assume that all languages do.
4908 bool HaveModules =
4909 Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
4910 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4911
David L. Jonesf561aba2017-03-08 01:02:16 +00004912 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4913 options::OPT_fno_experimental_new_pass_manager);
4914
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004915 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004916 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4917 Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004918
4919 if (Args.hasFlag(options::OPT_fapplication_extension,
4920 options::OPT_fno_application_extension, false))
4921 CmdArgs.push_back("-fapplication-extension");
4922
4923 // Handle GCC-style exception args.
4924 if (!C.getDriver().IsCLMode())
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004925 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004926
Martell Malonec950c652017-11-29 07:25:12 +00004927 // Handle exception personalities
4928 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4929 options::OPT_fseh_exceptions,
4930 options::OPT_fdwarf_exceptions);
4931 if (A) {
4932 const Option &Opt = A->getOption();
4933 if (Opt.matches(options::OPT_fsjlj_exceptions))
4934 CmdArgs.push_back("-fsjlj-exceptions");
4935 if (Opt.matches(options::OPT_fseh_exceptions))
4936 CmdArgs.push_back("-fseh-exceptions");
4937 if (Opt.matches(options::OPT_fdwarf_exceptions))
4938 CmdArgs.push_back("-fdwarf-exceptions");
4939 } else {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004940 switch (TC.GetExceptionModel(Args)) {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004941 default:
4942 break;
4943 case llvm::ExceptionHandling::DwarfCFI:
4944 CmdArgs.push_back("-fdwarf-exceptions");
4945 break;
4946 case llvm::ExceptionHandling::SjLj:
4947 CmdArgs.push_back("-fsjlj-exceptions");
4948 break;
4949 case llvm::ExceptionHandling::WinEH:
4950 CmdArgs.push_back("-fseh-exceptions");
4951 break;
Martell Malonec950c652017-11-29 07:25:12 +00004952 }
4953 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004954
4955 // C++ "sane" operator new.
4956 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4957 options::OPT_fno_assume_sane_operator_new))
4958 CmdArgs.push_back("-fno-assume-sane-operator-new");
4959
4960 // -frelaxed-template-template-args is off by default, as it is a severe
4961 // breaking change until a corresponding change to template partial ordering
4962 // is provided.
4963 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4964 options::OPT_fno_relaxed_template_template_args, false))
4965 CmdArgs.push_back("-frelaxed-template-template-args");
4966
4967 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4968 // most platforms.
4969 if (Args.hasFlag(options::OPT_fsized_deallocation,
4970 options::OPT_fno_sized_deallocation, false))
4971 CmdArgs.push_back("-fsized-deallocation");
4972
4973 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4974 // by default.
4975 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4976 options::OPT_fno_aligned_allocation,
4977 options::OPT_faligned_new_EQ)) {
4978 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4979 CmdArgs.push_back("-fno-aligned-allocation");
4980 else
4981 CmdArgs.push_back("-faligned-allocation");
4982 }
4983
4984 // The default new alignment can be specified using a dedicated option or via
4985 // a GCC-compatible option that also turns on aligned allocation.
4986 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4987 options::OPT_faligned_new_EQ))
4988 CmdArgs.push_back(
4989 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4990
4991 // -fconstant-cfstrings is default, and may be subject to argument translation
4992 // on Darwin.
4993 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4994 options::OPT_fno_constant_cfstrings) ||
4995 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4996 options::OPT_mno_constant_cfstrings))
4997 CmdArgs.push_back("-fno-constant-cfstrings");
4998
David L. Jonesf561aba2017-03-08 01:02:16 +00004999 // -fno-pascal-strings is default, only pass non-default.
5000 if (Args.hasFlag(options::OPT_fpascal_strings,
5001 options::OPT_fno_pascal_strings, false))
5002 CmdArgs.push_back("-fpascal-strings");
5003
5004 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5005 // -fno-pack-struct doesn't apply to -fpack-struct=.
5006 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5007 std::string PackStructStr = "-fpack-struct=";
5008 PackStructStr += A->getValue();
5009 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5010 } else if (Args.hasFlag(options::OPT_fpack_struct,
5011 options::OPT_fno_pack_struct, false)) {
5012 CmdArgs.push_back("-fpack-struct=1");
5013 }
5014
5015 // Handle -fmax-type-align=N and -fno-type-align
5016 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5017 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5018 if (!SkipMaxTypeAlign) {
5019 std::string MaxTypeAlignStr = "-fmax-type-align=";
5020 MaxTypeAlignStr += A->getValue();
5021 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5022 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00005023 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005024 if (!SkipMaxTypeAlign) {
5025 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5026 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5027 }
5028 }
5029
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00005030 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
5031 CmdArgs.push_back("-Qn");
5032
David L. Jonesf561aba2017-03-08 01:02:16 +00005033 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00005034 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00005035 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5036 !NoCommonDefault))
5037 CmdArgs.push_back("-fno-common");
5038
5039 // -fsigned-bitfields is default, and clang doesn't yet support
5040 // -funsigned-bitfields.
5041 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5042 options::OPT_funsigned_bitfields))
5043 D.Diag(diag::warn_drv_clang_unsupported)
5044 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5045
5046 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5047 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5048 D.Diag(diag::err_drv_clang_unsupported)
5049 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5050
5051 // -finput_charset=UTF-8 is default. Reject others
5052 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5053 StringRef value = inputCharset->getValue();
5054 if (!value.equals_lower("utf-8"))
5055 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5056 << value;
5057 }
5058
5059 // -fexec_charset=UTF-8 is default. Reject others
5060 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5061 StringRef value = execCharset->getValue();
5062 if (!value.equals_lower("utf-8"))
5063 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5064 << value;
5065 }
5066
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00005067 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005068
5069 // -fno-asm-blocks is default.
5070 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5071 false))
5072 CmdArgs.push_back("-fasm-blocks");
5073
5074 // -fgnu-inline-asm is default.
5075 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5076 options::OPT_fno_gnu_inline_asm, true))
5077 CmdArgs.push_back("-fno-gnu-inline-asm");
5078
5079 // Enable vectorization per default according to the optimization level
5080 // selected. For optimization levels that want vectorization we use the alias
5081 // option to simplify the hasFlag logic.
5082 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5083 OptSpecifier VectorizeAliasOption =
5084 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5085 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5086 options::OPT_fno_vectorize, EnableVec))
5087 CmdArgs.push_back("-vectorize-loops");
5088
5089 // -fslp-vectorize is enabled based on the optimization level selected.
5090 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5091 OptSpecifier SLPVectAliasOption =
5092 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5093 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5094 options::OPT_fno_slp_vectorize, EnableSLPVec))
5095 CmdArgs.push_back("-vectorize-slp");
5096
Craig Topper9a724aa2017-12-11 21:09:19 +00005097 ParseMPreferVectorWidth(D, Args, CmdArgs);
5098
Nico Weber908b6972019-06-26 17:51:47 +00005099 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
5100 Args.AddLastArg(CmdArgs,
5101 options::OPT_fsanitize_undefined_strip_path_components_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00005102
5103 // -fdollars-in-identifiers default varies depending on platform and
5104 // language; only pass if specified.
5105 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5106 options::OPT_fno_dollars_in_identifiers)) {
5107 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5108 CmdArgs.push_back("-fdollars-in-identifiers");
5109 else
5110 CmdArgs.push_back("-fno-dollars-in-identifiers");
5111 }
5112
5113 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5114 // practical purposes.
5115 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5116 options::OPT_fno_unit_at_a_time)) {
5117 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5118 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5119 }
5120
5121 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5122 options::OPT_fno_apple_pragma_pack, false))
5123 CmdArgs.push_back("-fapple-pragma-pack");
5124
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005125 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
David L. Jonesf561aba2017-03-08 01:02:16 +00005126 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00005127 options::OPT_foptimization_record_file_EQ,
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005128 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005129 Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5130 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005131 Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00005132 options::OPT_fno_save_optimization_record, false)) {
5133 CmdArgs.push_back("-opt-record-file");
5134
5135 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5136 if (A) {
5137 CmdArgs.push_back(A->getValue());
5138 } else {
5139 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00005140
5141 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5142 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5143 F = FinalOutput->getValue();
5144 }
5145
5146 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005147 // Use the input filename.
5148 F = llvm::sys::path::stem(Input.getBaseInput());
5149
5150 // If we're compiling for an offload architecture (i.e. a CUDA device),
5151 // we need to make the file name for the device compilation different
5152 // from the host compilation.
5153 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5154 !JA.isDeviceOffloading(Action::OFK_Host)) {
5155 llvm::sys::path::replace_extension(F, "");
5156 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5157 Triple.normalize());
5158 F += "-";
5159 F += JA.getOffloadingArch();
5160 }
5161 }
5162
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005163 std::string Extension = "opt.";
5164 if (const Arg *A =
5165 Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
5166 Extension += A->getValue();
5167 else
5168 Extension += "yaml";
5169
5170 llvm::sys::path::replace_extension(F, Extension);
David L. Jonesf561aba2017-03-08 01:02:16 +00005171 CmdArgs.push_back(Args.MakeArgString(F));
5172 }
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005173
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005174 if (const Arg *A =
5175 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5176 CmdArgs.push_back("-opt-record-passes");
5177 CmdArgs.push_back(A->getValue());
5178 }
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005179
5180 if (const Arg *A =
5181 Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
5182 CmdArgs.push_back("-opt-record-format");
5183 CmdArgs.push_back(A->getValue());
5184 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005185 }
5186
Richard Smith86a3ef52017-06-09 21:24:02 +00005187 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5188 options::OPT_fno_rewrite_imports, false);
5189 if (RewriteImports)
5190 CmdArgs.push_back("-frewrite-imports");
5191
David L. Jonesf561aba2017-03-08 01:02:16 +00005192 // Enable rewrite includes if the user's asked for it or if we're generating
5193 // diagnostics.
5194 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5195 // nice to enable this when doing a crashdump for modules as well.
5196 if (Args.hasFlag(options::OPT_frewrite_includes,
5197 options::OPT_fno_rewrite_includes, false) ||
David Blaikiea99b8e42018-11-15 03:04:19 +00005198 (C.isForDiagnostics() && !HaveModules))
David L. Jonesf561aba2017-03-08 01:02:16 +00005199 CmdArgs.push_back("-frewrite-includes");
5200
5201 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5202 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5203 options::OPT_traditional_cpp)) {
5204 if (isa<PreprocessJobAction>(JA))
5205 CmdArgs.push_back("-traditional-cpp");
5206 else
5207 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5208 }
5209
5210 Args.AddLastArg(CmdArgs, options::OPT_dM);
5211 Args.AddLastArg(CmdArgs, options::OPT_dD);
5212
5213 // Handle serialized diagnostics.
5214 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5215 CmdArgs.push_back("-serialize-diagnostic-file");
5216 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5217 }
5218
5219 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5220 CmdArgs.push_back("-fretain-comments-from-system-headers");
5221
5222 // Forward -fcomment-block-commands to -cc1.
5223 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5224 // Forward -fparse-all-comments to -cc1.
5225 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5226
5227 // Turn -fplugin=name.so into -load name.so
5228 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5229 CmdArgs.push_back("-load");
5230 CmdArgs.push_back(A->getValue());
5231 A->claim();
5232 }
5233
Philip Pfaffee3f105c2019-02-02 23:19:32 +00005234 // Forward -fpass-plugin=name.so to -cc1.
5235 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5236 CmdArgs.push_back(
5237 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5238 A->claim();
5239 }
5240
David L. Jonesf561aba2017-03-08 01:02:16 +00005241 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00005242 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5243 if (!StatsFile.empty())
5244 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00005245
5246 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5247 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00005248 // -finclude-default-header flag is for preprocessor,
5249 // do not pass it to other cc1 commands when save-temps is enabled
5250 if (C.getDriver().isSaveTempsEnabled() &&
5251 !isa<PreprocessJobAction>(JA)) {
5252 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5253 Arg->claim();
5254 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5255 CmdArgs.push_back(Arg->getValue());
5256 }
5257 }
5258 else {
5259 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5260 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005261 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5262 A->claim();
5263
5264 // We translate this by hand to the -cc1 argument, since nightly test uses
5265 // it and developers have been trained to spell it with -mllvm. Both
5266 // spellings are now deprecated and should be removed.
5267 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5268 CmdArgs.push_back("-disable-llvm-optzns");
5269 } else {
5270 A->render(Args, CmdArgs);
5271 }
5272 }
5273
5274 // With -save-temps, we want to save the unoptimized bitcode output from the
5275 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5276 // by the frontend.
5277 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5278 // has slightly different breakdown between stages.
5279 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5280 // pristine IR generated by the frontend. Ideally, a new compile action should
5281 // be added so both IR can be captured.
5282 if (C.getDriver().isSaveTempsEnabled() &&
5283 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5284 isa<CompileJobAction>(JA))
5285 CmdArgs.push_back("-disable-llvm-passes");
5286
David L. Jonesf561aba2017-03-08 01:02:16 +00005287 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5288
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00005289 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00005290
Scott Linderde6beb02018-12-14 15:38:15 +00005291 // Optionally embed the -cc1 level arguments into the debug info or a
5292 // section, for build analysis.
Eric Christopherca325172017-03-29 23:34:20 +00005293 // Also record command line arguments into the debug info if
5294 // -grecord-gcc-switches options is set on.
5295 // By default, -gno-record-gcc-switches is set on and no recording.
Scott Linderde6beb02018-12-14 15:38:15 +00005296 auto GRecordSwitches =
5297 Args.hasFlag(options::OPT_grecord_command_line,
5298 options::OPT_gno_record_command_line, false);
5299 auto FRecordSwitches =
5300 Args.hasFlag(options::OPT_frecord_command_line,
5301 options::OPT_fno_record_command_line, false);
5302 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5303 D.Diag(diag::err_drv_unsupported_opt_for_target)
5304 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5305 << TripleStr;
5306 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005307 ArgStringList OriginalArgs;
5308 for (const auto &Arg : Args)
5309 Arg->render(Args, OriginalArgs);
5310
5311 SmallString<256> Flags;
5312 Flags += Exec;
5313 for (const char *OriginalArg : OriginalArgs) {
5314 SmallString<128> EscapedArg;
5315 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5316 Flags += " ";
5317 Flags += EscapedArg;
5318 }
Scott Linderde6beb02018-12-14 15:38:15 +00005319 auto FlagsArgString = Args.MakeArgString(Flags);
5320 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5321 CmdArgs.push_back("-dwarf-debug-flags");
5322 CmdArgs.push_back(FlagsArgString);
5323 }
5324 if (FRecordSwitches) {
5325 CmdArgs.push_back("-record-command-line");
5326 CmdArgs.push_back(FlagsArgString);
5327 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005328 }
5329
Yaxun Liu97670892018-10-02 17:48:54 +00005330 // Host-side cuda compilation receives all device-side outputs in a single
5331 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5332 if ((IsCuda || IsHIP) && CudaDeviceInput) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00005333 CmdArgs.push_back("-fcuda-include-gpubinary");
Richard Smithcd35eff2018-09-15 01:21:16 +00005334 CmdArgs.push_back(CudaDeviceInput->getFilename());
Yaxun Liu97670892018-10-02 17:48:54 +00005335 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5336 CmdArgs.push_back("-fgpu-rdc");
5337 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005338
Yaxun Liu97670892018-10-02 17:48:54 +00005339 if (IsCuda) {
Artem Belevich679dafe2018-05-09 23:10:09 +00005340 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5341 options::OPT_fno_cuda_short_ptr, false))
5342 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00005343 }
5344
David L. Jonesf561aba2017-03-08 01:02:16 +00005345 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5346 // to specify the result of the compile phase on the host, so the meaningful
5347 // device declarations can be identified. Also, -fopenmp-is-device is passed
5348 // along to tell the frontend that it is generating code for a device, so that
5349 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005350 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005351 CmdArgs.push_back("-fopenmp-is-device");
Richard Smithcd35eff2018-09-15 01:21:16 +00005352 if (OpenMPDeviceInput) {
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005353 CmdArgs.push_back("-fopenmp-host-ir-file-path");
Richard Smithcd35eff2018-09-15 01:21:16 +00005354 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005355 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005356 }
5357
5358 // For all the host OpenMP offloading compile jobs we need to pass the targets
5359 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00005360 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005361 SmallString<128> TargetInfo("-fopenmp-targets=");
5362
5363 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5364 assert(Tgts && Tgts->getNumValues() &&
5365 "OpenMP offloading has to have targets specified.");
5366 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5367 if (i)
5368 TargetInfo += ',';
5369 // We need to get the string from the triple because it may be not exactly
5370 // the same as the one we get directly from the arguments.
5371 llvm::Triple T(Tgts->getValue(i));
5372 TargetInfo += T.getTriple();
5373 }
5374 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5375 }
5376
5377 bool WholeProgramVTables =
5378 Args.hasFlag(options::OPT_fwhole_program_vtables,
5379 options::OPT_fno_whole_program_vtables, false);
5380 if (WholeProgramVTables) {
5381 if (!D.isUsingLTO())
5382 D.Diag(diag::err_drv_argument_only_allowed_with)
5383 << "-fwhole-program-vtables"
5384 << "-flto";
5385 CmdArgs.push_back("-fwhole-program-vtables");
5386 }
5387
Teresa Johnson84cecfc2019-01-11 18:32:07 +00005388 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5389 bool SplitLTOUnit =
5390 Args.hasFlag(options::OPT_fsplit_lto_unit,
5391 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5392 if (RequiresSplitLTOUnit && !SplitLTOUnit)
5393 D.Diag(diag::err_drv_argument_not_allowed_with)
5394 << "-fno-split-lto-unit"
5395 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5396 if (SplitLTOUnit)
5397 CmdArgs.push_back("-fsplit-lto-unit");
5398
Amara Emerson4ee9f822018-01-26 00:27:22 +00005399 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5400 options::OPT_fno_experimental_isel)) {
5401 CmdArgs.push_back("-mllvm");
5402 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5403 CmdArgs.push_back("-global-isel=1");
5404
5405 // GISel is on by default on AArch64 -O0, so don't bother adding
5406 // the fallback remarks for it. Other combinations will add a warning of
5407 // some kind.
5408 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5409 bool IsOptLevelSupported = false;
5410
5411 Arg *A = Args.getLastArg(options::OPT_O_Group);
5412 if (Triple.getArch() == llvm::Triple::aarch64) {
5413 if (!A || A->getOption().matches(options::OPT_O0))
5414 IsOptLevelSupported = true;
5415 }
5416 if (!IsArchSupported || !IsOptLevelSupported) {
5417 CmdArgs.push_back("-mllvm");
5418 CmdArgs.push_back("-global-isel-abort=2");
5419
5420 if (!IsArchSupported)
5421 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5422 else
5423 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5424 }
5425 } else {
5426 CmdArgs.push_back("-global-isel=0");
5427 }
5428 }
5429
Manman Ren394d4cc2019-03-04 20:30:30 +00005430 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5431 CmdArgs.push_back("-forder-file-instrumentation");
5432 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5433 // on, we need to pass these flags as linker flags and that will be handled
5434 // outside of the compiler.
5435 if (!D.isUsingLTO()) {
5436 CmdArgs.push_back("-mllvm");
5437 CmdArgs.push_back("-enable-order-file-instrumentation");
5438 }
5439 }
5440
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00005441 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5442 options::OPT_fno_force_enable_int128)) {
5443 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5444 CmdArgs.push_back("-fforce-enable-int128");
5445 }
5446
Peter Collingbourne54d13b42018-05-30 03:40:04 +00005447 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5448 options::OPT_fno_complete_member_pointers, false))
5449 CmdArgs.push_back("-fcomplete-member-pointers");
5450
Erik Pilkington5a559e62018-08-21 17:24:06 +00005451 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5452 options::OPT_fno_cxx_static_destructors, true))
5453 CmdArgs.push_back("-fno-c++-static-destructors");
5454
Jessica Paquette36a25672018-06-29 18:06:10 +00005455 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5456 options::OPT_mno_outline)) {
5457 if (A->getOption().matches(options::OPT_moutline)) {
5458 // We only support -moutline in AArch64 right now. If we're not compiling
5459 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5460 // proper mllvm flags.
5461 if (Triple.getArch() != llvm::Triple::aarch64) {
5462 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5463 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00005464 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00005465 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005466 }
Jessica Paquette36a25672018-06-29 18:06:10 +00005467 } else {
5468 // Disable all outlining behaviour.
5469 CmdArgs.push_back("-mllvm");
5470 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005471 }
5472 }
5473
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005474 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00005475 (TC.getTriple().isOSBinFormatELF() ||
5476 TC.getTriple().isOSBinFormatCOFF()) &&
Douglas Yung25f04772018-12-19 22:45:26 +00005477 !TC.getTriple().isPS4() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005478 !TC.getTriple().isOSNetBSD() &&
Michal Gornydae01c32018-12-23 15:07:26 +00005479 !Distro(D.getVFS()).IsGentoo() &&
Dan Albertdd142342019-01-08 22:33:59 +00005480 !TC.getTriple().isAndroid() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005481 TC.useIntegratedAs()))
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005482 CmdArgs.push_back("-faddrsig");
5483
Peter Collingbournee08e68d2019-06-07 19:10:08 +00005484 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
5485 std::string Str = A->getAsString(Args);
5486 if (!TC.getTriple().isOSBinFormatELF())
5487 D.Diag(diag::err_drv_unsupported_opt_for_target)
5488 << Str << TC.getTripleString();
5489 CmdArgs.push_back(Args.MakeArgString(Str));
5490 }
5491
Reid Kleckner549ed542019-05-23 18:35:43 +00005492 // Add the "-o out -x type src.c" flags last. This is done primarily to make
5493 // the -cc1 command easier to edit when reproducing compiler crashes.
5494 if (Output.getType() == types::TY_Dependencies) {
5495 // Handled with other dependency code.
5496 } else if (Output.isFilename()) {
5497 CmdArgs.push_back("-o");
5498 CmdArgs.push_back(Output.getFilename());
5499 } else {
5500 assert(Output.isNothing() && "Invalid output.");
5501 }
5502
5503 addDashXForInput(Args, Input, CmdArgs);
5504
5505 ArrayRef<InputInfo> FrontendInputs = Input;
5506 if (IsHeaderModulePrecompile)
5507 FrontendInputs = ModuleHeaderInputs;
5508 else if (Input.isNothing())
5509 FrontendInputs = {};
5510
5511 for (const InputInfo &Input : FrontendInputs) {
5512 if (Input.isFilename())
5513 CmdArgs.push_back(Input.getFilename());
5514 else
5515 Input.getInputArg().renderAsInput(Args, CmdArgs);
5516 }
5517
David L. Jonesf561aba2017-03-08 01:02:16 +00005518 // Finally add the compile command to the compilation.
5519 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5520 Output.getType() == types::TY_Object &&
5521 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5522 auto CLCommand =
5523 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5524 C.addCommand(llvm::make_unique<FallbackCommand>(
5525 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5526 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5527 isa<PrecompileJobAction>(JA)) {
5528 // In /fallback builds, run the main compilation even if the pch generation
5529 // fails, so that the main compilation's fallback to cl.exe runs.
5530 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5531 CmdArgs, Inputs));
5532 } else {
5533 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5534 }
5535
Hans Wennborg2fe01042018-10-13 19:13:14 +00005536 // Make the compile command echo its inputs for /showFilenames.
5537 if (Output.getType() == types::TY_Object &&
5538 Args.hasFlag(options::OPT__SLASH_showFilenames,
5539 options::OPT__SLASH_showFilenames_, false)) {
5540 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5541 }
5542
David L. Jonesf561aba2017-03-08 01:02:16 +00005543 if (Arg *A = Args.getLastArg(options::OPT_pg))
Yuanfang Chenff22ec32019-07-20 22:50:50 +00005544 if (FPKeepKind == CodeGenOptions::FramePointerKind::None)
David L. Jonesf561aba2017-03-08 01:02:16 +00005545 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5546 << A->getAsString(Args);
5547
5548 // Claim some arguments which clang supports automatically.
5549
5550 // -fpch-preprocess is used with gcc to add a special marker in the output to
Erich Keane0a6b5b62018-12-04 14:34:09 +00005551 // include the PCH file.
David L. Jonesf561aba2017-03-08 01:02:16 +00005552 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5553
5554 // Claim some arguments which clang doesn't support, but we don't
5555 // care to warn the user about.
5556 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5557 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5558
5559 // Disable warnings for clang -E -emit-llvm foo.c
5560 Args.ClaimAllArgs(options::OPT_emit_llvm);
5561}
5562
5563Clang::Clang(const ToolChain &TC)
5564 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5565 // as it is for other tools. Some operations on a Tool actually test
5566 // whether that tool is Clang based on the Tool's Name as a string.
5567 : Tool("clang", "clang frontend", TC, RF_Full) {}
5568
5569Clang::~Clang() {}
5570
5571/// Add options related to the Objective-C runtime/ABI.
5572///
5573/// Returns true if the runtime is non-fragile.
5574ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5575 ArgStringList &cmdArgs,
5576 RewriteKind rewriteKind) const {
5577 // Look for the controlling runtime option.
5578 Arg *runtimeArg =
5579 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5580 options::OPT_fobjc_runtime_EQ);
5581
5582 // Just forward -fobjc-runtime= to the frontend. This supercedes
5583 // options about fragility.
5584 if (runtimeArg &&
5585 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5586 ObjCRuntime runtime;
5587 StringRef value = runtimeArg->getValue();
5588 if (runtime.tryParse(value)) {
5589 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5590 << value;
5591 }
David Chisnall404bbcb2018-05-22 10:13:06 +00005592 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5593 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnallef16ea72018-09-04 10:07:27 +00005594 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5595 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00005596 getToolChain().getDriver().Diag(
5597 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5598 << runtime.getVersion().getMajor();
5599 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005600
5601 runtimeArg->render(args, cmdArgs);
5602 return runtime;
5603 }
5604
5605 // Otherwise, we'll need the ABI "version". Version numbers are
5606 // slightly confusing for historical reasons:
5607 // 1 - Traditional "fragile" ABI
5608 // 2 - Non-fragile ABI, version 1
5609 // 3 - Non-fragile ABI, version 2
5610 unsigned objcABIVersion = 1;
5611 // If -fobjc-abi-version= is present, use that to set the version.
5612 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5613 StringRef value = abiArg->getValue();
5614 if (value == "1")
5615 objcABIVersion = 1;
5616 else if (value == "2")
5617 objcABIVersion = 2;
5618 else if (value == "3")
5619 objcABIVersion = 3;
5620 else
5621 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5622 } else {
5623 // Otherwise, determine if we are using the non-fragile ABI.
5624 bool nonFragileABIIsDefault =
5625 (rewriteKind == RK_NonFragile ||
5626 (rewriteKind == RK_None &&
5627 getToolChain().IsObjCNonFragileABIDefault()));
5628 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5629 options::OPT_fno_objc_nonfragile_abi,
5630 nonFragileABIIsDefault)) {
5631// Determine the non-fragile ABI version to use.
5632#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5633 unsigned nonFragileABIVersion = 1;
5634#else
5635 unsigned nonFragileABIVersion = 2;
5636#endif
5637
5638 if (Arg *abiArg =
5639 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5640 StringRef value = abiArg->getValue();
5641 if (value == "1")
5642 nonFragileABIVersion = 1;
5643 else if (value == "2")
5644 nonFragileABIVersion = 2;
5645 else
5646 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5647 << value;
5648 }
5649
5650 objcABIVersion = 1 + nonFragileABIVersion;
5651 } else {
5652 objcABIVersion = 1;
5653 }
5654 }
5655
5656 // We don't actually care about the ABI version other than whether
5657 // it's non-fragile.
5658 bool isNonFragile = objcABIVersion != 1;
5659
5660 // If we have no runtime argument, ask the toolchain for its default runtime.
5661 // However, the rewriter only really supports the Mac runtime, so assume that.
5662 ObjCRuntime runtime;
5663 if (!runtimeArg) {
5664 switch (rewriteKind) {
5665 case RK_None:
5666 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5667 break;
5668 case RK_Fragile:
5669 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5670 break;
5671 case RK_NonFragile:
5672 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5673 break;
5674 }
5675
5676 // -fnext-runtime
5677 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5678 // On Darwin, make this use the default behavior for the toolchain.
5679 if (getToolChain().getTriple().isOSDarwin()) {
5680 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5681
5682 // Otherwise, build for a generic macosx port.
5683 } else {
5684 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5685 }
5686
5687 // -fgnu-runtime
5688 } else {
5689 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5690 // Legacy behaviour is to target the gnustep runtime if we are in
5691 // non-fragile mode or the GCC runtime in fragile mode.
5692 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005693 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005694 else
5695 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5696 }
5697
5698 cmdArgs.push_back(
5699 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5700 return runtime;
5701}
5702
5703static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5704 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5705 I += HaveDash;
5706 return !HaveDash;
5707}
5708
5709namespace {
5710struct EHFlags {
5711 bool Synch = false;
5712 bool Asynch = false;
5713 bool NoUnwindC = false;
5714};
5715} // end anonymous namespace
5716
5717/// /EH controls whether to run destructor cleanups when exceptions are
5718/// thrown. There are three modifiers:
5719/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5720/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5721/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5722/// - c: Assume that extern "C" functions are implicitly nounwind.
5723/// The default is /EHs-c-, meaning cleanups are disabled.
5724static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5725 EHFlags EH;
5726
5727 std::vector<std::string> EHArgs =
5728 Args.getAllArgValues(options::OPT__SLASH_EH);
5729 for (auto EHVal : EHArgs) {
5730 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5731 switch (EHVal[I]) {
5732 case 'a':
5733 EH.Asynch = maybeConsumeDash(EHVal, I);
5734 if (EH.Asynch)
5735 EH.Synch = false;
5736 continue;
5737 case 'c':
5738 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5739 continue;
5740 case 's':
5741 EH.Synch = maybeConsumeDash(EHVal, I);
5742 if (EH.Synch)
5743 EH.Asynch = false;
5744 continue;
5745 default:
5746 break;
5747 }
5748 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5749 break;
5750 }
5751 }
5752 // The /GX, /GX- flags are only processed if there are not /EH flags.
5753 // The default is that /GX is not specified.
5754 if (EHArgs.empty() &&
5755 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005756 /*Default=*/false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005757 EH.Synch = true;
5758 EH.NoUnwindC = true;
5759 }
5760
5761 return EH;
5762}
5763
5764void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5765 ArgStringList &CmdArgs,
5766 codegenoptions::DebugInfoKind *DebugInfoKind,
5767 bool *EmitCodeView) const {
5768 unsigned RTOptionID = options::OPT__SLASH_MT;
5769
5770 if (Args.hasArg(options::OPT__SLASH_LDd))
5771 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5772 // but defining _DEBUG is sticky.
5773 RTOptionID = options::OPT__SLASH_MTd;
5774
5775 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5776 RTOptionID = A->getOption().getID();
5777
5778 StringRef FlagForCRT;
5779 switch (RTOptionID) {
5780 case options::OPT__SLASH_MD:
5781 if (Args.hasArg(options::OPT__SLASH_LDd))
5782 CmdArgs.push_back("-D_DEBUG");
5783 CmdArgs.push_back("-D_MT");
5784 CmdArgs.push_back("-D_DLL");
5785 FlagForCRT = "--dependent-lib=msvcrt";
5786 break;
5787 case options::OPT__SLASH_MDd:
5788 CmdArgs.push_back("-D_DEBUG");
5789 CmdArgs.push_back("-D_MT");
5790 CmdArgs.push_back("-D_DLL");
5791 FlagForCRT = "--dependent-lib=msvcrtd";
5792 break;
5793 case options::OPT__SLASH_MT:
5794 if (Args.hasArg(options::OPT__SLASH_LDd))
5795 CmdArgs.push_back("-D_DEBUG");
5796 CmdArgs.push_back("-D_MT");
5797 CmdArgs.push_back("-flto-visibility-public-std");
5798 FlagForCRT = "--dependent-lib=libcmt";
5799 break;
5800 case options::OPT__SLASH_MTd:
5801 CmdArgs.push_back("-D_DEBUG");
5802 CmdArgs.push_back("-D_MT");
5803 CmdArgs.push_back("-flto-visibility-public-std");
5804 FlagForCRT = "--dependent-lib=libcmtd";
5805 break;
5806 default:
5807 llvm_unreachable("Unexpected option ID.");
5808 }
5809
5810 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5811 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5812 } else {
5813 CmdArgs.push_back(FlagForCRT.data());
5814
5815 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5816 // users want. The /Za flag to cl.exe turns this off, but it's not
5817 // implemented in clang.
5818 CmdArgs.push_back("--dependent-lib=oldnames");
5819 }
5820
Nico Weber908b6972019-06-26 17:51:47 +00005821 Args.AddLastArg(CmdArgs, options::OPT_show_includes);
David L. Jonesf561aba2017-03-08 01:02:16 +00005822
5823 // This controls whether or not we emit RTTI data for polymorphic types.
5824 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005825 /*Default=*/false))
David L. Jonesf561aba2017-03-08 01:02:16 +00005826 CmdArgs.push_back("-fno-rtti-data");
5827
5828 // This controls whether or not we emit stack-protector instrumentation.
5829 // In MSVC, Buffer Security Check (/GS) is on by default.
5830 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005831 /*Default=*/true)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005832 CmdArgs.push_back("-stack-protector");
5833 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5834 }
5835
5836 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5837 if (Arg *DebugInfoArg =
5838 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5839 options::OPT_gline_tables_only)) {
5840 *EmitCodeView = true;
5841 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5842 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5843 else
5844 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +00005845 } else {
5846 *EmitCodeView = false;
5847 }
5848
5849 const Driver &D = getToolChain().getDriver();
5850 EHFlags EH = parseClangCLEHFlags(D, Args);
5851 if (EH.Synch || EH.Asynch) {
5852 if (types::isCXX(InputType))
5853 CmdArgs.push_back("-fcxx-exceptions");
5854 CmdArgs.push_back("-fexceptions");
5855 }
5856 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5857 CmdArgs.push_back("-fexternc-nounwind");
5858
5859 // /EP should expand to -E -P.
5860 if (Args.hasArg(options::OPT__SLASH_EP)) {
5861 CmdArgs.push_back("-E");
5862 CmdArgs.push_back("-P");
5863 }
5864
5865 unsigned VolatileOptionID;
5866 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5867 getToolChain().getArch() == llvm::Triple::x86)
5868 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5869 else
5870 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5871
5872 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5873 VolatileOptionID = A->getOption().getID();
5874
5875 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5876 CmdArgs.push_back("-fms-volatile");
5877
Takuto Ikuta302c6432018-11-03 06:45:00 +00005878 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5879 options::OPT__SLASH_Zc_dllexportInlines,
Takuto Ikuta245d9472018-11-13 04:14:09 +00005880 false)) {
5881 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5882 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5883 } else {
Takuto Ikuta302c6432018-11-03 06:45:00 +00005884 CmdArgs.push_back("-fno-dllexport-inlines");
Takuto Ikuta245d9472018-11-13 04:14:09 +00005885 }
5886 }
Takuto Ikuta302c6432018-11-03 06:45:00 +00005887
David L. Jonesf561aba2017-03-08 01:02:16 +00005888 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5889 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5890 if (MostGeneralArg && BestCaseArg)
5891 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5892 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5893
5894 if (MostGeneralArg) {
5895 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5896 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5897 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5898
5899 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5900 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5901 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5902 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5903 << FirstConflict->getAsString(Args)
5904 << SecondConflict->getAsString(Args);
5905
5906 if (SingleArg)
5907 CmdArgs.push_back("-fms-memptr-rep=single");
5908 else if (MultipleArg)
5909 CmdArgs.push_back("-fms-memptr-rep=multiple");
5910 else
5911 CmdArgs.push_back("-fms-memptr-rep=virtual");
5912 }
5913
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005914 // Parse the default calling convention options.
5915 if (Arg *CCArg =
5916 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005917 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5918 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005919 unsigned DCCOptId = CCArg->getOption().getID();
5920 const char *DCCFlag = nullptr;
5921 bool ArchSupported = true;
5922 llvm::Triple::ArchType Arch = getToolChain().getArch();
5923 switch (DCCOptId) {
5924 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005925 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005926 break;
5927 case options::OPT__SLASH_Gr:
5928 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005929 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005930 break;
5931 case options::OPT__SLASH_Gz:
5932 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005933 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005934 break;
5935 case options::OPT__SLASH_Gv:
5936 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005937 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005938 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005939 case options::OPT__SLASH_Gregcall:
5940 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5941 DCCFlag = "-fdefault-calling-conv=regcall";
5942 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005943 }
5944
5945 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5946 if (ArchSupported && DCCFlag)
5947 CmdArgs.push_back(DCCFlag);
5948 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005949
Nico Weber908b6972019-06-26 17:51:47 +00005950 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00005951
5952 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5953 CmdArgs.push_back("-fdiagnostics-format");
5954 if (Args.hasArg(options::OPT__SLASH_fallback))
5955 CmdArgs.push_back("msvc-fallback");
5956 else
5957 CmdArgs.push_back("msvc");
5958 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005959
Hans Wennborga912e3e2018-08-10 09:49:21 +00005960 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5961 SmallVector<StringRef, 1> SplitArgs;
5962 StringRef(A->getValue()).split(SplitArgs, ",");
5963 bool Instrument = false;
5964 bool NoChecks = false;
5965 for (StringRef Arg : SplitArgs) {
5966 if (Arg.equals_lower("cf"))
5967 Instrument = true;
5968 else if (Arg.equals_lower("cf-"))
5969 Instrument = false;
5970 else if (Arg.equals_lower("nochecks"))
5971 NoChecks = true;
5972 else if (Arg.equals_lower("nochecks-"))
5973 NoChecks = false;
5974 else
5975 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5976 }
5977 // Currently there's no support emitting CFG instrumentation; the flag only
5978 // emits the table of address-taken functions.
5979 if (Instrument || NoChecks)
5980 CmdArgs.push_back("-cfguard");
5981 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005982}
5983
5984visualstudio::Compiler *Clang::getCLFallback() const {
5985 if (!CLFallback)
5986 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5987 return CLFallback.get();
5988}
5989
5990
5991const char *Clang::getBaseInputName(const ArgList &Args,
5992 const InputInfo &Input) {
5993 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5994}
5995
5996const char *Clang::getBaseInputStem(const ArgList &Args,
5997 const InputInfoList &Inputs) {
5998 const char *Str = getBaseInputName(Args, Inputs[0]);
5999
6000 if (const char *End = strrchr(Str, '.'))
6001 return Args.MakeArgString(std::string(Str, End));
6002
6003 return Str;
6004}
6005
6006const char *Clang::getDependencyFileName(const ArgList &Args,
6007 const InputInfoList &Inputs) {
6008 // FIXME: Think about this more.
6009 std::string Res;
6010
6011 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6012 std::string Str(OutputOpt->getValue());
6013 Res = Str.substr(0, Str.rfind('.'));
6014 } else {
6015 Res = getBaseInputStem(Args, Inputs);
6016 }
6017 return Args.MakeArgString(Res + ".d");
6018}
6019
6020// Begin ClangAs
6021
6022void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6023 ArgStringList &CmdArgs) const {
6024 StringRef CPUName;
6025 StringRef ABIName;
6026 const llvm::Triple &Triple = getToolChain().getTriple();
6027 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6028
6029 CmdArgs.push_back("-target-abi");
6030 CmdArgs.push_back(ABIName.data());
6031}
6032
6033void ClangAs::AddX86TargetArgs(const ArgList &Args,
6034 ArgStringList &CmdArgs) const {
6035 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
6036 StringRef Value = A->getValue();
6037 if (Value == "intel" || Value == "att") {
6038 CmdArgs.push_back("-mllvm");
6039 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
6040 } else {
6041 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
6042 << A->getOption().getName() << Value;
6043 }
6044 }
6045}
6046
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006047void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
6048 ArgStringList &CmdArgs) const {
6049 const llvm::Triple &Triple = getToolChain().getTriple();
6050 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
6051
6052 CmdArgs.push_back("-target-abi");
6053 CmdArgs.push_back(ABIName.data());
6054}
6055
David L. Jonesf561aba2017-03-08 01:02:16 +00006056void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6057 const InputInfo &Output, const InputInfoList &Inputs,
6058 const ArgList &Args,
6059 const char *LinkingOutput) const {
6060 ArgStringList CmdArgs;
6061
6062 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6063 const InputInfo &Input = Inputs[0];
6064
Martin Storsjob547ef22018-10-26 08:33:29 +00006065 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00006066 const std::string &TripleStr = Triple.getTriple();
Martin Storsjob547ef22018-10-26 08:33:29 +00006067 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00006068
6069 // Don't warn about "clang -w -c foo.s"
6070 Args.ClaimAllArgs(options::OPT_w);
6071 // and "clang -emit-llvm -c foo.s"
6072 Args.ClaimAllArgs(options::OPT_emit_llvm);
6073
6074 claimNoWarnArgs(Args);
6075
6076 // Invoke ourselves in -cc1as mode.
6077 //
6078 // FIXME: Implement custom jobs for internal actions.
6079 CmdArgs.push_back("-cc1as");
6080
6081 // Add the "effective" target triple.
6082 CmdArgs.push_back("-triple");
6083 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6084
6085 // Set the output mode, we currently only expect to be used as a real
6086 // assembler.
6087 CmdArgs.push_back("-filetype");
6088 CmdArgs.push_back("obj");
6089
6090 // Set the main file name, so that debug info works even with
6091 // -save-temps or preprocessed assembly.
6092 CmdArgs.push_back("-main-file-name");
6093 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6094
6095 // Add the target cpu
6096 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6097 if (!CPU.empty()) {
6098 CmdArgs.push_back("-target-cpu");
6099 CmdArgs.push_back(Args.MakeArgString(CPU));
6100 }
6101
6102 // Add the target features
6103 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6104
6105 // Ignore explicit -force_cpusubtype_ALL option.
6106 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6107
6108 // Pass along any -I options so we get proper .include search paths.
6109 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6110
6111 // Determine the original source input.
6112 const Action *SourceAction = &JA;
6113 while (SourceAction->getKind() != Action::InputClass) {
6114 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6115 SourceAction = SourceAction->getInputs()[0];
6116 }
6117
6118 // Forward -g and handle debug info related flags, assuming we are dealing
6119 // with an actual assembly file.
6120 bool WantDebug = false;
6121 unsigned DwarfVersion = 0;
6122 Args.ClaimAllArgs(options::OPT_g_Group);
6123 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6124 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6125 !A->getOption().matches(options::OPT_ggdb0);
6126 if (WantDebug)
6127 DwarfVersion = DwarfVersionNum(A->getSpelling());
6128 }
6129 if (DwarfVersion == 0)
6130 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6131
6132 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6133
6134 if (SourceAction->getType() == types::TY_Asm ||
6135 SourceAction->getType() == types::TY_PP_Asm) {
6136 // You might think that it would be ok to set DebugInfoKind outside of
6137 // the guard for source type, however there is a test which asserts
6138 // that some assembler invocation receives no -debug-info-kind,
6139 // and it's not clear whether that test is just overly restrictive.
6140 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6141 : codegenoptions::NoDebugInfo);
6142 // Add the -fdebug-compilation-dir flag if needed.
Michael J. Spencer7e48b402019-05-28 22:21:47 +00006143 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
David L. Jonesf561aba2017-03-08 01:02:16 +00006144
Paul Robinson9b292b42018-07-10 15:15:24 +00006145 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6146
David L. Jonesf561aba2017-03-08 01:02:16 +00006147 // Set the AT_producer to the clang version when using the integrated
6148 // assembler on assembly source files.
6149 CmdArgs.push_back("-dwarf-debug-producer");
6150 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6151
6152 // And pass along -I options
6153 Args.AddAllArgs(CmdArgs, options::OPT_I);
6154 }
6155 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6156 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00006157 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00006158
David L. Jonesf561aba2017-03-08 01:02:16 +00006159
6160 // Handle -fPIC et al -- the relocation-model affects the assembler
6161 // for some targets.
6162 llvm::Reloc::Model RelocationModel;
6163 unsigned PICLevel;
6164 bool IsPIE;
6165 std::tie(RelocationModel, PICLevel, IsPIE) =
6166 ParsePICArgs(getToolChain(), Args);
6167
6168 const char *RMName = RelocationModelName(RelocationModel);
6169 if (RMName) {
6170 CmdArgs.push_back("-mrelocation-model");
6171 CmdArgs.push_back(RMName);
6172 }
6173
6174 // Optionally embed the -cc1as level arguments into the debug info, for build
6175 // analysis.
6176 if (getToolChain().UseDwarfDebugFlags()) {
6177 ArgStringList OriginalArgs;
6178 for (const auto &Arg : Args)
6179 Arg->render(Args, OriginalArgs);
6180
6181 SmallString<256> Flags;
6182 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6183 Flags += Exec;
6184 for (const char *OriginalArg : OriginalArgs) {
6185 SmallString<128> EscapedArg;
6186 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6187 Flags += " ";
6188 Flags += EscapedArg;
6189 }
6190 CmdArgs.push_back("-dwarf-debug-flags");
6191 CmdArgs.push_back(Args.MakeArgString(Flags));
6192 }
6193
6194 // FIXME: Add -static support, once we have it.
6195
6196 // Add target specific flags.
6197 switch (getToolChain().getArch()) {
6198 default:
6199 break;
6200
6201 case llvm::Triple::mips:
6202 case llvm::Triple::mipsel:
6203 case llvm::Triple::mips64:
6204 case llvm::Triple::mips64el:
6205 AddMIPSTargetArgs(Args, CmdArgs);
6206 break;
6207
6208 case llvm::Triple::x86:
6209 case llvm::Triple::x86_64:
6210 AddX86TargetArgs(Args, CmdArgs);
6211 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00006212
6213 case llvm::Triple::arm:
6214 case llvm::Triple::armeb:
6215 case llvm::Triple::thumb:
6216 case llvm::Triple::thumbeb:
6217 // This isn't in AddARMTargetArgs because we want to do this for assembly
6218 // only, not C/C++.
6219 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6220 options::OPT_mno_default_build_attributes, true)) {
6221 CmdArgs.push_back("-mllvm");
6222 CmdArgs.push_back("-arm-add-build-attributes");
6223 }
6224 break;
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006225
6226 case llvm::Triple::riscv32:
6227 case llvm::Triple::riscv64:
6228 AddRISCVTargetArgs(Args, CmdArgs);
6229 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00006230 }
6231
6232 // Consume all the warning flags. Usually this would be handled more
6233 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6234 // doesn't handle that so rather than warning about unused flags that are
6235 // actually used, we'll lie by omission instead.
6236 // FIXME: Stop lying and consume only the appropriate driver flags
6237 Args.ClaimAllArgs(options::OPT_W_Group);
6238
6239 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6240 getToolChain().getDriver());
6241
6242 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6243
6244 assert(Output.isFilename() && "Unexpected lipo output.");
6245 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00006246 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006247
Petr Hosekd3265352018-10-15 21:30:32 +00006248 const llvm::Triple &T = getToolChain().getTriple();
George Rimar91829ee2018-11-14 09:22:16 +00006249 Arg *A;
Fangrui Songee957e02019-03-28 08:24:00 +00006250 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6251 T.isOSBinFormatELF()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00006252 CmdArgs.push_back("-split-dwarf-output");
George Rimar36d71da2019-03-27 11:00:03 +00006253 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
Peter Collingbourne91d02842018-05-22 18:52:37 +00006254 }
6255
David L. Jonesf561aba2017-03-08 01:02:16 +00006256 assert(Input.isFilename() && "Invalid input.");
Martin Storsjob547ef22018-10-26 08:33:29 +00006257 CmdArgs.push_back(Input.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006258
6259 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6260 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00006261}
6262
6263// Begin OffloadBundler
6264
6265void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6266 const InputInfo &Output,
6267 const InputInfoList &Inputs,
6268 const llvm::opt::ArgList &TCArgs,
6269 const char *LinkingOutput) const {
6270 // The version with only one output is expected to refer to a bundling job.
6271 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6272
6273 // The bundling command looks like this:
6274 // clang-offload-bundler -type=bc
6275 // -targets=host-triple,openmp-triple1,openmp-triple2
6276 // -outputs=input_file
6277 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6278
6279 ArgStringList CmdArgs;
6280
6281 // Get the type.
6282 CmdArgs.push_back(TCArgs.MakeArgString(
6283 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6284
6285 assert(JA.getInputs().size() == Inputs.size() &&
6286 "Not have inputs for all dependence actions??");
6287
6288 // Get the targets.
6289 SmallString<128> Triples;
6290 Triples += "-targets=";
6291 for (unsigned I = 0; I < Inputs.size(); ++I) {
6292 if (I)
6293 Triples += ',';
6294
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006295 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00006296 Action::OffloadKind CurKind = Action::OFK_Host;
6297 const ToolChain *CurTC = &getToolChain();
6298 const Action *CurDep = JA.getInputs()[I];
6299
6300 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006301 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00006302 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006303 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00006304 CurKind = A->getOffloadingDeviceKind();
6305 CurTC = TC;
6306 });
6307 }
6308 Triples += Action::GetOffloadKindName(CurKind);
6309 Triples += '-';
6310 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006311 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6312 Triples += '-';
6313 Triples += CurDep->getOffloadingArch();
6314 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006315 }
6316 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6317
6318 // Get bundled file command.
6319 CmdArgs.push_back(
6320 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6321
6322 // Get unbundled files command.
6323 SmallString<128> UB;
6324 UB += "-inputs=";
6325 for (unsigned I = 0; I < Inputs.size(); ++I) {
6326 if (I)
6327 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006328
6329 // Find ToolChain for this input.
6330 const ToolChain *CurTC = &getToolChain();
6331 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6332 CurTC = nullptr;
6333 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6334 assert(CurTC == nullptr && "Expected one dependence!");
6335 CurTC = TC;
6336 });
6337 }
6338 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006339 }
6340 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6341
6342 // All the inputs are encoded as commands.
6343 C.addCommand(llvm::make_unique<Command>(
6344 JA, *this,
6345 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6346 CmdArgs, None));
6347}
6348
6349void OffloadBundler::ConstructJobMultipleOutputs(
6350 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6351 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6352 const char *LinkingOutput) const {
6353 // The version with multiple outputs is expected to refer to a unbundling job.
6354 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6355
6356 // The unbundling command looks like this:
6357 // clang-offload-bundler -type=bc
6358 // -targets=host-triple,openmp-triple1,openmp-triple2
6359 // -inputs=input_file
6360 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6361 // -unbundle
6362
6363 ArgStringList CmdArgs;
6364
6365 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6366 InputInfo Input = Inputs.front();
6367
6368 // Get the type.
6369 CmdArgs.push_back(TCArgs.MakeArgString(
6370 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6371
6372 // Get the targets.
6373 SmallString<128> Triples;
6374 Triples += "-targets=";
6375 auto DepInfo = UA.getDependentActionsInfo();
6376 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6377 if (I)
6378 Triples += ',';
6379
6380 auto &Dep = DepInfo[I];
6381 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6382 Triples += '-';
6383 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006384 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6385 !Dep.DependentBoundArch.empty()) {
6386 Triples += '-';
6387 Triples += Dep.DependentBoundArch;
6388 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006389 }
6390
6391 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6392
6393 // Get bundled file command.
6394 CmdArgs.push_back(
6395 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6396
6397 // Get unbundled files command.
6398 SmallString<128> UB;
6399 UB += "-outputs=";
6400 for (unsigned I = 0; I < Outputs.size(); ++I) {
6401 if (I)
6402 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006403 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006404 }
6405 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6406 CmdArgs.push_back("-unbundle");
6407
6408 // All the inputs are encoded as commands.
6409 C.addCommand(llvm::make_unique<Command>(
6410 JA, *this,
6411 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6412 CmdArgs, None));
6413}