blob: d76e175959835aa4f2e88c509b6f342f4f42a0a9 [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"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
Michal Gornydae01c32018-12-23 15:07:26 +000028#include "clang/Driver/Distro.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000029#include "clang/Driver/DriverDiagnostic.h"
30#include "clang/Driver/Options.h"
31#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000032#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000033#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000034#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000035#include "llvm/Option/ArgList.h"
36#include "llvm/Support/CodeGen.h"
37#include "llvm/Support/Compression.h"
38#include "llvm/Support/FileSystem.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/Process.h"
Eric Christopher53b2cb72017-06-30 00:03:56 +000041#include "llvm/Support/TargetParser.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000042#include "llvm/Support/YAMLParser.h"
43
44#ifdef LLVM_ON_UNIX
45#include <unistd.h> // For getuid().
46#endif
47
48using namespace clang::driver;
49using namespace clang::driver::tools;
50using namespace clang;
51using namespace llvm::opt;
52
53static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
54 if (Arg *A =
55 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
56 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
57 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
58 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
59 << A->getBaseArg().getAsString(Args)
60 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
61 }
62 }
63}
64
65static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
66 // In gcc, only ARM checks this, but it seems reasonable to check universally.
67 if (Args.hasArg(options::OPT_static))
68 if (const Arg *A =
69 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
70 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
71 << "-static";
72}
73
74// Add backslashes to escape spaces and other backslashes.
75// This is used for the space-separated argument list specified with
76// the -dwarf-debug-flags option.
77static void EscapeSpacesAndBackslashes(const char *Arg,
78 SmallVectorImpl<char> &Res) {
79 for (; *Arg; ++Arg) {
80 switch (*Arg) {
81 default:
82 break;
83 case ' ':
84 case '\\':
85 Res.push_back('\\');
86 break;
87 }
88 Res.push_back(*Arg);
89 }
90}
91
92// Quote target names for inclusion in GNU Make dependency files.
93// Only the characters '$', '#', ' ', '\t' are quoted.
94static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
95 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
96 switch (Target[i]) {
97 case ' ':
98 case '\t':
99 // Escape the preceding backslashes
100 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
101 Res.push_back('\\');
102
103 // Escape the space/tab
104 Res.push_back('\\');
105 break;
106 case '$':
107 Res.push_back('$');
108 break;
109 case '#':
110 Res.push_back('\\');
111 break;
112 default:
113 break;
114 }
115
116 Res.push_back(Target[i]);
117 }
118}
119
120/// Apply \a Work on the current tool chain \a RegularToolChain and any other
121/// offloading tool chain that is associated with the current action \a JA.
122static void
123forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
124 const ToolChain &RegularToolChain,
125 llvm::function_ref<void(const ToolChain &)> Work) {
126 // Apply Work on the current/regular tool chain.
127 Work(RegularToolChain);
128
129 // Apply Work on all the offloading tool chains associated with the current
130 // action.
131 if (JA.isHostOffloading(Action::OFK_Cuda))
132 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
133 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
134 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
Yaxun Liu398612b2018-05-08 21:02:12 +0000135 else if (JA.isHostOffloading(Action::OFK_HIP))
136 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
137 else if (JA.isDeviceOffloading(Action::OFK_HIP))
138 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
David L. Jonesf561aba2017-03-08 01:02:16 +0000139
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000140 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
141 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
142 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
143 Work(*II->second);
144 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
145 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
146
David L. Jonesf561aba2017-03-08 01:02:16 +0000147 //
148 // TODO: Add support for other offloading programming models here.
149 //
150}
151
152/// This is a helper function for validating the optional refinement step
153/// parameter in reciprocal argument strings. Return false if there is an error
154/// parsing the refinement step. Otherwise, return true and set the Position
155/// of the refinement step in the input string.
156static bool getRefinementStep(StringRef In, const Driver &D,
157 const Arg &A, size_t &Position) {
158 const char RefinementStepToken = ':';
159 Position = In.find(RefinementStepToken);
160 if (Position != StringRef::npos) {
161 StringRef Option = A.getOption().getName();
162 StringRef RefStep = In.substr(Position + 1);
163 // Allow exactly one numeric character for the additional refinement
164 // step parameter. This is reasonable for all currently-supported
165 // operations and architectures because we would expect that a larger value
166 // of refinement steps would cause the estimate "optimization" to
167 // under-perform the native operation. Also, if the estimate does not
168 // converge quickly, it probably will not ever converge, so further
169 // refinement steps will not produce a better answer.
170 if (RefStep.size() != 1) {
171 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
172 return false;
173 }
174 char RefStepChar = RefStep[0];
175 if (RefStepChar < '0' || RefStepChar > '9') {
176 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
177 return false;
178 }
179 }
180 return true;
181}
182
183/// The -mrecip flag requires processing of many optional parameters.
184static void ParseMRecip(const Driver &D, const ArgList &Args,
185 ArgStringList &OutStrings) {
186 StringRef DisabledPrefixIn = "!";
187 StringRef DisabledPrefixOut = "!";
188 StringRef EnabledPrefixOut = "";
189 StringRef Out = "-mrecip=";
190
191 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
192 if (!A)
193 return;
194
195 unsigned NumOptions = A->getNumValues();
196 if (NumOptions == 0) {
197 // No option is the same as "all".
198 OutStrings.push_back(Args.MakeArgString(Out + "all"));
199 return;
200 }
201
202 // Pass through "all", "none", or "default" with an optional refinement step.
203 if (NumOptions == 1) {
204 StringRef Val = A->getValue(0);
205 size_t RefStepLoc;
206 if (!getRefinementStep(Val, D, *A, RefStepLoc))
207 return;
208 StringRef ValBase = Val.slice(0, RefStepLoc);
209 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
210 OutStrings.push_back(Args.MakeArgString(Out + Val));
211 return;
212 }
213 }
214
215 // Each reciprocal type may be enabled or disabled individually.
216 // Check each input value for validity, concatenate them all back together,
217 // and pass through.
218
219 llvm::StringMap<bool> OptionStrings;
220 OptionStrings.insert(std::make_pair("divd", false));
221 OptionStrings.insert(std::make_pair("divf", false));
222 OptionStrings.insert(std::make_pair("vec-divd", false));
223 OptionStrings.insert(std::make_pair("vec-divf", false));
224 OptionStrings.insert(std::make_pair("sqrtd", false));
225 OptionStrings.insert(std::make_pair("sqrtf", false));
226 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
227 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
228
229 for (unsigned i = 0; i != NumOptions; ++i) {
230 StringRef Val = A->getValue(i);
231
232 bool IsDisabled = Val.startswith(DisabledPrefixIn);
233 // Ignore the disablement token for string matching.
234 if (IsDisabled)
235 Val = Val.substr(1);
236
237 size_t RefStep;
238 if (!getRefinementStep(Val, D, *A, RefStep))
239 return;
240
241 StringRef ValBase = Val.slice(0, RefStep);
242 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
243 if (OptionIter == OptionStrings.end()) {
244 // Try again specifying float suffix.
245 OptionIter = OptionStrings.find(ValBase.str() + 'f');
246 if (OptionIter == OptionStrings.end()) {
247 // The input name did not match any known option string.
248 D.Diag(diag::err_drv_unknown_argument) << Val;
249 return;
250 }
251 // The option was specified without a float or double suffix.
252 // Make sure that the double entry was not already specified.
253 // The float entry will be checked below.
254 if (OptionStrings[ValBase.str() + 'd']) {
255 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
256 return;
257 }
258 }
259
260 if (OptionIter->second == true) {
261 // Duplicate option specified.
262 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
263 return;
264 }
265
266 // Mark the matched option as found. Do not allow duplicate specifiers.
267 OptionIter->second = true;
268
269 // If the precision was not specified, also mark the double entry as found.
270 if (ValBase.back() != 'f' && ValBase.back() != 'd')
271 OptionStrings[ValBase.str() + 'd'] = true;
272
273 // Build the output string.
274 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
275 Out = Args.MakeArgString(Out + Prefix + Val);
276 if (i != NumOptions - 1)
277 Out = Args.MakeArgString(Out + ",");
278 }
279
280 OutStrings.push_back(Args.MakeArgString(Out));
281}
282
Craig Topper9a724aa2017-12-11 21:09:19 +0000283/// The -mprefer-vector-width option accepts either a positive integer
284/// or the string "none".
285static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
286 ArgStringList &CmdArgs) {
287 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
288 if (!A)
289 return;
290
291 StringRef Value = A->getValue();
292 if (Value == "none") {
293 CmdArgs.push_back("-mprefer-vector-width=none");
294 } else {
295 unsigned Width;
296 if (Value.getAsInteger(10, Width)) {
297 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
298 return;
299 }
300 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
301 }
302}
303
David L. Jonesf561aba2017-03-08 01:02:16 +0000304static void getWebAssemblyTargetFeatures(const ArgList &Args,
305 std::vector<StringRef> &Features) {
306 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
307}
308
David L. Jonesf561aba2017-03-08 01:02:16 +0000309static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
310 const ArgList &Args, ArgStringList &CmdArgs,
311 bool ForAS) {
312 const Driver &D = TC.getDriver();
313 std::vector<StringRef> Features;
314 switch (Triple.getArch()) {
315 default:
316 break;
317 case llvm::Triple::mips:
318 case llvm::Triple::mipsel:
319 case llvm::Triple::mips64:
320 case llvm::Triple::mips64el:
321 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
322 break;
323
324 case llvm::Triple::arm:
325 case llvm::Triple::armeb:
326 case llvm::Triple::thumb:
327 case llvm::Triple::thumbeb:
328 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
329 break;
330
331 case llvm::Triple::ppc:
332 case llvm::Triple::ppc64:
333 case llvm::Triple::ppc64le:
334 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
335 break;
Alex Bradbury71f45452018-01-11 13:36:56 +0000336 case llvm::Triple::riscv32:
337 case llvm::Triple::riscv64:
338 riscv::getRISCVTargetFeatures(D, Args, Features);
339 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000340 case llvm::Triple::systemz:
341 systemz::getSystemZTargetFeatures(Args, Features);
342 break;
343 case llvm::Triple::aarch64:
344 case llvm::Triple::aarch64_be:
Alex Lorenz9b20a992018-12-17 19:30:46 +0000345 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000346 break;
347 case llvm::Triple::x86:
348 case llvm::Triple::x86_64:
349 x86::getX86TargetFeatures(D, Triple, Args, Features);
350 break;
351 case llvm::Triple::hexagon:
Sumanth Gundapaneni57098f52017-10-18 18:10:13 +0000352 hexagon::getHexagonTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000353 break;
354 case llvm::Triple::wasm32:
355 case llvm::Triple::wasm64:
356 getWebAssemblyTargetFeatures(Args, Features);
357 break;
358 case llvm::Triple::sparc:
359 case llvm::Triple::sparcel:
360 case llvm::Triple::sparcv9:
361 sparc::getSparcTargetFeatures(D, Args, Features);
362 break;
363 case llvm::Triple::r600:
364 case llvm::Triple::amdgcn:
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +0000365 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000366 break;
Anton Korobeynikov93165d62019-01-15 19:44:05 +0000367 case llvm::Triple::msp430:
368 msp430::getMSP430TargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000369 }
370
371 // Find the last of each feature.
372 llvm::StringMap<unsigned> LastOpt;
373 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
374 StringRef Name = Features[I];
375 assert(Name[0] == '-' || Name[0] == '+');
376 LastOpt[Name.drop_front(1)] = I;
377 }
378
379 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
380 // If this feature was overridden, ignore it.
381 StringRef Name = Features[I];
382 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
383 assert(LastI != LastOpt.end());
384 unsigned Last = LastI->second;
385 if (Last != I)
386 continue;
387
388 CmdArgs.push_back("-target-feature");
389 CmdArgs.push_back(Name.data());
390 }
391}
392
393static bool
394shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
395 const llvm::Triple &Triple) {
396 // We use the zero-cost exception tables for Objective-C if the non-fragile
397 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
398 // later.
399 if (runtime.isNonFragile())
400 return true;
401
402 if (!Triple.isMacOSX())
403 return false;
404
405 return (!Triple.isMacOSXVersionLT(10, 5) &&
406 (Triple.getArch() == llvm::Triple::x86_64 ||
407 Triple.getArch() == llvm::Triple::arm));
408}
409
410/// Adds exception related arguments to the driver command arguments. There's a
411/// master flag, -fexceptions and also language specific flags to enable/disable
412/// C++ and Objective-C exceptions. This makes it possible to for example
413/// disable C++ exceptions but enable Objective-C exceptions.
414static void addExceptionArgs(const ArgList &Args, types::ID InputType,
415 const ToolChain &TC, bool KernelOrKext,
416 const ObjCRuntime &objcRuntime,
417 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000418 const llvm::Triple &Triple = TC.getTriple();
419
420 if (KernelOrKext) {
421 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
422 // arguments now to avoid warnings about unused arguments.
423 Args.ClaimAllArgs(options::OPT_fexceptions);
424 Args.ClaimAllArgs(options::OPT_fno_exceptions);
425 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
426 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
427 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
428 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
429 return;
430 }
431
432 // See if the user explicitly enabled exceptions.
433 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
434 false);
435
436 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
437 // is not necessarily sensible, but follows GCC.
438 if (types::isObjC(InputType) &&
439 Args.hasFlag(options::OPT_fobjc_exceptions,
440 options::OPT_fno_objc_exceptions, true)) {
441 CmdArgs.push_back("-fobjc-exceptions");
442
443 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
444 }
445
446 if (types::isCXX(InputType)) {
447 // Disable C++ EH by default on XCore and PS4.
448 bool CXXExceptionsEnabled =
449 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
450 Arg *ExceptionArg = Args.getLastArg(
451 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
452 options::OPT_fexceptions, options::OPT_fno_exceptions);
453 if (ExceptionArg)
454 CXXExceptionsEnabled =
455 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
456 ExceptionArg->getOption().matches(options::OPT_fexceptions);
457
458 if (CXXExceptionsEnabled) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000459 CmdArgs.push_back("-fcxx-exceptions");
460
461 EH = true;
462 }
463 }
464
465 if (EH)
466 CmdArgs.push_back("-fexceptions");
467}
468
469static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
470 bool Default = true;
471 if (TC.getTriple().isOSDarwin()) {
472 // The native darwin assembler doesn't support the linker_option directives,
473 // so we disable them if we think the .s file will be passed to it.
474 Default = TC.useIntegratedAs();
475 }
476 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
477 Default);
478}
479
480static bool ShouldDisableDwarfDirectory(const ArgList &Args,
481 const ToolChain &TC) {
482 bool UseDwarfDirectory =
483 Args.hasFlag(options::OPT_fdwarf_directory_asm,
484 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
485 return !UseDwarfDirectory;
486}
487
488// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
489// to the corresponding DebugInfoKind.
490static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
491 assert(A.getOption().matches(options::OPT_gN_Group) &&
492 "Not a -g option that specifies a debug-info level");
493 if (A.getOption().matches(options::OPT_g0) ||
494 A.getOption().matches(options::OPT_ggdb0))
495 return codegenoptions::NoDebugInfo;
496 if (A.getOption().matches(options::OPT_gline_tables_only) ||
497 A.getOption().matches(options::OPT_ggdb1))
498 return codegenoptions::DebugLineTablesOnly;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000499 if (A.getOption().matches(options::OPT_gline_directives_only))
500 return codegenoptions::DebugDirectivesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +0000501 return codegenoptions::LimitedDebugInfo;
502}
503
504static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
505 switch (Triple.getArch()){
506 default:
507 return false;
508 case llvm::Triple::arm:
509 case llvm::Triple::thumb:
510 // ARM Darwin targets require a frame pointer to be always present to aid
511 // offline debugging via backtraces.
512 return Triple.isOSDarwin();
513 }
514}
515
516static bool useFramePointerForTargetByDefault(const ArgList &Args,
517 const llvm::Triple &Triple) {
518 switch (Triple.getArch()) {
519 case llvm::Triple::xcore:
520 case llvm::Triple::wasm32:
521 case llvm::Triple::wasm64:
Anton Korobeynikovf1f897c2019-02-05 20:15:03 +0000522 case llvm::Triple::msp430:
David L. Jonesf561aba2017-03-08 01:02:16 +0000523 // XCore never wants frame pointers, regardless of OS.
524 // WebAssembly never wants frame pointers.
525 return false;
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000526 case llvm::Triple::riscv32:
527 case llvm::Triple::riscv64:
528 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000529 default:
530 break;
531 }
532
Michal Gorny5a409d02018-12-20 13:09:30 +0000533 if (Triple.isOSNetBSD()) {
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000534 return !areOptimizationsEnabled(Args);
535 }
536
Brad Smith21375ca2019-04-12 01:29:18 +0000537 if (Triple.isOSOpenBSD()) {
538 switch (Triple.getArch()) {
539 case llvm::Triple::mips64:
540 case llvm::Triple::mips64el:
Brad Smith4fccc0c2019-04-19 18:41:40 +0000541 case llvm::Triple::ppc:
Brad Smith21375ca2019-04-12 01:29:18 +0000542 case llvm::Triple::x86:
543 case llvm::Triple::x86_64:
544 return !areOptimizationsEnabled(Args);
545 default:
546 return true;
547 }
548 }
549
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000550 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
551 Triple.isOSHurd()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000552 switch (Triple.getArch()) {
553 // Don't use a frame pointer on linux if optimizing for certain targets.
554 case llvm::Triple::mips64:
555 case llvm::Triple::mips64el:
556 case llvm::Triple::mips:
557 case llvm::Triple::mipsel:
558 case llvm::Triple::ppc:
559 case llvm::Triple::ppc64:
560 case llvm::Triple::ppc64le:
561 case llvm::Triple::systemz:
562 case llvm::Triple::x86:
563 case llvm::Triple::x86_64:
564 return !areOptimizationsEnabled(Args);
565 default:
566 return true;
567 }
568 }
569
570 if (Triple.isOSWindows()) {
571 switch (Triple.getArch()) {
572 case llvm::Triple::x86:
573 return !areOptimizationsEnabled(Args);
574 case llvm::Triple::x86_64:
575 return Triple.isOSBinFormatMachO();
576 case llvm::Triple::arm:
577 case llvm::Triple::thumb:
578 // Windows on ARM builds with FPO disabled to aid fast stack walking
579 return true;
580 default:
581 // All other supported Windows ISAs use xdata unwind information, so frame
582 // pointers are not generally useful.
583 return false;
584 }
585 }
586
587 return true;
588}
589
590static bool shouldUseFramePointer(const ArgList &Args,
591 const llvm::Triple &Triple) {
592 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
593 options::OPT_fomit_frame_pointer))
594 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
595 mustUseNonLeafFramePointerForTarget(Triple);
596
597 if (Args.hasArg(options::OPT_pg))
598 return true;
599
600 return useFramePointerForTargetByDefault(Args, Triple);
601}
602
603static bool shouldUseLeafFramePointer(const ArgList &Args,
604 const llvm::Triple &Triple) {
605 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
606 options::OPT_momit_leaf_frame_pointer))
607 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
608
609 if (Args.hasArg(options::OPT_pg))
610 return true;
611
612 if (Triple.isPS4CPU())
613 return false;
614
615 return useFramePointerForTargetByDefault(Args, Triple);
616}
617
618/// Add a CC1 option to specify the debug compilation directory.
619static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
620 SmallString<128> cwd;
621 if (!llvm::sys::fs::current_path(cwd)) {
622 CmdArgs.push_back("-fdebug-compilation-dir");
623 CmdArgs.push_back(Args.MakeArgString(cwd));
624 }
625}
626
Paul Robinson9b292b42018-07-10 15:15:24 +0000627/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
628static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
629 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
630 StringRef Map = A->getValue();
631 if (Map.find('=') == StringRef::npos)
632 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
633 else
634 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
635 A->claim();
636 }
637}
638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000639/// Vectorize at all optimization levels greater than 1 except for -Oz.
David L. Jonesf561aba2017-03-08 01:02:16 +0000640/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
641static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
642 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
643 if (A->getOption().matches(options::OPT_O4) ||
644 A->getOption().matches(options::OPT_Ofast))
645 return true;
646
647 if (A->getOption().matches(options::OPT_O0))
648 return false;
649
650 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
651
652 // Vectorize -Os.
653 StringRef S(A->getValue());
654 if (S == "s")
655 return true;
656
657 // Don't vectorize -Oz, unless it's the slp vectorizer.
658 if (S == "z")
659 return isSlpVec;
660
661 unsigned OptLevel = 0;
662 if (S.getAsInteger(10, OptLevel))
663 return false;
664
665 return OptLevel > 1;
666 }
667
668 return false;
669}
670
671/// Add -x lang to \p CmdArgs for \p Input.
672static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
673 ArgStringList &CmdArgs) {
674 // When using -verify-pch, we don't want to provide the type
675 // 'precompiled-header' if it was inferred from the file extension
676 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
677 return;
678
679 CmdArgs.push_back("-x");
680 if (Args.hasArg(options::OPT_rewrite_objc))
681 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000682 else {
683 // Map the driver type to the frontend type. This is mostly an identity
684 // mapping, except that the distinction between module interface units
685 // and other source files does not exist at the frontend layer.
686 const char *ClangType;
687 switch (Input.getType()) {
688 case types::TY_CXXModule:
689 ClangType = "c++";
690 break;
691 case types::TY_PP_CXXModule:
692 ClangType = "c++-cpp-output";
693 break;
694 default:
695 ClangType = types::getTypeName(Input.getType());
696 break;
697 }
698 CmdArgs.push_back(ClangType);
699 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000700}
701
702static void appendUserToPath(SmallVectorImpl<char> &Result) {
703#ifdef LLVM_ON_UNIX
704 const char *Username = getenv("LOGNAME");
705#else
706 const char *Username = getenv("USERNAME");
707#endif
708 if (Username) {
709 // Validate that LoginName can be used in a path, and get its length.
710 size_t Len = 0;
711 for (const char *P = Username; *P; ++P, ++Len) {
712 if (!clang::isAlphanumeric(*P) && *P != '_') {
713 Username = nullptr;
714 break;
715 }
716 }
717
718 if (Username && Len > 0) {
719 Result.append(Username, Username + Len);
720 return;
721 }
722 }
723
724// Fallback to user id.
725#ifdef LLVM_ON_UNIX
726 std::string UID = llvm::utostr(getuid());
727#else
728 // FIXME: Windows seems to have an 'SID' that might work.
729 std::string UID = "9999";
730#endif
731 Result.append(UID.begin(), UID.end());
732}
733
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000734static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
735 const Driver &D, const InputInfo &Output,
736 const ArgList &Args,
David L. Jonesf561aba2017-03-08 01:02:16 +0000737 ArgStringList &CmdArgs) {
738
739 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
740 options::OPT_fprofile_generate_EQ,
741 options::OPT_fno_profile_generate);
742 if (PGOGenerateArg &&
743 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
744 PGOGenerateArg = nullptr;
745
Rong Xua4a09b22019-03-04 20:21:31 +0000746 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
747 options::OPT_fcs_profile_generate_EQ,
748 options::OPT_fno_profile_generate);
749 if (CSPGOGenerateArg &&
750 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
751 CSPGOGenerateArg = nullptr;
752
David L. Jonesf561aba2017-03-08 01:02:16 +0000753 auto *ProfileGenerateArg = Args.getLastArg(
754 options::OPT_fprofile_instr_generate,
755 options::OPT_fprofile_instr_generate_EQ,
756 options::OPT_fno_profile_instr_generate);
757 if (ProfileGenerateArg &&
758 ProfileGenerateArg->getOption().matches(
759 options::OPT_fno_profile_instr_generate))
760 ProfileGenerateArg = nullptr;
761
762 if (PGOGenerateArg && ProfileGenerateArg)
763 D.Diag(diag::err_drv_argument_not_allowed_with)
764 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
765
766 auto *ProfileUseArg = getLastProfileUseArg(Args);
767
768 if (PGOGenerateArg && ProfileUseArg)
769 D.Diag(diag::err_drv_argument_not_allowed_with)
770 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
771
772 if (ProfileGenerateArg && ProfileUseArg)
773 D.Diag(diag::err_drv_argument_not_allowed_with)
774 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
775
Rong Xua4a09b22019-03-04 20:21:31 +0000776 if (CSPGOGenerateArg && PGOGenerateArg)
777 D.Diag(diag::err_drv_argument_not_allowed_with)
778 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
779
David L. Jonesf561aba2017-03-08 01:02:16 +0000780 if (ProfileGenerateArg) {
781 if (ProfileGenerateArg->getOption().matches(
782 options::OPT_fprofile_instr_generate_EQ))
783 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
784 ProfileGenerateArg->getValue()));
785 // The default is to use Clang Instrumentation.
786 CmdArgs.push_back("-fprofile-instrument=clang");
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000787 if (TC.getTriple().isWindowsMSVCEnvironment()) {
788 // Add dependent lib for clang_rt.profile
789 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
790 TC.getCompilerRT(Args, "profile")));
791 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000792 }
793
Rong Xua4a09b22019-03-04 20:21:31 +0000794 Arg *PGOGenArg = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +0000795 if (PGOGenerateArg) {
Rong Xua4a09b22019-03-04 20:21:31 +0000796 assert(!CSPGOGenerateArg);
797 PGOGenArg = PGOGenerateArg;
David L. Jonesf561aba2017-03-08 01:02:16 +0000798 CmdArgs.push_back("-fprofile-instrument=llvm");
Rong Xua4a09b22019-03-04 20:21:31 +0000799 }
800 if (CSPGOGenerateArg) {
801 assert(!PGOGenerateArg);
802 PGOGenArg = CSPGOGenerateArg;
803 CmdArgs.push_back("-fprofile-instrument=csllvm");
804 }
805 if (PGOGenArg) {
Russell Gallop72fea1d2019-05-22 10:06:49 +0000806 if (TC.getTriple().isWindowsMSVCEnvironment()) {
807 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
808 TC.getCompilerRT(Args, "profile")));
809 }
Rong Xua4a09b22019-03-04 20:21:31 +0000810 if (PGOGenArg->getOption().matches(
811 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
812 : options::OPT_fcs_profile_generate_EQ)) {
813 SmallString<128> Path(PGOGenArg->getValue());
David L. Jonesf561aba2017-03-08 01:02:16 +0000814 llvm::sys::path::append(Path, "default_%m.profraw");
815 CmdArgs.push_back(
816 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
817 }
818 }
819
820 if (ProfileUseArg) {
821 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
822 CmdArgs.push_back(Args.MakeArgString(
823 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
824 else if ((ProfileUseArg->getOption().matches(
825 options::OPT_fprofile_use_EQ) ||
826 ProfileUseArg->getOption().matches(
827 options::OPT_fprofile_instr_use))) {
828 SmallString<128> Path(
829 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
830 if (Path.empty() || llvm::sys::fs::is_directory(Path))
831 llvm::sys::path::append(Path, "default.profdata");
832 CmdArgs.push_back(
833 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
834 }
835 }
836
837 if (Args.hasArg(options::OPT_ftest_coverage) ||
838 Args.hasArg(options::OPT_coverage))
839 CmdArgs.push_back("-femit-coverage-notes");
840 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
841 false) ||
842 Args.hasArg(options::OPT_coverage))
843 CmdArgs.push_back("-femit-coverage-data");
844
845 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000846 options::OPT_fno_coverage_mapping, false)) {
847 if (!ProfileGenerateArg)
848 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
849 << "-fcoverage-mapping"
850 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000851
David L. Jonesf561aba2017-03-08 01:02:16 +0000852 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000853 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000854
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000855 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
856 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
857 if (!Args.hasArg(options::OPT_coverage))
858 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
859 << "-fprofile-exclude-files="
860 << "--coverage";
861
862 StringRef v = Arg->getValue();
863 CmdArgs.push_back(
864 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
865 }
866
867 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
868 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
869 if (!Args.hasArg(options::OPT_coverage))
870 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
871 << "-fprofile-filter-files="
872 << "--coverage";
873
874 StringRef v = Arg->getValue();
875 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
876 }
877
David L. Jonesf561aba2017-03-08 01:02:16 +0000878 if (C.getArgs().hasArg(options::OPT_c) ||
879 C.getArgs().hasArg(options::OPT_S)) {
880 if (Output.isFilename()) {
881 CmdArgs.push_back("-coverage-notes-file");
882 SmallString<128> OutputFilename;
883 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
884 OutputFilename = FinalOutput->getValue();
885 else
886 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
887 SmallString<128> CoverageFilename = OutputFilename;
888 if (llvm::sys::path::is_relative(CoverageFilename)) {
889 SmallString<128> Pwd;
890 if (!llvm::sys::fs::current_path(Pwd)) {
891 llvm::sys::path::append(Pwd, CoverageFilename);
892 CoverageFilename.swap(Pwd);
893 }
894 }
895 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
896 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
897
898 // Leave -fprofile-dir= an unused argument unless .gcda emission is
899 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
900 // the flag used. There is no -fno-profile-dir, so the user has no
901 // targeted way to suppress the warning.
902 if (Args.hasArg(options::OPT_fprofile_arcs) ||
903 Args.hasArg(options::OPT_coverage)) {
904 CmdArgs.push_back("-coverage-data-file");
905 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
906 CoverageFilename = FProfileDir->getValue();
907 llvm::sys::path::append(CoverageFilename, OutputFilename);
908 }
909 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
910 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
911 }
912 }
913 }
914}
915
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000916/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000917static bool ContainsCompileAction(const Action *A) {
918 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
919 return true;
920
921 for (const auto &AI : A->inputs())
922 if (ContainsCompileAction(AI))
923 return true;
924
925 return false;
926}
927
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000928/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000929/// This is done by default when compiling non-assembler source with -O0.
930static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
931 bool RelaxDefault = true;
932
933 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
934 RelaxDefault = A->getOption().matches(options::OPT_O0);
935
936 if (RelaxDefault) {
937 RelaxDefault = false;
938 for (const auto &Act : C.getActions()) {
939 if (ContainsCompileAction(Act)) {
940 RelaxDefault = true;
941 break;
942 }
943 }
944 }
945
946 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
947 RelaxDefault);
948}
949
950// Extract the integer N from a string spelled "-dwarf-N", returning 0
951// on mismatch. The StringRef input (rather than an Arg) allows
952// for use by the "-Xassembler" option parser.
953static unsigned DwarfVersionNum(StringRef ArgValue) {
954 return llvm::StringSwitch<unsigned>(ArgValue)
955 .Case("-gdwarf-2", 2)
956 .Case("-gdwarf-3", 3)
957 .Case("-gdwarf-4", 4)
958 .Case("-gdwarf-5", 5)
959 .Default(0);
960}
961
962static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
963 codegenoptions::DebugInfoKind DebugInfoKind,
964 unsigned DwarfVersion,
965 llvm::DebuggerKind DebuggerTuning) {
966 switch (DebugInfoKind) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000967 case codegenoptions::DebugDirectivesOnly:
968 CmdArgs.push_back("-debug-info-kind=line-directives-only");
969 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000970 case codegenoptions::DebugLineTablesOnly:
971 CmdArgs.push_back("-debug-info-kind=line-tables-only");
972 break;
973 case codegenoptions::LimitedDebugInfo:
974 CmdArgs.push_back("-debug-info-kind=limited");
975 break;
976 case codegenoptions::FullDebugInfo:
977 CmdArgs.push_back("-debug-info-kind=standalone");
978 break;
979 default:
980 break;
981 }
982 if (DwarfVersion > 0)
983 CmdArgs.push_back(
984 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
985 switch (DebuggerTuning) {
986 case llvm::DebuggerKind::GDB:
987 CmdArgs.push_back("-debugger-tuning=gdb");
988 break;
989 case llvm::DebuggerKind::LLDB:
990 CmdArgs.push_back("-debugger-tuning=lldb");
991 break;
992 case llvm::DebuggerKind::SCE:
993 CmdArgs.push_back("-debugger-tuning=sce");
994 break;
995 default:
996 break;
997 }
998}
999
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001000static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1001 const Driver &D, const ToolChain &TC) {
1002 assert(A && "Expected non-nullptr argument.");
1003 if (TC.supportsDebugInfoOption(A))
1004 return true;
1005 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1006 << A->getAsString(Args) << TC.getTripleString();
1007 return false;
1008}
1009
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001010static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1011 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001012 const Driver &D,
1013 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001014 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
1015 if (!A)
1016 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001017 if (checkDebugInfoOption(A, Args, D, TC)) {
1018 if (A->getOption().getID() == options::OPT_gz) {
1019 if (llvm::zlib::isAvailable())
Fangrui Songbaabc872019-05-11 01:14:50 +00001020 CmdArgs.push_back("--compress-debug-sections");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001021 else
1022 D.Diag(diag::warn_debug_compression_unavailable);
1023 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001024 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001025
1026 StringRef Value = A->getValue();
1027 if (Value == "none") {
Fangrui Songbaabc872019-05-11 01:14:50 +00001028 CmdArgs.push_back("--compress-debug-sections=none");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001029 } else if (Value == "zlib" || Value == "zlib-gnu") {
1030 if (llvm::zlib::isAvailable()) {
1031 CmdArgs.push_back(
Fangrui Songbaabc872019-05-11 01:14:50 +00001032 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001033 } else {
1034 D.Diag(diag::warn_debug_compression_unavailable);
1035 }
1036 } else {
1037 D.Diag(diag::err_drv_unsupported_option_argument)
1038 << A->getOption().getName() << Value;
1039 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001040 }
1041}
1042
David L. Jonesf561aba2017-03-08 01:02:16 +00001043static const char *RelocationModelName(llvm::Reloc::Model Model) {
1044 switch (Model) {
1045 case llvm::Reloc::Static:
1046 return "static";
1047 case llvm::Reloc::PIC_:
1048 return "pic";
1049 case llvm::Reloc::DynamicNoPIC:
1050 return "dynamic-no-pic";
1051 case llvm::Reloc::ROPI:
1052 return "ropi";
1053 case llvm::Reloc::RWPI:
1054 return "rwpi";
1055 case llvm::Reloc::ROPI_RWPI:
1056 return "ropi-rwpi";
1057 }
1058 llvm_unreachable("Unknown Reloc::Model kind");
1059}
1060
1061void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1062 const Driver &D, const ArgList &Args,
1063 ArgStringList &CmdArgs,
1064 const InputInfo &Output,
1065 const InputInfoList &Inputs) const {
1066 Arg *A;
1067 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1068
1069 CheckPreprocessingOptions(D, Args);
1070
1071 Args.AddLastArg(CmdArgs, options::OPT_C);
1072 Args.AddLastArg(CmdArgs, options::OPT_CC);
1073
1074 // Handle dependency file generation.
1075 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1076 (A = Args.getLastArg(options::OPT_MD)) ||
1077 (A = Args.getLastArg(options::OPT_MMD))) {
1078 // Determine the output location.
1079 const char *DepFile;
1080 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1081 DepFile = MF->getValue();
1082 C.addFailureResultFile(DepFile, &JA);
1083 } else if (Output.getType() == types::TY_Dependencies) {
1084 DepFile = Output.getFilename();
1085 } else if (A->getOption().matches(options::OPT_M) ||
1086 A->getOption().matches(options::OPT_MM)) {
1087 DepFile = "-";
1088 } else {
1089 DepFile = getDependencyFileName(Args, Inputs);
1090 C.addFailureResultFile(DepFile, &JA);
1091 }
1092 CmdArgs.push_back("-dependency-file");
1093 CmdArgs.push_back(DepFile);
1094
1095 // Add a default target if one wasn't specified.
1096 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1097 const char *DepTarget;
1098
1099 // If user provided -o, that is the dependency target, except
1100 // when we are only generating a dependency file.
1101 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1102 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1103 DepTarget = OutputOpt->getValue();
1104 } else {
1105 // Otherwise derive from the base input.
1106 //
1107 // FIXME: This should use the computed output file location.
1108 SmallString<128> P(Inputs[0].getBaseInput());
1109 llvm::sys::path::replace_extension(P, "o");
1110 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1111 }
1112
Yuka Takahashicdb53482017-06-16 16:01:13 +00001113 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1114 CmdArgs.push_back("-w");
1115 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001116 CmdArgs.push_back("-MT");
1117 SmallString<128> Quoted;
1118 QuoteTarget(DepTarget, Quoted);
1119 CmdArgs.push_back(Args.MakeArgString(Quoted));
1120 }
1121
1122 if (A->getOption().matches(options::OPT_M) ||
1123 A->getOption().matches(options::OPT_MD))
1124 CmdArgs.push_back("-sys-header-deps");
1125 if ((isa<PrecompileJobAction>(JA) &&
1126 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1127 Args.hasArg(options::OPT_fmodule_file_deps))
1128 CmdArgs.push_back("-module-file-deps");
1129 }
1130
1131 if (Args.hasArg(options::OPT_MG)) {
1132 if (!A || A->getOption().matches(options::OPT_MD) ||
1133 A->getOption().matches(options::OPT_MMD))
1134 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1135 CmdArgs.push_back("-MG");
1136 }
1137
1138 Args.AddLastArg(CmdArgs, options::OPT_MP);
1139 Args.AddLastArg(CmdArgs, options::OPT_MV);
1140
1141 // Convert all -MQ <target> args to -MT <quoted target>
1142 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1143 A->claim();
1144
1145 if (A->getOption().matches(options::OPT_MQ)) {
1146 CmdArgs.push_back("-MT");
1147 SmallString<128> Quoted;
1148 QuoteTarget(A->getValue(), Quoted);
1149 CmdArgs.push_back(Args.MakeArgString(Quoted));
1150
1151 // -MT flag - no change
1152 } else {
1153 A->render(Args, CmdArgs);
1154 }
1155 }
1156
1157 // Add offload include arguments specific for CUDA. This must happen before
1158 // we -I or -include anything else, because we must pick up the CUDA headers
1159 // from the particular CUDA installation, rather than from e.g.
1160 // /usr/local/include.
1161 if (JA.isOffloading(Action::OFK_Cuda))
1162 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1163
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001164 // If we are offloading to a target via OpenMP we need to include the
1165 // openmp_wrappers folder which contains alternative system headers.
1166 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1167 getToolChain().getTriple().isNVPTX()){
1168 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1169 // Add openmp_wrappers/* to our system include path. This lets us wrap
1170 // standard library headers.
1171 SmallString<128> P(D.ResourceDir);
1172 llvm::sys::path::append(P, "include");
1173 llvm::sys::path::append(P, "openmp_wrappers");
1174 CmdArgs.push_back("-internal-isystem");
1175 CmdArgs.push_back(Args.MakeArgString(P));
1176 }
1177
1178 CmdArgs.push_back("-include");
Gheorghe-Teodor Bercea94695712019-05-13 22:11:44 +00001179 CmdArgs.push_back("__clang_openmp_math_declares.h");
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001180 }
1181
David L. Jonesf561aba2017-03-08 01:02:16 +00001182 // Add -i* options, and automatically translate to
1183 // -include-pch/-include-pth for transparent PCH support. It's
1184 // wonky, but we include looking for .gch so we can support seamless
1185 // replacement into a build system already set up to be generating
1186 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001187
1188 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001189 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1190 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001191 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1192 JA.getKind() <= Action::AssembleJobClass) {
1193 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001194 }
Erich Keane76675de2018-07-05 17:22:13 +00001195 if (YcArg || YuArg) {
1196 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1197 if (!isa<PrecompileJobAction>(JA)) {
1198 CmdArgs.push_back("-include-pch");
Mike Rice58df1af2018-09-11 17:10:44 +00001199 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1200 C, !ThroughHeader.empty()
1201 ? ThroughHeader
1202 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
Erich Keane76675de2018-07-05 17:22:13 +00001203 }
Mike Rice58df1af2018-09-11 17:10:44 +00001204
1205 if (ThroughHeader.empty()) {
1206 CmdArgs.push_back(Args.MakeArgString(
1207 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1208 } else {
1209 CmdArgs.push_back(
1210 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1211 }
Erich Keane76675de2018-07-05 17:22:13 +00001212 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001213 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001214
1215 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001216 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001217 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001218 // Handling of gcc-style gch precompiled headers.
1219 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1220 RenderedImplicitInclude = true;
1221
David L. Jonesf561aba2017-03-08 01:02:16 +00001222 bool FoundPCH = false;
1223 SmallString<128> P(A->getValue());
1224 // We want the files to have a name like foo.h.pch. Add a dummy extension
1225 // so that replace_extension does the right thing.
1226 P += ".dummy";
Erich Keane0a6b5b62018-12-04 14:34:09 +00001227 llvm::sys::path::replace_extension(P, "pch");
1228 if (llvm::sys::fs::exists(P))
1229 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001230
1231 if (!FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001232 llvm::sys::path::replace_extension(P, "gch");
1233 if (llvm::sys::fs::exists(P)) {
Erich Keane0a6b5b62018-12-04 14:34:09 +00001234 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001235 }
1236 }
1237
Erich Keane0a6b5b62018-12-04 14:34:09 +00001238 if (FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001239 if (IsFirstImplicitInclude) {
1240 A->claim();
Erich Keane0a6b5b62018-12-04 14:34:09 +00001241 CmdArgs.push_back("-include-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00001242 CmdArgs.push_back(Args.MakeArgString(P));
1243 continue;
1244 } else {
1245 // Ignore the PCH if not first on command line and emit warning.
1246 D.Diag(diag::warn_drv_pch_not_first_include) << P
1247 << A->getAsString(Args);
1248 }
1249 }
1250 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1251 // Handling of paths which must come late. These entries are handled by
1252 // the toolchain itself after the resource dir is inserted in the right
1253 // search order.
1254 // Do not claim the argument so that the use of the argument does not
1255 // silently go unnoticed on toolchains which do not honour the option.
1256 continue;
1257 }
1258
1259 // Not translated, render as usual.
1260 A->claim();
1261 A->render(Args, CmdArgs);
1262 }
1263
1264 Args.AddAllArgs(CmdArgs,
1265 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1266 options::OPT_F, options::OPT_index_header_map});
1267
1268 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1269
1270 // FIXME: There is a very unfortunate problem here, some troubled
1271 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1272 // really support that we would have to parse and then translate
1273 // those options. :(
1274 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1275 options::OPT_Xpreprocessor);
1276
1277 // -I- is a deprecated GCC feature, reject it.
1278 if (Arg *A = Args.getLastArg(options::OPT_I_))
1279 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1280
1281 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1282 // -isysroot to the CC1 invocation.
1283 StringRef sysroot = C.getSysRoot();
1284 if (sysroot != "") {
1285 if (!Args.hasArg(options::OPT_isysroot)) {
1286 CmdArgs.push_back("-isysroot");
1287 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1288 }
1289 }
1290
1291 // Parse additional include paths from environment variables.
1292 // FIXME: We should probably sink the logic for handling these from the
1293 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1294 // CPATH - included following the user specified includes (but prior to
1295 // builtin and standard includes).
1296 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1297 // C_INCLUDE_PATH - system includes enabled when compiling C.
1298 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1299 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1300 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1301 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1302 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1303 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1304 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1305
1306 // While adding the include arguments, we also attempt to retrieve the
1307 // arguments of related offloading toolchains or arguments that are specific
1308 // of an offloading programming model.
1309
1310 // Add C++ include arguments, if needed.
1311 if (types::isCXX(Inputs[0].getType()))
1312 forAllAssociatedToolChains(C, JA, getToolChain(),
1313 [&Args, &CmdArgs](const ToolChain &TC) {
1314 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1315 });
1316
1317 // Add system include arguments for all targets but IAMCU.
1318 if (!IsIAMCU)
1319 forAllAssociatedToolChains(C, JA, getToolChain(),
1320 [&Args, &CmdArgs](const ToolChain &TC) {
1321 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1322 });
1323 else {
1324 // For IAMCU add special include arguments.
1325 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1326 }
1327}
1328
1329// FIXME: Move to target hook.
1330static bool isSignedCharDefault(const llvm::Triple &Triple) {
1331 switch (Triple.getArch()) {
1332 default:
1333 return true;
1334
1335 case llvm::Triple::aarch64:
1336 case llvm::Triple::aarch64_be:
1337 case llvm::Triple::arm:
1338 case llvm::Triple::armeb:
1339 case llvm::Triple::thumb:
1340 case llvm::Triple::thumbeb:
1341 if (Triple.isOSDarwin() || Triple.isOSWindows())
1342 return true;
1343 return false;
1344
1345 case llvm::Triple::ppc:
1346 case llvm::Triple::ppc64:
1347 if (Triple.isOSDarwin())
1348 return true;
1349 return false;
1350
1351 case llvm::Triple::hexagon:
1352 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001353 case llvm::Triple::riscv32:
1354 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001355 case llvm::Triple::systemz:
1356 case llvm::Triple::xcore:
1357 return false;
1358 }
1359}
1360
1361static bool isNoCommonDefault(const llvm::Triple &Triple) {
1362 switch (Triple.getArch()) {
1363 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001364 if (Triple.isOSFuchsia())
1365 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001366 return false;
1367
1368 case llvm::Triple::xcore:
1369 case llvm::Triple::wasm32:
1370 case llvm::Triple::wasm64:
1371 return true;
1372 }
1373}
1374
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001375namespace {
1376void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1377 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001378 // Select the ABI to use.
1379 // FIXME: Support -meabi.
1380 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1381 const char *ABIName = nullptr;
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001382 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001383 ABIName = A->getValue();
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001384 } else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001385 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001386 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001387 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001388
David L. Jonesf561aba2017-03-08 01:02:16 +00001389 CmdArgs.push_back("-target-abi");
1390 CmdArgs.push_back(ABIName);
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001391}
1392}
1393
1394void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1395 ArgStringList &CmdArgs, bool KernelOrKext) const {
1396 RenderARMABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001397
1398 // Determine floating point ABI from the options & target defaults.
1399 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1400 if (ABI == arm::FloatABI::Soft) {
1401 // Floating point operations and argument passing are soft.
1402 // FIXME: This changes CPP defines, we need -target-soft-float.
1403 CmdArgs.push_back("-msoft-float");
1404 CmdArgs.push_back("-mfloat-abi");
1405 CmdArgs.push_back("soft");
1406 } else if (ABI == arm::FloatABI::SoftFP) {
1407 // Floating point operations are hard, but argument passing is soft.
1408 CmdArgs.push_back("-mfloat-abi");
1409 CmdArgs.push_back("soft");
1410 } else {
1411 // Floating point operations and argument passing are hard.
1412 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1413 CmdArgs.push_back("-mfloat-abi");
1414 CmdArgs.push_back("hard");
1415 }
1416
1417 // Forward the -mglobal-merge option for explicit control over the pass.
1418 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1419 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001420 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001421 if (A->getOption().matches(options::OPT_mno_global_merge))
1422 CmdArgs.push_back("-arm-global-merge=false");
1423 else
1424 CmdArgs.push_back("-arm-global-merge=true");
1425 }
1426
1427 if (!Args.hasFlag(options::OPT_mimplicit_float,
1428 options::OPT_mno_implicit_float, true))
1429 CmdArgs.push_back("-no-implicit-float");
Javed Absar603a2ba2019-05-21 14:21:26 +00001430
1431 if (Args.getLastArg(options::OPT_mcmse))
1432 CmdArgs.push_back("-mcmse");
David L. Jonesf561aba2017-03-08 01:02:16 +00001433}
1434
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001435void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1436 const ArgList &Args, bool KernelOrKext,
1437 ArgStringList &CmdArgs) const {
1438 const ToolChain &TC = getToolChain();
1439
1440 // Add the target features
1441 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1442
1443 // Add target specific flags.
1444 switch (TC.getArch()) {
1445 default:
1446 break;
1447
1448 case llvm::Triple::arm:
1449 case llvm::Triple::armeb:
1450 case llvm::Triple::thumb:
1451 case llvm::Triple::thumbeb:
1452 // Use the effective triple, which takes into account the deployment target.
1453 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1454 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1455 break;
1456
1457 case llvm::Triple::aarch64:
1458 case llvm::Triple::aarch64_be:
1459 AddAArch64TargetArgs(Args, CmdArgs);
1460 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1461 break;
1462
1463 case llvm::Triple::mips:
1464 case llvm::Triple::mipsel:
1465 case llvm::Triple::mips64:
1466 case llvm::Triple::mips64el:
1467 AddMIPSTargetArgs(Args, CmdArgs);
1468 break;
1469
1470 case llvm::Triple::ppc:
1471 case llvm::Triple::ppc64:
1472 case llvm::Triple::ppc64le:
1473 AddPPCTargetArgs(Args, CmdArgs);
1474 break;
1475
Alex Bradbury71f45452018-01-11 13:36:56 +00001476 case llvm::Triple::riscv32:
1477 case llvm::Triple::riscv64:
1478 AddRISCVTargetArgs(Args, CmdArgs);
1479 break;
1480
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001481 case llvm::Triple::sparc:
1482 case llvm::Triple::sparcel:
1483 case llvm::Triple::sparcv9:
1484 AddSparcTargetArgs(Args, CmdArgs);
1485 break;
1486
1487 case llvm::Triple::systemz:
1488 AddSystemZTargetArgs(Args, CmdArgs);
1489 break;
1490
1491 case llvm::Triple::x86:
1492 case llvm::Triple::x86_64:
1493 AddX86TargetArgs(Args, CmdArgs);
1494 break;
1495
1496 case llvm::Triple::lanai:
1497 AddLanaiTargetArgs(Args, CmdArgs);
1498 break;
1499
1500 case llvm::Triple::hexagon:
1501 AddHexagonTargetArgs(Args, CmdArgs);
1502 break;
1503
1504 case llvm::Triple::wasm32:
1505 case llvm::Triple::wasm64:
1506 AddWebAssemblyTargetArgs(Args, CmdArgs);
1507 break;
1508 }
1509}
1510
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001511// Parse -mbranch-protection=<protection>[+<protection>]* where
1512// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1513// Returns a triple of (return address signing Scope, signing key, require
1514// landing pads)
1515static std::tuple<StringRef, StringRef, bool>
1516ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1517 const Arg *A) {
1518 StringRef Scope = "none";
1519 StringRef Key = "a_key";
1520 bool IndirectBranches = false;
1521
1522 StringRef Value = A->getValue();
1523 // This maps onto -mbranch-protection=<scope>+<key>
1524
1525 if (Value.equals("standard")) {
1526 Scope = "non-leaf";
1527 Key = "a_key";
1528 IndirectBranches = true;
1529
1530 } else if (!Value.equals("none")) {
1531 SmallVector<StringRef, 4> BranchProtection;
1532 StringRef(A->getValue()).split(BranchProtection, '+');
1533
1534 auto Protection = BranchProtection.begin();
1535 while (Protection != BranchProtection.end()) {
1536 if (Protection->equals("bti"))
1537 IndirectBranches = true;
1538 else if (Protection->equals("pac-ret")) {
1539 Scope = "non-leaf";
1540 while (++Protection != BranchProtection.end()) {
1541 // Inner loop as "leaf" and "b-key" options must only appear attached
1542 // to pac-ret.
1543 if (Protection->equals("leaf"))
1544 Scope = "all";
1545 else if (Protection->equals("b-key"))
1546 Key = "b_key";
1547 else
1548 break;
1549 }
1550 Protection--;
1551 } else
1552 D.Diag(diag::err_invalid_branch_protection)
1553 << *Protection << A->getAsString(Args);
1554 Protection++;
1555 }
1556 }
1557
1558 return std::make_tuple(Scope, Key, IndirectBranches);
1559}
1560
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001561namespace {
1562void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1563 ArgStringList &CmdArgs) {
1564 const char *ABIName = nullptr;
1565 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1566 ABIName = A->getValue();
1567 else if (Triple.isOSDarwin())
1568 ABIName = "darwinpcs";
1569 else
1570 ABIName = "aapcs";
1571
1572 CmdArgs.push_back("-target-abi");
1573 CmdArgs.push_back(ABIName);
1574}
1575}
1576
David L. Jonesf561aba2017-03-08 01:02:16 +00001577void Clang::AddAArch64TargetArgs(const ArgList &Args,
1578 ArgStringList &CmdArgs) const {
1579 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1580
1581 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1582 Args.hasArg(options::OPT_mkernel) ||
1583 Args.hasArg(options::OPT_fapple_kext))
1584 CmdArgs.push_back("-disable-red-zone");
1585
1586 if (!Args.hasFlag(options::OPT_mimplicit_float,
1587 options::OPT_mno_implicit_float, true))
1588 CmdArgs.push_back("-no-implicit-float");
1589
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001590 RenderAArch64ABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001591
1592 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1593 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001594 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001595 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1596 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1597 else
1598 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1599 } else if (Triple.isAndroid()) {
1600 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001601 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001602 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1603 }
1604
1605 // Forward the -mglobal-merge option for explicit control over the pass.
1606 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1607 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001608 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001609 if (A->getOption().matches(options::OPT_mno_global_merge))
1610 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1611 else
1612 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1613 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001614
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001615 // Enable/disable return address signing and indirect branch targets.
1616 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1617 options::OPT_mbranch_protection_EQ)) {
1618
1619 const Driver &D = getToolChain().getDriver();
1620
1621 StringRef Scope, Key;
1622 bool IndirectBranches;
1623
1624 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1625 Scope = A->getValue();
1626 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1627 !Scope.equals("all"))
1628 D.Diag(diag::err_invalid_branch_protection)
1629 << Scope << A->getAsString(Args);
1630 Key = "a_key";
1631 IndirectBranches = false;
1632 } else
1633 std::tie(Scope, Key, IndirectBranches) =
1634 ParseAArch64BranchProtection(D, Args, A);
1635
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001636 CmdArgs.push_back(
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001637 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1638 CmdArgs.push_back(
1639 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1640 if (IndirectBranches)
1641 CmdArgs.push_back("-mbranch-target-enforce");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001642 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001643}
1644
1645void Clang::AddMIPSTargetArgs(const ArgList &Args,
1646 ArgStringList &CmdArgs) const {
1647 const Driver &D = getToolChain().getDriver();
1648 StringRef CPUName;
1649 StringRef ABIName;
1650 const llvm::Triple &Triple = getToolChain().getTriple();
1651 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1652
1653 CmdArgs.push_back("-target-abi");
1654 CmdArgs.push_back(ABIName.data());
1655
1656 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1657 if (ABI == mips::FloatABI::Soft) {
1658 // Floating point operations and argument passing are soft.
1659 CmdArgs.push_back("-msoft-float");
1660 CmdArgs.push_back("-mfloat-abi");
1661 CmdArgs.push_back("soft");
1662 } else {
1663 // Floating point operations and argument passing are hard.
1664 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1665 CmdArgs.push_back("-mfloat-abi");
1666 CmdArgs.push_back("hard");
1667 }
1668
1669 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1670 if (A->getOption().matches(options::OPT_mxgot)) {
1671 CmdArgs.push_back("-mllvm");
1672 CmdArgs.push_back("-mxgot");
1673 }
1674 }
1675
1676 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1677 options::OPT_mno_ldc1_sdc1)) {
1678 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1679 CmdArgs.push_back("-mllvm");
1680 CmdArgs.push_back("-mno-ldc1-sdc1");
1681 }
1682 }
1683
1684 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1685 options::OPT_mno_check_zero_division)) {
1686 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1687 CmdArgs.push_back("-mllvm");
1688 CmdArgs.push_back("-mno-check-zero-division");
1689 }
1690 }
1691
1692 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1693 StringRef v = A->getValue();
1694 CmdArgs.push_back("-mllvm");
1695 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1696 A->claim();
1697 }
1698
Simon Dardis31636a12017-07-20 14:04:12 +00001699 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1700 Arg *ABICalls =
1701 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1702
1703 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1704 // -mgpopt is the default for static, -fno-pic environments but these two
1705 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1706 // the only case where -mllvm -mgpopt is passed.
1707 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1708 // passed explicitly when compiling something with -mabicalls
1709 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001710 //
1711 // When the ABI in use is N64, we also need to determine the PIC mode that
1712 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001713 bool NoABICalls =
1714 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001715
1716 llvm::Reloc::Model RelocationModel;
1717 unsigned PICLevel;
1718 bool IsPIE;
1719 std::tie(RelocationModel, PICLevel, IsPIE) =
1720 ParsePICArgs(getToolChain(), Args);
1721
1722 NoABICalls = NoABICalls ||
1723 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1724
Simon Dardis31636a12017-07-20 14:04:12 +00001725 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1726 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1727 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1728 CmdArgs.push_back("-mllvm");
1729 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001730
1731 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1732 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001733 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001734 options::OPT_mno_extern_sdata);
1735 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1736 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001737 if (LocalSData) {
1738 CmdArgs.push_back("-mllvm");
1739 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1740 CmdArgs.push_back("-mlocal-sdata=1");
1741 } else {
1742 CmdArgs.push_back("-mlocal-sdata=0");
1743 }
1744 LocalSData->claim();
1745 }
1746
Simon Dardis7d318782017-07-24 14:02:09 +00001747 if (ExternSData) {
1748 CmdArgs.push_back("-mllvm");
1749 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1750 CmdArgs.push_back("-mextern-sdata=1");
1751 } else {
1752 CmdArgs.push_back("-mextern-sdata=0");
1753 }
1754 ExternSData->claim();
1755 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001756
1757 if (EmbeddedData) {
1758 CmdArgs.push_back("-mllvm");
1759 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1760 CmdArgs.push_back("-membedded-data=1");
1761 } else {
1762 CmdArgs.push_back("-membedded-data=0");
1763 }
1764 EmbeddedData->claim();
1765 }
1766
Simon Dardis31636a12017-07-20 14:04:12 +00001767 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1768 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1769
1770 if (GPOpt)
1771 GPOpt->claim();
1772
David L. Jonesf561aba2017-03-08 01:02:16 +00001773 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1774 StringRef Val = StringRef(A->getValue());
1775 if (mips::hasCompactBranches(CPUName)) {
1776 if (Val == "never" || Val == "always" || Val == "optimal") {
1777 CmdArgs.push_back("-mllvm");
1778 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1779 } else
1780 D.Diag(diag::err_drv_unsupported_option_argument)
1781 << A->getOption().getName() << Val;
1782 } else
1783 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1784 }
Vladimir Stefanovic99113a02019-01-18 19:54:51 +00001785
1786 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1787 options::OPT_mno_relax_pic_calls)) {
1788 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1789 CmdArgs.push_back("-mllvm");
1790 CmdArgs.push_back("-mips-jalr-reloc=0");
1791 }
1792 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001793}
1794
1795void Clang::AddPPCTargetArgs(const ArgList &Args,
1796 ArgStringList &CmdArgs) const {
1797 // Select the ABI to use.
1798 const char *ABIName = nullptr;
1799 if (getToolChain().getTriple().isOSLinux())
1800 switch (getToolChain().getArch()) {
1801 case llvm::Triple::ppc64: {
1802 // When targeting a processor that supports QPX, or if QPX is
1803 // specifically enabled, default to using the ABI that supports QPX (so
1804 // long as it is not specifically disabled).
1805 bool HasQPX = false;
1806 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1807 HasQPX = A->getValue() == StringRef("a2q");
1808 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1809 if (HasQPX) {
1810 ABIName = "elfv1-qpx";
1811 break;
1812 }
1813
1814 ABIName = "elfv1";
1815 break;
1816 }
1817 case llvm::Triple::ppc64le:
1818 ABIName = "elfv2";
1819 break;
1820 default:
1821 break;
1822 }
1823
1824 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1825 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1826 // the option if given as we don't have backend support for any targets
1827 // that don't use the altivec abi.
1828 if (StringRef(A->getValue()) != "altivec")
1829 ABIName = A->getValue();
1830
1831 ppc::FloatABI FloatABI =
1832 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1833
1834 if (FloatABI == ppc::FloatABI::Soft) {
1835 // Floating point operations and argument passing are soft.
1836 CmdArgs.push_back("-msoft-float");
1837 CmdArgs.push_back("-mfloat-abi");
1838 CmdArgs.push_back("soft");
1839 } else {
1840 // Floating point operations and argument passing are hard.
1841 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1842 CmdArgs.push_back("-mfloat-abi");
1843 CmdArgs.push_back("hard");
1844 }
1845
1846 if (ABIName) {
1847 CmdArgs.push_back("-target-abi");
1848 CmdArgs.push_back(ABIName);
1849 }
1850}
1851
Alex Bradbury71f45452018-01-11 13:36:56 +00001852void Clang::AddRISCVTargetArgs(const ArgList &Args,
1853 ArgStringList &CmdArgs) const {
1854 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001855 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001856 const char *ABIName = nullptr;
1857 const llvm::Triple &Triple = getToolChain().getTriple();
1858 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1859 ABIName = A->getValue();
1860 else if (Triple.getArch() == llvm::Triple::riscv32)
1861 ABIName = "ilp32";
1862 else if (Triple.getArch() == llvm::Triple::riscv64)
1863 ABIName = "lp64";
1864 else
1865 llvm_unreachable("Unexpected triple!");
1866
1867 CmdArgs.push_back("-target-abi");
1868 CmdArgs.push_back(ABIName);
1869}
1870
David L. Jonesf561aba2017-03-08 01:02:16 +00001871void Clang::AddSparcTargetArgs(const ArgList &Args,
1872 ArgStringList &CmdArgs) const {
1873 sparc::FloatABI FloatABI =
1874 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1875
1876 if (FloatABI == sparc::FloatABI::Soft) {
1877 // Floating point operations and argument passing are soft.
1878 CmdArgs.push_back("-msoft-float");
1879 CmdArgs.push_back("-mfloat-abi");
1880 CmdArgs.push_back("soft");
1881 } else {
1882 // Floating point operations and argument passing are hard.
1883 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1884 CmdArgs.push_back("-mfloat-abi");
1885 CmdArgs.push_back("hard");
1886 }
1887}
1888
1889void Clang::AddSystemZTargetArgs(const ArgList &Args,
1890 ArgStringList &CmdArgs) const {
1891 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1892 CmdArgs.push_back("-mbackchain");
1893}
1894
1895void Clang::AddX86TargetArgs(const ArgList &Args,
1896 ArgStringList &CmdArgs) const {
1897 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1898 Args.hasArg(options::OPT_mkernel) ||
1899 Args.hasArg(options::OPT_fapple_kext))
1900 CmdArgs.push_back("-disable-red-zone");
1901
Kristina Brooks7f569b72018-10-18 14:07:02 +00001902 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1903 options::OPT_mno_tls_direct_seg_refs, true))
1904 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1905
David L. Jonesf561aba2017-03-08 01:02:16 +00001906 // Default to avoid implicit floating-point for kernel/kext code, but allow
1907 // that to be overridden with -mno-soft-float.
1908 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1909 Args.hasArg(options::OPT_fapple_kext));
1910 if (Arg *A = Args.getLastArg(
1911 options::OPT_msoft_float, options::OPT_mno_soft_float,
1912 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1913 const Option &O = A->getOption();
1914 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1915 O.matches(options::OPT_msoft_float));
1916 }
1917 if (NoImplicitFloat)
1918 CmdArgs.push_back("-no-implicit-float");
1919
1920 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1921 StringRef Value = A->getValue();
1922 if (Value == "intel" || Value == "att") {
1923 CmdArgs.push_back("-mllvm");
1924 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1925 } else {
1926 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1927 << A->getOption().getName() << Value;
1928 }
Nico Webere3712cf2018-01-17 13:34:20 +00001929 } else if (getToolChain().getDriver().IsCLMode()) {
1930 CmdArgs.push_back("-mllvm");
1931 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001932 }
1933
1934 // Set flags to support MCU ABI.
1935 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1936 CmdArgs.push_back("-mfloat-abi");
1937 CmdArgs.push_back("soft");
1938 CmdArgs.push_back("-mstack-alignment=4");
1939 }
1940}
1941
1942void Clang::AddHexagonTargetArgs(const ArgList &Args,
1943 ArgStringList &CmdArgs) const {
1944 CmdArgs.push_back("-mqdsp6-compat");
1945 CmdArgs.push_back("-Wreturn-type");
1946
1947 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001948 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001949 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1950 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001951 }
1952
1953 if (!Args.hasArg(options::OPT_fno_short_enums))
1954 CmdArgs.push_back("-fshort-enums");
1955 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1956 CmdArgs.push_back("-mllvm");
1957 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1958 }
1959 CmdArgs.push_back("-mllvm");
1960 CmdArgs.push_back("-machine-sink-split=0");
1961}
1962
1963void Clang::AddLanaiTargetArgs(const ArgList &Args,
1964 ArgStringList &CmdArgs) const {
1965 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1966 StringRef CPUName = A->getValue();
1967
1968 CmdArgs.push_back("-target-cpu");
1969 CmdArgs.push_back(Args.MakeArgString(CPUName));
1970 }
1971 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1972 StringRef Value = A->getValue();
1973 // Only support mregparm=4 to support old usage. Report error for all other
1974 // cases.
1975 int Mregparm;
1976 if (Value.getAsInteger(10, Mregparm)) {
1977 if (Mregparm != 4) {
1978 getToolChain().getDriver().Diag(
1979 diag::err_drv_unsupported_option_argument)
1980 << A->getOption().getName() << Value;
1981 }
1982 }
1983 }
1984}
1985
1986void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1987 ArgStringList &CmdArgs) const {
1988 // Default to "hidden" visibility.
1989 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1990 options::OPT_fvisibility_ms_compat)) {
1991 CmdArgs.push_back("-fvisibility");
1992 CmdArgs.push_back("hidden");
1993 }
1994}
1995
1996void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1997 StringRef Target, const InputInfo &Output,
1998 const InputInfo &Input, const ArgList &Args) const {
1999 // If this is a dry run, do not create the compilation database file.
2000 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2001 return;
2002
2003 using llvm::yaml::escape;
2004 const Driver &D = getToolChain().getDriver();
2005
2006 if (!CompilationDatabase) {
2007 std::error_code EC;
2008 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
2009 if (EC) {
2010 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2011 << EC.message();
2012 return;
2013 }
2014 CompilationDatabase = std::move(File);
2015 }
2016 auto &CDB = *CompilationDatabase;
2017 SmallString<128> Buf;
2018 if (llvm::sys::fs::current_path(Buf))
2019 Buf = ".";
2020 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
2021 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2022 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2023 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2024 Buf = "-x";
2025 Buf += types::getTypeName(Input.getType());
2026 CDB << ", \"" << escape(Buf) << "\"";
2027 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2028 Buf = "--sysroot=";
2029 Buf += D.SysRoot;
2030 CDB << ", \"" << escape(Buf) << "\"";
2031 }
2032 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2033 for (auto &A: Args) {
2034 auto &O = A->getOption();
2035 // Skip language selection, which is positional.
2036 if (O.getID() == options::OPT_x)
2037 continue;
2038 // Skip writing dependency output and the compilation database itself.
2039 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2040 continue;
2041 // Skip inputs.
2042 if (O.getKind() == Option::InputClass)
2043 continue;
2044 // All other arguments are quoted and appended.
2045 ArgStringList ASL;
2046 A->render(Args, ASL);
2047 for (auto &it: ASL)
2048 CDB << ", \"" << escape(it) << "\"";
2049 }
2050 Buf = "--target=";
2051 Buf += Target;
2052 CDB << ", \"" << escape(Buf) << "\"]},\n";
2053}
2054
2055static void CollectArgsForIntegratedAssembler(Compilation &C,
2056 const ArgList &Args,
2057 ArgStringList &CmdArgs,
2058 const Driver &D) {
2059 if (UseRelaxAll(C, Args))
2060 CmdArgs.push_back("-mrelax-all");
2061
2062 // Only default to -mincremental-linker-compatible if we think we are
2063 // targeting the MSVC linker.
2064 bool DefaultIncrementalLinkerCompatible =
2065 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2066 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2067 options::OPT_mno_incremental_linker_compatible,
2068 DefaultIncrementalLinkerCompatible))
2069 CmdArgs.push_back("-mincremental-linker-compatible");
2070
2071 switch (C.getDefaultToolChain().getArch()) {
2072 case llvm::Triple::arm:
2073 case llvm::Triple::armeb:
2074 case llvm::Triple::thumb:
2075 case llvm::Triple::thumbeb:
2076 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2077 StringRef Value = A->getValue();
2078 if (Value == "always" || Value == "never" || Value == "arm" ||
2079 Value == "thumb") {
2080 CmdArgs.push_back("-mllvm");
2081 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2082 } else {
2083 D.Diag(diag::err_drv_unsupported_option_argument)
2084 << A->getOption().getName() << Value;
2085 }
2086 }
2087 break;
2088 default:
2089 break;
2090 }
2091
2092 // When passing -I arguments to the assembler we sometimes need to
2093 // unconditionally take the next argument. For example, when parsing
2094 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2095 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2096 // arg after parsing the '-I' arg.
2097 bool TakeNextArg = false;
2098
Petr Hosek5668d832017-11-22 01:38:31 +00002099 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
Dan Albert2715b282019-03-28 18:08:28 +00002100 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00002101 const char *MipsTargetFeature = nullptr;
2102 for (const Arg *A :
2103 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2104 A->claim();
2105
2106 for (StringRef Value : A->getValues()) {
2107 if (TakeNextArg) {
2108 CmdArgs.push_back(Value.data());
2109 TakeNextArg = false;
2110 continue;
2111 }
2112
2113 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2114 Value == "-mbig-obj")
2115 continue; // LLVM handles bigobj automatically
2116
2117 switch (C.getDefaultToolChain().getArch()) {
2118 default:
2119 break;
Peter Smith3947cb32017-11-20 13:43:55 +00002120 case llvm::Triple::thumb:
2121 case llvm::Triple::thumbeb:
2122 case llvm::Triple::arm:
2123 case llvm::Triple::armeb:
2124 if (Value == "-mthumb")
2125 // -mthumb has already been processed in ComputeLLVMTriple()
2126 // recognize but skip over here.
2127 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00002128 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00002129 case llvm::Triple::mips:
2130 case llvm::Triple::mipsel:
2131 case llvm::Triple::mips64:
2132 case llvm::Triple::mips64el:
2133 if (Value == "--trap") {
2134 CmdArgs.push_back("-target-feature");
2135 CmdArgs.push_back("+use-tcc-in-div");
2136 continue;
2137 }
2138 if (Value == "--break") {
2139 CmdArgs.push_back("-target-feature");
2140 CmdArgs.push_back("-use-tcc-in-div");
2141 continue;
2142 }
2143 if (Value.startswith("-msoft-float")) {
2144 CmdArgs.push_back("-target-feature");
2145 CmdArgs.push_back("+soft-float");
2146 continue;
2147 }
2148 if (Value.startswith("-mhard-float")) {
2149 CmdArgs.push_back("-target-feature");
2150 CmdArgs.push_back("-soft-float");
2151 continue;
2152 }
2153
2154 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2155 .Case("-mips1", "+mips1")
2156 .Case("-mips2", "+mips2")
2157 .Case("-mips3", "+mips3")
2158 .Case("-mips4", "+mips4")
2159 .Case("-mips5", "+mips5")
2160 .Case("-mips32", "+mips32")
2161 .Case("-mips32r2", "+mips32r2")
2162 .Case("-mips32r3", "+mips32r3")
2163 .Case("-mips32r5", "+mips32r5")
2164 .Case("-mips32r6", "+mips32r6")
2165 .Case("-mips64", "+mips64")
2166 .Case("-mips64r2", "+mips64r2")
2167 .Case("-mips64r3", "+mips64r3")
2168 .Case("-mips64r5", "+mips64r5")
2169 .Case("-mips64r6", "+mips64r6")
2170 .Default(nullptr);
2171 if (MipsTargetFeature)
2172 continue;
2173 }
2174
2175 if (Value == "-force_cpusubtype_ALL") {
2176 // Do nothing, this is the default and we don't support anything else.
2177 } else if (Value == "-L") {
2178 CmdArgs.push_back("-msave-temp-labels");
2179 } else if (Value == "--fatal-warnings") {
2180 CmdArgs.push_back("-massembler-fatal-warnings");
2181 } else if (Value == "--noexecstack") {
Dan Albert2715b282019-03-28 18:08:28 +00002182 UseNoExecStack = true;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002183 } else if (Value.startswith("-compress-debug-sections") ||
2184 Value.startswith("--compress-debug-sections") ||
2185 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002186 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002187 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002188 } else if (Value == "-mrelax-relocations=yes" ||
2189 Value == "--mrelax-relocations=yes") {
2190 UseRelaxRelocations = true;
2191 } else if (Value == "-mrelax-relocations=no" ||
2192 Value == "--mrelax-relocations=no") {
2193 UseRelaxRelocations = false;
2194 } else if (Value.startswith("-I")) {
2195 CmdArgs.push_back(Value.data());
2196 // We need to consume the next argument if the current arg is a plain
2197 // -I. The next arg will be the include directory.
2198 if (Value == "-I")
2199 TakeNextArg = true;
2200 } else if (Value.startswith("-gdwarf-")) {
2201 // "-gdwarf-N" options are not cc1as options.
2202 unsigned DwarfVersion = DwarfVersionNum(Value);
2203 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2204 CmdArgs.push_back(Value.data());
2205 } else {
2206 RenderDebugEnablingArgs(Args, CmdArgs,
2207 codegenoptions::LimitedDebugInfo,
2208 DwarfVersion, llvm::DebuggerKind::Default);
2209 }
2210 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2211 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2212 // Do nothing, we'll validate it later.
2213 } else if (Value == "-defsym") {
2214 if (A->getNumValues() != 2) {
2215 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2216 break;
2217 }
2218 const char *S = A->getValue(1);
2219 auto Pair = StringRef(S).split('=');
2220 auto Sym = Pair.first;
2221 auto SVal = Pair.second;
2222
2223 if (Sym.empty() || SVal.empty()) {
2224 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2225 break;
2226 }
2227 int64_t IVal;
2228 if (SVal.getAsInteger(0, IVal)) {
2229 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2230 break;
2231 }
2232 CmdArgs.push_back(Value.data());
2233 TakeNextArg = true;
Nico Weber4c9fa4a2018-12-06 18:50:39 +00002234 } else if (Value == "-fdebug-compilation-dir") {
2235 CmdArgs.push_back("-fdebug-compilation-dir");
2236 TakeNextArg = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002237 } else {
2238 D.Diag(diag::err_drv_unsupported_option_argument)
2239 << A->getOption().getName() << Value;
2240 }
2241 }
2242 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002243 if (UseRelaxRelocations)
2244 CmdArgs.push_back("--mrelax-relocations");
Dan Albert2715b282019-03-28 18:08:28 +00002245 if (UseNoExecStack)
2246 CmdArgs.push_back("-mnoexecstack");
David L. Jonesf561aba2017-03-08 01:02:16 +00002247 if (MipsTargetFeature != nullptr) {
2248 CmdArgs.push_back("-target-feature");
2249 CmdArgs.push_back(MipsTargetFeature);
2250 }
Steven Wu098742f2018-12-12 17:30:16 +00002251
2252 // forward -fembed-bitcode to assmebler
2253 if (C.getDriver().embedBitcodeEnabled() ||
2254 C.getDriver().embedBitcodeMarkerOnly())
2255 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00002256}
2257
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002258static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2259 bool OFastEnabled, const ArgList &Args,
2260 ArgStringList &CmdArgs) {
2261 // Handle various floating point optimization flags, mapping them to the
2262 // appropriate LLVM code generation flags. This is complicated by several
2263 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002264 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002265 // LLVM flags based on the final state.
2266 bool HonorINFs = true;
2267 bool HonorNaNs = true;
2268 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2269 bool MathErrno = TC.IsMathErrnoDefault();
2270 bool AssociativeMath = false;
2271 bool ReciprocalMath = false;
2272 bool SignedZeros = true;
2273 bool TrappingMath = true;
2274 StringRef DenormalFPMath = "";
2275 StringRef FPContract = "";
2276
Saleem Abdulrasool258e4f62018-09-18 21:12:39 +00002277 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2278 CmdArgs.push_back("-mlimit-float-precision");
2279 CmdArgs.push_back(A->getValue());
2280 }
2281
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002282 for (const Arg *A : Args) {
2283 switch (A->getOption().getID()) {
2284 // If this isn't an FP option skip the claim below
2285 default: continue;
2286
2287 // Options controlling individual features
2288 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2289 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2290 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2291 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2292 case options::OPT_fmath_errno: MathErrno = true; break;
2293 case options::OPT_fno_math_errno: MathErrno = false; break;
2294 case options::OPT_fassociative_math: AssociativeMath = true; break;
2295 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2296 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2297 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2298 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2299 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2300 case options::OPT_ftrapping_math: TrappingMath = true; break;
2301 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2302
2303 case options::OPT_fdenormal_fp_math_EQ:
2304 DenormalFPMath = A->getValue();
2305 break;
2306
2307 // Validate and pass through -fp-contract option.
2308 case options::OPT_ffp_contract: {
2309 StringRef Val = A->getValue();
2310 if (Val == "fast" || Val == "on" || Val == "off")
2311 FPContract = Val;
2312 else
2313 D.Diag(diag::err_drv_unsupported_option_argument)
2314 << A->getOption().getName() << Val;
2315 break;
2316 }
2317
2318 case options::OPT_ffinite_math_only:
2319 HonorINFs = false;
2320 HonorNaNs = false;
2321 break;
2322 case options::OPT_fno_finite_math_only:
2323 HonorINFs = true;
2324 HonorNaNs = true;
2325 break;
2326
2327 case options::OPT_funsafe_math_optimizations:
2328 AssociativeMath = true;
2329 ReciprocalMath = true;
2330 SignedZeros = false;
2331 TrappingMath = false;
2332 break;
2333 case options::OPT_fno_unsafe_math_optimizations:
2334 AssociativeMath = false;
2335 ReciprocalMath = false;
2336 SignedZeros = true;
2337 TrappingMath = true;
2338 // -fno_unsafe_math_optimizations restores default denormal handling
2339 DenormalFPMath = "";
2340 break;
2341
2342 case options::OPT_Ofast:
2343 // If -Ofast is the optimization level, then -ffast-math should be enabled
2344 if (!OFastEnabled)
2345 continue;
2346 LLVM_FALLTHROUGH;
2347 case options::OPT_ffast_math:
2348 HonorINFs = false;
2349 HonorNaNs = false;
2350 MathErrno = false;
2351 AssociativeMath = true;
2352 ReciprocalMath = true;
2353 SignedZeros = false;
2354 TrappingMath = false;
2355 // If fast-math is set then set the fp-contract mode to fast.
2356 FPContract = "fast";
2357 break;
2358 case options::OPT_fno_fast_math:
2359 HonorINFs = true;
2360 HonorNaNs = true;
2361 // Turning on -ffast-math (with either flag) removes the need for
2362 // MathErrno. However, turning *off* -ffast-math merely restores the
2363 // toolchain default (which may be false).
2364 MathErrno = TC.IsMathErrnoDefault();
2365 AssociativeMath = false;
2366 ReciprocalMath = false;
2367 SignedZeros = true;
2368 TrappingMath = true;
2369 // -fno_fast_math restores default denormal and fpcontract handling
2370 DenormalFPMath = "";
2371 FPContract = "";
2372 break;
2373 }
2374
2375 // If we handled this option claim it
2376 A->claim();
2377 }
2378
2379 if (!HonorINFs)
2380 CmdArgs.push_back("-menable-no-infs");
2381
2382 if (!HonorNaNs)
2383 CmdArgs.push_back("-menable-no-nans");
2384
2385 if (MathErrno)
2386 CmdArgs.push_back("-fmath-errno");
2387
2388 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2389 !TrappingMath)
2390 CmdArgs.push_back("-menable-unsafe-fp-math");
2391
2392 if (!SignedZeros)
2393 CmdArgs.push_back("-fno-signed-zeros");
2394
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002395 if (AssociativeMath && !SignedZeros && !TrappingMath)
2396 CmdArgs.push_back("-mreassociate");
2397
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002398 if (ReciprocalMath)
2399 CmdArgs.push_back("-freciprocal-math");
2400
2401 if (!TrappingMath)
2402 CmdArgs.push_back("-fno-trapping-math");
2403
2404 if (!DenormalFPMath.empty())
2405 CmdArgs.push_back(
2406 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2407
2408 if (!FPContract.empty())
2409 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2410
2411 ParseMRecip(D, Args, CmdArgs);
2412
2413 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2414 // individual features enabled by -ffast-math instead of the option itself as
2415 // that's consistent with gcc's behaviour.
2416 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2417 ReciprocalMath && !SignedZeros && !TrappingMath)
2418 CmdArgs.push_back("-ffast-math");
2419
2420 // Handle __FINITE_MATH_ONLY__ similarly.
2421 if (!HonorINFs && !HonorNaNs)
2422 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002423
2424 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2425 CmdArgs.push_back("-mfpmath");
2426 CmdArgs.push_back(A->getValue());
2427 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002428
2429 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002430 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2431 options::OPT_fstrict_float_cast_overflow, false))
2432 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002433}
2434
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002435static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2436 const llvm::Triple &Triple,
2437 const InputInfo &Input) {
2438 // Enable region store model by default.
2439 CmdArgs.push_back("-analyzer-store=region");
2440
2441 // Treat blocks as analysis entry points.
2442 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2443
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002444 // Add default argument set.
2445 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2446 CmdArgs.push_back("-analyzer-checker=core");
2447 CmdArgs.push_back("-analyzer-checker=apiModeling");
2448
2449 if (!Triple.isWindowsMSVCEnvironment()) {
2450 CmdArgs.push_back("-analyzer-checker=unix");
2451 } else {
2452 // Enable "unix" checkers that also work on Windows.
2453 CmdArgs.push_back("-analyzer-checker=unix.API");
2454 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2455 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2456 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2457 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2458 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2459 }
2460
2461 // Disable some unix checkers for PS4.
2462 if (Triple.isPS4CPU()) {
2463 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2464 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2465 }
2466
2467 if (Triple.isOSDarwin())
2468 CmdArgs.push_back("-analyzer-checker=osx");
2469
2470 CmdArgs.push_back("-analyzer-checker=deadcode");
2471
2472 if (types::isCXX(Input.getType()))
2473 CmdArgs.push_back("-analyzer-checker=cplusplus");
2474
2475 if (!Triple.isPS4CPU()) {
2476 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2477 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2478 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2479 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2480 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2481 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2482 }
2483
2484 // Default nullability checks.
2485 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2486 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2487 }
2488
2489 // Set the output format. The default is plist, for (lame) historical reasons.
2490 CmdArgs.push_back("-analyzer-output");
2491 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2492 CmdArgs.push_back(A->getValue());
2493 else
2494 CmdArgs.push_back("plist");
2495
2496 // Disable the presentation of standard compiler warnings when using
2497 // --analyze. We only want to show static analyzer diagnostics or frontend
2498 // errors.
2499 CmdArgs.push_back("-w");
2500
2501 // Add -Xanalyzer arguments when running as analyzer.
2502 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2503}
2504
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002505static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002506 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002507 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2508
2509 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2510 // doesn't even have a stack!
2511 if (EffectiveTriple.isNVPTX())
2512 return;
2513
2514 // -stack-protector=0 is default.
2515 unsigned StackProtectorLevel = 0;
2516 unsigned DefaultStackProtectorLevel =
2517 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2518
2519 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2520 options::OPT_fstack_protector_all,
2521 options::OPT_fstack_protector_strong,
2522 options::OPT_fstack_protector)) {
2523 if (A->getOption().matches(options::OPT_fstack_protector))
2524 StackProtectorLevel =
2525 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2526 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2527 StackProtectorLevel = LangOptions::SSPStrong;
2528 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2529 StackProtectorLevel = LangOptions::SSPReq;
2530 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002531 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002532 }
2533
2534 if (StackProtectorLevel) {
2535 CmdArgs.push_back("-stack-protector");
2536 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2537 }
2538
2539 // --param ssp-buffer-size=
2540 for (const Arg *A : Args.filtered(options::OPT__param)) {
2541 StringRef Str(A->getValue());
2542 if (Str.startswith("ssp-buffer-size=")) {
2543 if (StackProtectorLevel) {
2544 CmdArgs.push_back("-stack-protector-buffer-size");
2545 // FIXME: Verify the argument is a valid integer.
2546 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2547 }
2548 A->claim();
2549 }
2550 }
2551}
2552
JF Bastien14daa202018-12-18 05:12:21 +00002553static void RenderTrivialAutoVarInitOptions(const Driver &D,
2554 const ToolChain &TC,
2555 const ArgList &Args,
2556 ArgStringList &CmdArgs) {
2557 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2558 StringRef TrivialAutoVarInit = "";
2559
2560 for (const Arg *A : Args) {
2561 switch (A->getOption().getID()) {
2562 default:
2563 continue;
2564 case options::OPT_ftrivial_auto_var_init: {
2565 A->claim();
2566 StringRef Val = A->getValue();
2567 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2568 TrivialAutoVarInit = Val;
2569 else
2570 D.Diag(diag::err_drv_unsupported_option_argument)
2571 << A->getOption().getName() << Val;
2572 break;
2573 }
2574 }
2575 }
2576
2577 if (TrivialAutoVarInit.empty())
2578 switch (DefaultTrivialAutoVarInit) {
2579 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2580 break;
2581 case LangOptions::TrivialAutoVarInitKind::Pattern:
2582 TrivialAutoVarInit = "pattern";
2583 break;
2584 case LangOptions::TrivialAutoVarInitKind::Zero:
2585 TrivialAutoVarInit = "zero";
2586 break;
2587 }
2588
2589 if (!TrivialAutoVarInit.empty()) {
2590 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2591 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2592 CmdArgs.push_back(
2593 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2594 }
2595}
2596
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002597static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2598 const unsigned ForwardedArguments[] = {
2599 options::OPT_cl_opt_disable,
2600 options::OPT_cl_strict_aliasing,
2601 options::OPT_cl_single_precision_constant,
2602 options::OPT_cl_finite_math_only,
2603 options::OPT_cl_kernel_arg_info,
2604 options::OPT_cl_unsafe_math_optimizations,
2605 options::OPT_cl_fast_relaxed_math,
2606 options::OPT_cl_mad_enable,
2607 options::OPT_cl_no_signed_zeros,
2608 options::OPT_cl_denorms_are_zero,
2609 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002610 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002611 };
2612
2613 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2614 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2615 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2616 }
2617
2618 for (const auto &Arg : ForwardedArguments)
2619 if (const auto *A = Args.getLastArg(Arg))
2620 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2621}
2622
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002623static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2624 ArgStringList &CmdArgs) {
2625 bool ARCMTEnabled = false;
2626 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2627 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2628 options::OPT_ccc_arcmt_modify,
2629 options::OPT_ccc_arcmt_migrate)) {
2630 ARCMTEnabled = true;
2631 switch (A->getOption().getID()) {
2632 default: llvm_unreachable("missed a case");
2633 case options::OPT_ccc_arcmt_check:
2634 CmdArgs.push_back("-arcmt-check");
2635 break;
2636 case options::OPT_ccc_arcmt_modify:
2637 CmdArgs.push_back("-arcmt-modify");
2638 break;
2639 case options::OPT_ccc_arcmt_migrate:
2640 CmdArgs.push_back("-arcmt-migrate");
2641 CmdArgs.push_back("-mt-migrate-directory");
2642 CmdArgs.push_back(A->getValue());
2643
2644 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2645 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2646 break;
2647 }
2648 }
2649 } else {
2650 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2651 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2652 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2653 }
2654
2655 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2656 if (ARCMTEnabled)
2657 D.Diag(diag::err_drv_argument_not_allowed_with)
2658 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2659
2660 CmdArgs.push_back("-mt-migrate-directory");
2661 CmdArgs.push_back(A->getValue());
2662
2663 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2664 options::OPT_objcmt_migrate_subscripting,
2665 options::OPT_objcmt_migrate_property)) {
2666 // None specified, means enable them all.
2667 CmdArgs.push_back("-objcmt-migrate-literals");
2668 CmdArgs.push_back("-objcmt-migrate-subscripting");
2669 CmdArgs.push_back("-objcmt-migrate-property");
2670 } else {
2671 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2672 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2673 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2674 }
2675 } else {
2676 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2677 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2678 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2679 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2680 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2681 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2682 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2683 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2684 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2685 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2686 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2687 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2688 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2689 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2690 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2691 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2692 }
2693}
2694
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002695static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2696 const ArgList &Args, ArgStringList &CmdArgs) {
2697 // -fbuiltin is default unless -mkernel is used.
2698 bool UseBuiltins =
2699 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2700 !Args.hasArg(options::OPT_mkernel));
2701 if (!UseBuiltins)
2702 CmdArgs.push_back("-fno-builtin");
2703
2704 // -ffreestanding implies -fno-builtin.
2705 if (Args.hasArg(options::OPT_ffreestanding))
2706 UseBuiltins = false;
2707
2708 // Process the -fno-builtin-* options.
2709 for (const auto &Arg : Args) {
2710 const Option &O = Arg->getOption();
2711 if (!O.matches(options::OPT_fno_builtin_))
2712 continue;
2713
2714 Arg->claim();
2715
2716 // If -fno-builtin is specified, then there's no need to pass the option to
2717 // the frontend.
2718 if (!UseBuiltins)
2719 continue;
2720
2721 StringRef FuncName = Arg->getValue();
2722 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2723 }
2724
2725 // le32-specific flags:
2726 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2727 // by default.
2728 if (TC.getArch() == llvm::Triple::le32)
2729 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002730}
2731
Adrian Prantl70599032018-02-09 18:43:10 +00002732void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2733 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2734 llvm::sys::path::append(Result, "org.llvm.clang.");
2735 appendUserToPath(Result);
2736 llvm::sys::path::append(Result, "ModuleCache");
2737}
2738
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002739static void RenderModulesOptions(Compilation &C, const Driver &D,
2740 const ArgList &Args, const InputInfo &Input,
2741 const InputInfo &Output,
2742 ArgStringList &CmdArgs, bool &HaveModules) {
2743 // -fmodules enables the use of precompiled modules (off by default).
2744 // Users can pass -fno-cxx-modules to turn off modules support for
2745 // C++/Objective-C++ programs.
2746 bool HaveClangModules = false;
2747 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2748 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2749 options::OPT_fno_cxx_modules, true);
2750 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2751 CmdArgs.push_back("-fmodules");
2752 HaveClangModules = true;
2753 }
2754 }
2755
Richard Smithb1b580e2019-04-14 11:11:37 +00002756 HaveModules |= HaveClangModules;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002757 if (Args.hasArg(options::OPT_fmodules_ts)) {
2758 CmdArgs.push_back("-fmodules-ts");
2759 HaveModules = true;
2760 }
2761
2762 // -fmodule-maps enables implicit reading of module map files. By default,
2763 // this is enabled if we are using Clang's flavor of precompiled modules.
2764 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2765 options::OPT_fno_implicit_module_maps, HaveClangModules))
2766 CmdArgs.push_back("-fimplicit-module-maps");
2767
2768 // -fmodules-decluse checks that modules used are declared so (off by default)
2769 if (Args.hasFlag(options::OPT_fmodules_decluse,
2770 options::OPT_fno_modules_decluse, false))
2771 CmdArgs.push_back("-fmodules-decluse");
2772
2773 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2774 // all #included headers are part of modules.
2775 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2776 options::OPT_fno_modules_strict_decluse, false))
2777 CmdArgs.push_back("-fmodules-strict-decluse");
2778
2779 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002780 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002781 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2782 options::OPT_fno_implicit_modules, HaveClangModules)) {
2783 if (HaveModules)
2784 CmdArgs.push_back("-fno-implicit-modules");
2785 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002786 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002787 // -fmodule-cache-path specifies where our implicitly-built module files
2788 // should be written.
2789 SmallString<128> Path;
2790 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2791 Path = A->getValue();
2792
2793 if (C.isForDiagnostics()) {
2794 // When generating crash reports, we want to emit the modules along with
2795 // the reproduction sources, so we ignore any provided module path.
2796 Path = Output.getFilename();
2797 llvm::sys::path::replace_extension(Path, ".cache");
2798 llvm::sys::path::append(Path, "modules");
2799 } else if (Path.empty()) {
2800 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002801 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002802 }
2803
2804 const char Arg[] = "-fmodules-cache-path=";
2805 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2806 CmdArgs.push_back(Args.MakeArgString(Path));
2807 }
2808
2809 if (HaveModules) {
2810 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2811 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2812 CmdArgs.push_back(Args.MakeArgString(
2813 std::string("-fprebuilt-module-path=") + A->getValue()));
2814 A->claim();
2815 }
2816 }
2817
2818 // -fmodule-name specifies the module that is currently being built (or
2819 // used for header checking by -fmodule-maps).
2820 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2821
2822 // -fmodule-map-file can be used to specify files containing module
2823 // definitions.
2824 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2825
2826 // -fbuiltin-module-map can be used to load the clang
2827 // builtin headers modulemap file.
2828 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2829 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2830 llvm::sys::path::append(BuiltinModuleMap, "include");
2831 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2832 if (llvm::sys::fs::exists(BuiltinModuleMap))
2833 CmdArgs.push_back(
2834 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2835 }
2836
2837 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2838 // names to precompiled module files (the module is loaded only if used).
2839 // The -fmodule-file=<file> form can be used to unconditionally load
2840 // precompiled module files (whether used or not).
2841 if (HaveModules)
2842 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2843 else
2844 Args.ClaimAllArgs(options::OPT_fmodule_file);
2845
2846 // When building modules and generating crashdumps, we need to dump a module
2847 // dependency VFS alongside the output.
2848 if (HaveClangModules && C.isForDiagnostics()) {
2849 SmallString<128> VFSDir(Output.getFilename());
2850 llvm::sys::path::replace_extension(VFSDir, ".cache");
2851 // Add the cache directory as a temp so the crash diagnostics pick it up.
2852 C.addTempFile(Args.MakeArgString(VFSDir));
2853
2854 llvm::sys::path::append(VFSDir, "vfs");
2855 CmdArgs.push_back("-module-dependency-dir");
2856 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2857 }
2858
2859 if (HaveClangModules)
2860 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2861
2862 // Pass through all -fmodules-ignore-macro arguments.
2863 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2864 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2865 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2866
2867 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2868
2869 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2870 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2871 D.Diag(diag::err_drv_argument_not_allowed_with)
2872 << A->getAsString(Args) << "-fbuild-session-timestamp";
2873
2874 llvm::sys::fs::file_status Status;
2875 if (llvm::sys::fs::status(A->getValue(), Status))
2876 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2877 CmdArgs.push_back(
2878 Args.MakeArgString("-fbuild-session-timestamp=" +
2879 Twine((uint64_t)Status.getLastModificationTime()
2880 .time_since_epoch()
2881 .count())));
2882 }
2883
2884 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2885 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2886 options::OPT_fbuild_session_file))
2887 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2888
2889 Args.AddLastArg(CmdArgs,
2890 options::OPT_fmodules_validate_once_per_build_session);
2891 }
2892
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002893 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2894 options::OPT_fno_modules_validate_system_headers,
2895 ImplicitModules))
2896 CmdArgs.push_back("-fmodules-validate-system-headers");
2897
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002898 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2899}
2900
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002901static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2902 ArgStringList &CmdArgs) {
2903 // -fsigned-char is default.
2904 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2905 options::OPT_fno_signed_char,
2906 options::OPT_funsigned_char,
2907 options::OPT_fno_unsigned_char)) {
2908 if (A->getOption().matches(options::OPT_funsigned_char) ||
2909 A->getOption().matches(options::OPT_fno_signed_char)) {
2910 CmdArgs.push_back("-fno-signed-char");
2911 }
2912 } else if (!isSignedCharDefault(T)) {
2913 CmdArgs.push_back("-fno-signed-char");
2914 }
2915
Richard Smith28ddb912018-11-14 21:04:34 +00002916 // The default depends on the language standard.
2917 if (const Arg *A =
2918 Args.getLastArg(options::OPT_fchar8__t, options::OPT_fno_char8__t))
2919 A->render(Args, CmdArgs);
Richard Smith3a8244d2018-05-01 05:02:45 +00002920
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002921 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2922 options::OPT_fno_short_wchar)) {
2923 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2924 CmdArgs.push_back("-fwchar-type=short");
2925 CmdArgs.push_back("-fno-signed-wchar");
2926 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002927 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002928 CmdArgs.push_back("-fwchar-type=int");
Michal Gorny5a409d02018-12-20 13:09:30 +00002929 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2930 T.isOSOpenBSD()))
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002931 CmdArgs.push_back("-fno-signed-wchar");
2932 else
2933 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002934 }
2935 }
2936}
2937
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002938static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2939 const llvm::Triple &T, const ArgList &Args,
2940 ObjCRuntime &Runtime, bool InferCovariantReturns,
2941 const InputInfo &Input, ArgStringList &CmdArgs) {
2942 const llvm::Triple::ArchType Arch = TC.getArch();
2943
2944 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2945 // is the default. Except for deployment target of 10.5, next runtime is
2946 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2947 if (Runtime.isNonFragile()) {
2948 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2949 options::OPT_fno_objc_legacy_dispatch,
2950 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2951 if (TC.UseObjCMixedDispatch())
2952 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2953 else
2954 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2955 }
2956 }
2957
2958 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2959 // to do Array/Dictionary subscripting by default.
2960 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002961 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2962 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2963
2964 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2965 // NOTE: This logic is duplicated in ToolChains.cpp.
2966 if (isObjCAutoRefCount(Args)) {
2967 TC.CheckObjCARC();
2968
2969 CmdArgs.push_back("-fobjc-arc");
2970
2971 // FIXME: It seems like this entire block, and several around it should be
2972 // wrapped in isObjC, but for now we just use it here as this is where it
2973 // was being used previously.
2974 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2975 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2976 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2977 else
2978 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2979 }
2980
2981 // Allow the user to enable full exceptions code emission.
2982 // We default off for Objective-C, on for Objective-C++.
2983 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2984 options::OPT_fno_objc_arc_exceptions,
2985 /*default=*/types::isCXX(Input.getType())))
2986 CmdArgs.push_back("-fobjc-arc-exceptions");
2987 }
2988
2989 // Silence warning for full exception code emission options when explicitly
2990 // set to use no ARC.
2991 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2992 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2993 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2994 }
2995
Pete Coopere3886802018-12-08 05:13:50 +00002996 // Allow the user to control whether messages can be converted to runtime
2997 // functions.
2998 if (types::isObjC(Input.getType())) {
2999 auto *Arg = Args.getLastArg(
3000 options::OPT_fobjc_convert_messages_to_runtime_calls,
3001 options::OPT_fno_objc_convert_messages_to_runtime_calls);
3002 if (Arg &&
3003 Arg->getOption().matches(
3004 options::OPT_fno_objc_convert_messages_to_runtime_calls))
3005 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3006 }
3007
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00003008 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3009 // rewriter.
3010 if (InferCovariantReturns)
3011 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3012
3013 // Pass down -fobjc-weak or -fno-objc-weak if present.
3014 if (types::isObjC(Input.getType())) {
3015 auto WeakArg =
3016 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3017 if (!WeakArg) {
3018 // nothing to do
3019 } else if (!Runtime.allowsWeak()) {
3020 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3021 D.Diag(diag::err_objc_weak_unsupported);
3022 } else {
3023 WeakArg->render(Args, CmdArgs);
3024 }
3025 }
3026}
3027
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00003028static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3029 ArgStringList &CmdArgs) {
3030 bool CaretDefault = true;
3031 bool ColumnDefault = true;
3032
3033 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3034 options::OPT__SLASH_diagnostics_column,
3035 options::OPT__SLASH_diagnostics_caret)) {
3036 switch (A->getOption().getID()) {
3037 case options::OPT__SLASH_diagnostics_caret:
3038 CaretDefault = true;
3039 ColumnDefault = true;
3040 break;
3041 case options::OPT__SLASH_diagnostics_column:
3042 CaretDefault = false;
3043 ColumnDefault = true;
3044 break;
3045 case options::OPT__SLASH_diagnostics_classic:
3046 CaretDefault = false;
3047 ColumnDefault = false;
3048 break;
3049 }
3050 }
3051
3052 // -fcaret-diagnostics is default.
3053 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3054 options::OPT_fno_caret_diagnostics, CaretDefault))
3055 CmdArgs.push_back("-fno-caret-diagnostics");
3056
3057 // -fdiagnostics-fixit-info is default, only pass non-default.
3058 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3059 options::OPT_fno_diagnostics_fixit_info))
3060 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3061
3062 // Enable -fdiagnostics-show-option by default.
3063 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3064 options::OPT_fno_diagnostics_show_option))
3065 CmdArgs.push_back("-fdiagnostics-show-option");
3066
3067 if (const Arg *A =
3068 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3069 CmdArgs.push_back("-fdiagnostics-show-category");
3070 CmdArgs.push_back(A->getValue());
3071 }
3072
3073 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3074 options::OPT_fno_diagnostics_show_hotness, false))
3075 CmdArgs.push_back("-fdiagnostics-show-hotness");
3076
3077 if (const Arg *A =
3078 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3079 std::string Opt =
3080 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3081 CmdArgs.push_back(Args.MakeArgString(Opt));
3082 }
3083
3084 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3085 CmdArgs.push_back("-fdiagnostics-format");
3086 CmdArgs.push_back(A->getValue());
3087 }
3088
3089 if (const Arg *A = Args.getLastArg(
3090 options::OPT_fdiagnostics_show_note_include_stack,
3091 options::OPT_fno_diagnostics_show_note_include_stack)) {
3092 const Option &O = A->getOption();
3093 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3094 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3095 else
3096 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3097 }
3098
3099 // Color diagnostics are parsed by the driver directly from argv and later
3100 // re-parsed to construct this job; claim any possible color diagnostic here
3101 // to avoid warn_drv_unused_argument and diagnose bad
3102 // OPT_fdiagnostics_color_EQ values.
3103 for (const Arg *A : Args) {
3104 const Option &O = A->getOption();
3105 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3106 !O.matches(options::OPT_fdiagnostics_color) &&
3107 !O.matches(options::OPT_fno_color_diagnostics) &&
3108 !O.matches(options::OPT_fno_diagnostics_color) &&
3109 !O.matches(options::OPT_fdiagnostics_color_EQ))
3110 continue;
3111
3112 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3113 StringRef Value(A->getValue());
3114 if (Value != "always" && Value != "never" && Value != "auto")
3115 D.Diag(diag::err_drv_clang_unsupported)
3116 << ("-fdiagnostics-color=" + Value).str();
3117 }
3118 A->claim();
3119 }
3120
3121 if (D.getDiags().getDiagnosticOptions().ShowColors)
3122 CmdArgs.push_back("-fcolor-diagnostics");
3123
3124 if (Args.hasArg(options::OPT_fansi_escape_codes))
3125 CmdArgs.push_back("-fansi-escape-codes");
3126
3127 if (!Args.hasFlag(options::OPT_fshow_source_location,
3128 options::OPT_fno_show_source_location))
3129 CmdArgs.push_back("-fno-show-source-location");
3130
3131 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3132 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3133
3134 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3135 ColumnDefault))
3136 CmdArgs.push_back("-fno-show-column");
3137
3138 if (!Args.hasFlag(options::OPT_fspell_checking,
3139 options::OPT_fno_spell_checking))
3140 CmdArgs.push_back("-fno-spell-checking");
3141}
3142
George Rimar91829ee2018-11-14 09:22:16 +00003143enum class DwarfFissionKind { None, Split, Single };
3144
3145static DwarfFissionKind getDebugFissionKind(const Driver &D,
3146 const ArgList &Args, Arg *&Arg) {
3147 Arg =
3148 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3149 if (!Arg)
3150 return DwarfFissionKind::None;
3151
3152 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3153 return DwarfFissionKind::Split;
3154
3155 StringRef Value = Arg->getValue();
3156 if (Value == "split")
3157 return DwarfFissionKind::Split;
3158 if (Value == "single")
3159 return DwarfFissionKind::Single;
3160
3161 D.Diag(diag::err_drv_unsupported_option_argument)
3162 << Arg->getOption().getName() << Arg->getValue();
3163 return DwarfFissionKind::None;
3164}
3165
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003166static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3167 const llvm::Triple &T, const ArgList &Args,
3168 bool EmitCodeView, bool IsWindowsMSVC,
3169 ArgStringList &CmdArgs,
3170 codegenoptions::DebugInfoKind &DebugInfoKind,
George Rimar91829ee2018-11-14 09:22:16 +00003171 DwarfFissionKind &DwarfFission) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003172 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003173 options::OPT_fno_debug_info_for_profiling, false) &&
3174 checkDebugInfoOption(
3175 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003176 CmdArgs.push_back("-fdebug-info-for-profiling");
3177
3178 // The 'g' groups options involve a somewhat intricate sequence of decisions
3179 // about what to pass from the driver to the frontend, but by the time they
3180 // reach cc1 they've been factored into three well-defined orthogonal choices:
3181 // * what level of debug info to generate
3182 // * what dwarf version to write
3183 // * what debugger tuning to use
3184 // This avoids having to monkey around further in cc1 other than to disable
3185 // codeview if not running in a Windows environment. Perhaps even that
3186 // decision should be made in the driver as well though.
3187 unsigned DWARFVersion = 0;
3188 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3189
3190 bool SplitDWARFInlining =
3191 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3192 options::OPT_fno_split_dwarf_inlining, true);
3193
3194 Args.ClaimAllArgs(options::OPT_g_Group);
3195
George Rimar91829ee2018-11-14 09:22:16 +00003196 Arg* SplitDWARFArg;
3197 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003198
George Rimar91829ee2018-11-14 09:22:16 +00003199 if (DwarfFission != DwarfFissionKind::None &&
3200 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3201 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003202 SplitDWARFInlining = false;
3203 }
3204
Fangrui Songe3576b02019-04-17 01:46:27 +00003205 if (const Arg *A =
3206 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3207 options::OPT_gsplit_dwarf_EQ)) {
3208 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3209
3210 // If the last option explicitly specified a debug-info level, use it.
3211 if (checkDebugInfoOption(A, Args, D, TC) &&
3212 A->getOption().matches(options::OPT_gN_Group)) {
3213 DebugInfoKind = DebugLevelToInfoKind(*A);
3214 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3215 // complicated if you've disabled inline info in the skeleton CUs
3216 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3217 // line-tables-only, so let those compose naturally in that case.
3218 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3219 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3220 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3221 SplitDWARFInlining))
3222 DwarfFission = DwarfFissionKind::None;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003223 }
3224 }
3225
3226 // If a debugger tuning argument appeared, remember it.
3227 if (const Arg *A =
3228 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003229 if (checkDebugInfoOption(A, Args, D, TC)) {
3230 if (A->getOption().matches(options::OPT_glldb))
3231 DebuggerTuning = llvm::DebuggerKind::LLDB;
3232 else if (A->getOption().matches(options::OPT_gsce))
3233 DebuggerTuning = llvm::DebuggerKind::SCE;
3234 else
3235 DebuggerTuning = llvm::DebuggerKind::GDB;
3236 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003237 }
3238
3239 // If a -gdwarf argument appeared, remember it.
3240 if (const Arg *A =
3241 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3242 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003243 if (checkDebugInfoOption(A, Args, D, TC))
3244 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003245
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003246 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3247 if (checkDebugInfoOption(A, Args, D, TC))
3248 EmitCodeView = true;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003249 }
3250
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003251 // If the user asked for debug info but did not explicitly specify -gcodeview
3252 // or -gdwarf, ask the toolchain for the default format.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003253 if (!EmitCodeView && DWARFVersion == 0 &&
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003254 DebugInfoKind != codegenoptions::NoDebugInfo) {
3255 switch (TC.getDefaultDebugFormat()) {
3256 case codegenoptions::DIF_CodeView:
3257 EmitCodeView = true;
3258 break;
3259 case codegenoptions::DIF_DWARF:
3260 DWARFVersion = TC.GetDefaultDwarfVersion();
3261 break;
3262 }
3263 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003264
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003265 // -gline-directives-only supported only for the DWARF debug info.
3266 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3267 DebugInfoKind = codegenoptions::NoDebugInfo;
3268
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003269 // We ignore flag -gstrict-dwarf for now.
3270 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3271 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3272
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003273 // Column info is included by default for everything except SCE and
3274 // CodeView. Clang doesn't track end columns, just starting columns, which,
3275 // in theory, is fine for CodeView (and PDB). In practice, however, the
3276 // Microsoft debuggers don't handle missing end columns well, so it's better
3277 // not to include any column info.
3278 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3279 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003280 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003281 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003282 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003283 CmdArgs.push_back("-dwarf-column-info");
3284
3285 // FIXME: Move backend command line options to the module.
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003286 // If -gline-tables-only or -gline-directives-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003287 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3288 if (checkDebugInfoOption(A, Args, D, TC)) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003289 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3290 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003291 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3292 CmdArgs.push_back("-dwarf-ext-refs");
3293 CmdArgs.push_back("-fmodule-format=obj");
3294 }
3295 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003296
Fangrui Songe3576b02019-04-17 01:46:27 +00003297 // -gsplit-dwarf enables the backend dwarf splitting and extraction.
Fangrui Songee957e02019-03-28 08:24:00 +00003298 if (T.isOSBinFormatELF()) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003299 if (!SplitDWARFInlining)
3300 CmdArgs.push_back("-fno-split-dwarf-inlining");
3301
George Rimar91829ee2018-11-14 09:22:16 +00003302 if (DwarfFission != DwarfFissionKind::None) {
George Rimar91829ee2018-11-14 09:22:16 +00003303 if (DwarfFission == DwarfFissionKind::Single)
3304 CmdArgs.push_back("-enable-split-dwarf=single");
3305 else
3306 CmdArgs.push_back("-enable-split-dwarf");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003307 }
3308 }
3309
3310 // After we've dealt with all combinations of things that could
3311 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3312 // figure out if we need to "upgrade" it to standalone debug info.
3313 // We parse these two '-f' options whether or not they will be used,
3314 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
David Blaikieb068f922019-04-16 00:16:29 +00003315 bool NeedFullDebug = Args.hasFlag(
3316 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3317 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3318 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003319 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3320 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003321 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3322 DebugInfoKind = codegenoptions::FullDebugInfo;
3323
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003324 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3325 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003326 // Source embedding is a vendor extension to DWARF v5. By now we have
3327 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003328 // fallen back to the target default, so if this is still not at least 5
3329 // we emit an error.
3330 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003331 if (DWARFVersion < 5)
3332 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003333 << A->getAsString(Args) << "-gdwarf-5";
3334 else if (checkDebugInfoOption(A, Args, D, TC))
3335 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003336 }
3337
Reid Kleckner75557712018-11-16 18:47:41 +00003338 if (EmitCodeView) {
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003339 CmdArgs.push_back("-gcodeview");
3340
Reid Kleckner75557712018-11-16 18:47:41 +00003341 // Emit codeview type hashes if requested.
3342 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3343 options::OPT_gno_codeview_ghash, false)) {
3344 CmdArgs.push_back("-gcodeview-ghash");
3345 }
3346 }
3347
Alexey Bataevc92fc3c2018-12-12 14:52:27 +00003348 // Adjust the debug info kind for the given toolchain.
3349 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3350
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003351 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3352 DebuggerTuning);
3353
3354 // -fdebug-macro turns on macro debug info generation.
3355 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3356 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003357 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3358 D, TC))
3359 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003360
3361 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003362 const auto *PubnamesArg =
3363 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3364 options::OPT_gpubnames, options::OPT_gno_pubnames);
George Rimar91829ee2018-11-14 09:22:16 +00003365 if (DwarfFission != DwarfFissionKind::None ||
3366 DebuggerTuning == llvm::DebuggerKind::LLDB ||
David Blaikie65864522018-08-20 20:14:08 +00003367 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3368 if (!PubnamesArg ||
3369 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3370 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3371 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3372 options::OPT_gpubnames)
3373 ? "-gpubnames"
3374 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003375
David Blaikie27692de2018-11-13 20:08:13 +00003376 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3377 options::OPT_fno_debug_ranges_base_address, false)) {
3378 CmdArgs.push_back("-fdebug-ranges-base-address");
3379 }
3380
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003381 // -gdwarf-aranges turns on the emission of the aranges section in the
3382 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003383 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003384 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3385 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3386 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3387 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003388 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003389 CmdArgs.push_back("-generate-arange-section");
3390 }
3391
3392 if (Args.hasFlag(options::OPT_fdebug_types_section,
3393 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003394 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003395 D.Diag(diag::err_drv_unsupported_opt_for_target)
3396 << Args.getLastArg(options::OPT_fdebug_types_section)
3397 ->getAsString(Args)
3398 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003399 } else if (checkDebugInfoOption(
3400 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3401 TC)) {
3402 CmdArgs.push_back("-mllvm");
3403 CmdArgs.push_back("-generate-type-units");
3404 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003405 }
3406
Paul Robinson1787f812017-09-28 18:37:02 +00003407 // Decide how to render forward declarations of template instantiations.
3408 // SCE wants full descriptions, others just get them in the name.
3409 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3410 CmdArgs.push_back("-debug-forward-template-params");
3411
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003412 // Do we need to explicitly import anonymous namespaces into the parent
3413 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003414 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3415 CmdArgs.push_back("-dwarf-explicit-import");
3416
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003417 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003418}
3419
David L. Jonesf561aba2017-03-08 01:02:16 +00003420void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3421 const InputInfo &Output, const InputInfoList &Inputs,
3422 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003423 const auto &TC = getToolChain();
3424 const llvm::Triple &RawTriple = TC.getTriple();
3425 const llvm::Triple &Triple = TC.getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003426 const std::string &TripleStr = Triple.getTriple();
3427
3428 bool KernelOrKext =
3429 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003430 const Driver &D = TC.getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00003431 ArgStringList CmdArgs;
3432
3433 // Check number of inputs for sanity. We need at least one input.
3434 assert(Inputs.size() >= 1 && "Must have at least one input.");
Yaxun Liu398612b2018-05-08 21:02:12 +00003435 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003436 // device-side compilations). OpenMP device jobs also take the host IR as a
Richard Smithcd35eff2018-09-15 01:21:16 +00003437 // second input. Module precompilation accepts a list of header files to
3438 // include as part of the module. All other jobs are expected to have exactly
3439 // one input.
David L. Jonesf561aba2017-03-08 01:02:16 +00003440 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003441 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003442 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Richard Smithcd35eff2018-09-15 01:21:16 +00003443 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3444
3445 // A header module compilation doesn't have a main input file, so invent a
3446 // fake one as a placeholder.
Richard Smithcd35eff2018-09-15 01:21:16 +00003447 const char *ModuleName = [&]{
3448 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3449 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3450 }();
Benjamin Kramer5904c412018-11-05 12:46:02 +00003451 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
Richard Smithcd35eff2018-09-15 01:21:16 +00003452
3453 const InputInfo &Input =
3454 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3455
3456 InputInfoList ModuleHeaderInputs;
3457 const InputInfo *CudaDeviceInput = nullptr;
3458 const InputInfo *OpenMPDeviceInput = nullptr;
3459 for (const InputInfo &I : Inputs) {
3460 if (&I == &Input) {
3461 // This is the primary input.
Benjamin Kramer5904c412018-11-05 12:46:02 +00003462 } else if (IsHeaderModulePrecompile &&
Richard Smithcd35eff2018-09-15 01:21:16 +00003463 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
Benjamin Kramer5904c412018-11-05 12:46:02 +00003464 types::ID Expected = HeaderModuleInput.getType();
Richard Smithcd35eff2018-09-15 01:21:16 +00003465 if (I.getType() != Expected) {
3466 D.Diag(diag::err_drv_module_header_wrong_kind)
3467 << I.getFilename() << types::getTypeName(I.getType())
3468 << types::getTypeName(Expected);
3469 }
3470 ModuleHeaderInputs.push_back(I);
3471 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3472 CudaDeviceInput = &I;
3473 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3474 OpenMPDeviceInput = &I;
3475 } else {
3476 llvm_unreachable("unexpectedly given multiple inputs");
3477 }
3478 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003479
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003480 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003481 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3482 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3483 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003484 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003485
Yaxun Liu398612b2018-05-08 21:02:12 +00003486 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3487 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3488 // Windows), we need to pass Windows-specific flags to cc1.
3489 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003490 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3491 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3492 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3493 }
3494
3495 // C++ is not supported for IAMCU.
3496 if (IsIAMCU && types::isCXX(Input.getType()))
3497 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3498
3499 // Invoke ourselves in -cc1 mode.
3500 //
3501 // FIXME: Implement custom jobs for internal actions.
3502 CmdArgs.push_back("-cc1");
3503
3504 // Add the "effective" target triple.
3505 CmdArgs.push_back("-triple");
3506 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3507
3508 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3509 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3510 Args.ClaimAllArgs(options::OPT_MJ);
3511 }
3512
Yaxun Liu398612b2018-05-08 21:02:12 +00003513 if (IsCuda || IsHIP) {
3514 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3515 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003516 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003517 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3518 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003519 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3520 ->getTriple()
3521 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003522 else {
3523 // Host-side compilation.
Yaxun Liu398612b2018-05-08 21:02:12 +00003524 NormalizedTriple =
3525 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3526 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3527 ->getTriple()
3528 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003529 if (IsCuda) {
3530 // We need to figure out which CUDA version we're compiling for, as that
3531 // determines how we load and launch GPU kernels.
3532 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3533 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3534 assert(CTC && "Expected valid CUDA Toolchain.");
3535 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3536 CmdArgs.push_back(Args.MakeArgString(
3537 Twine("-target-sdk-version=") +
3538 CudaVersionToString(CTC->CudaInstallation.version())));
3539 }
3540 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003541 CmdArgs.push_back("-aux-triple");
3542 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3543 }
3544
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003545 if (IsOpenMPDevice) {
3546 // We have to pass the triple of the host if compiling for an OpenMP device.
3547 std::string NormalizedTriple =
3548 C.getSingleOffloadToolChain<Action::OFK_Host>()
3549 ->getTriple()
3550 .normalize();
3551 CmdArgs.push_back("-aux-triple");
3552 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3553 }
3554
David L. Jonesf561aba2017-03-08 01:02:16 +00003555 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3556 Triple.getArch() == llvm::Triple::thumb)) {
3557 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3558 unsigned Version;
3559 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3560 if (Version < 7)
3561 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3562 << TripleStr;
3563 }
3564
3565 // Push all default warning arguments that are specific to
3566 // the given target. These come before user provided warning options
3567 // are provided.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003568 TC.addClangWarningOptions(CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003569
3570 // Select the appropriate action.
3571 RewriteKind rewriteKind = RK_None;
3572
3573 if (isa<AnalyzeJobAction>(JA)) {
3574 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3575 CmdArgs.push_back("-analyze");
3576 } else if (isa<MigrateJobAction>(JA)) {
3577 CmdArgs.push_back("-migrate");
3578 } else if (isa<PreprocessJobAction>(JA)) {
3579 if (Output.getType() == types::TY_Dependencies)
3580 CmdArgs.push_back("-Eonly");
3581 else {
3582 CmdArgs.push_back("-E");
3583 if (Args.hasArg(options::OPT_rewrite_objc) &&
3584 !Args.hasArg(options::OPT_g_Group))
3585 CmdArgs.push_back("-P");
3586 }
3587 } else if (isa<AssembleJobAction>(JA)) {
3588 CmdArgs.push_back("-emit-obj");
3589
3590 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3591
3592 // Also ignore explicit -force_cpusubtype_ALL option.
3593 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3594 } else if (isa<PrecompileJobAction>(JA)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003595 if (JA.getType() == types::TY_Nothing)
3596 CmdArgs.push_back("-fsyntax-only");
3597 else if (JA.getType() == types::TY_ModuleFile)
Richard Smithcd35eff2018-09-15 01:21:16 +00003598 CmdArgs.push_back(IsHeaderModulePrecompile
3599 ? "-emit-header-module"
3600 : "-emit-module-interface");
David L. Jonesf561aba2017-03-08 01:02:16 +00003601 else
Erich Keane0a6b5b62018-12-04 14:34:09 +00003602 CmdArgs.push_back("-emit-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00003603 } else if (isa<VerifyPCHJobAction>(JA)) {
3604 CmdArgs.push_back("-verify-pch");
3605 } else {
3606 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3607 "Invalid action for clang tool.");
3608 if (JA.getType() == types::TY_Nothing) {
3609 CmdArgs.push_back("-fsyntax-only");
3610 } else if (JA.getType() == types::TY_LLVM_IR ||
3611 JA.getType() == types::TY_LTO_IR) {
3612 CmdArgs.push_back("-emit-llvm");
3613 } else if (JA.getType() == types::TY_LLVM_BC ||
3614 JA.getType() == types::TY_LTO_BC) {
3615 CmdArgs.push_back("-emit-llvm-bc");
3616 } else if (JA.getType() == types::TY_PP_Asm) {
3617 CmdArgs.push_back("-S");
3618 } else if (JA.getType() == types::TY_AST) {
3619 CmdArgs.push_back("-emit-pch");
3620 } else if (JA.getType() == types::TY_ModuleFile) {
3621 CmdArgs.push_back("-module-file-info");
3622 } else if (JA.getType() == types::TY_RewrittenObjC) {
3623 CmdArgs.push_back("-rewrite-objc");
3624 rewriteKind = RK_NonFragile;
3625 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3626 CmdArgs.push_back("-rewrite-objc");
3627 rewriteKind = RK_Fragile;
3628 } else {
3629 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3630 }
3631
3632 // Preserve use-list order by default when emitting bitcode, so that
3633 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3634 // same result as running passes here. For LTO, we don't need to preserve
3635 // the use-list order, since serialization to bitcode is part of the flow.
3636 if (JA.getType() == types::TY_LLVM_BC)
3637 CmdArgs.push_back("-emit-llvm-uselists");
3638
Artem Belevichecb178b2018-03-21 22:22:59 +00003639 // Device-side jobs do not support LTO.
3640 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3641 JA.isDeviceOffloading(Action::OFK_Host));
3642
3643 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003644 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3645
Paul Robinsond23f2a82017-07-13 21:25:47 +00003646 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3647 // does not support LTO unit features (CFI, whole program vtable opt)
3648 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003649 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003650 D.getLTOMode() == LTOK_Full)
3651 CmdArgs.push_back("-flto-unit");
3652 }
3653 }
3654
3655 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3656 if (!types::isLLVMIR(Input.getType()))
3657 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3658 << "-x ir";
3659 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3660 }
3661
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003662 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003663 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3664
David L. Jonesf561aba2017-03-08 01:02:16 +00003665 // Embed-bitcode option.
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003666 // Only white-listed flags below are allowed to be embedded.
David L. Jonesf561aba2017-03-08 01:02:16 +00003667 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3668 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3669 // Add flags implied by -fembed-bitcode.
3670 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3671 // Disable all llvm IR level optimizations.
3672 CmdArgs.push_back("-disable-llvm-passes");
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003673
3674 // reject options that shouldn't be supported in bitcode
3675 // also reject kernel/kext
3676 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3677 options::OPT_mkernel,
3678 options::OPT_fapple_kext,
3679 options::OPT_ffunction_sections,
3680 options::OPT_fno_function_sections,
3681 options::OPT_fdata_sections,
3682 options::OPT_fno_data_sections,
3683 options::OPT_funique_section_names,
3684 options::OPT_fno_unique_section_names,
3685 options::OPT_mrestrict_it,
3686 options::OPT_mno_restrict_it,
3687 options::OPT_mstackrealign,
3688 options::OPT_mno_stackrealign,
3689 options::OPT_mstack_alignment,
3690 options::OPT_mcmodel_EQ,
3691 options::OPT_mlong_calls,
3692 options::OPT_mno_long_calls,
3693 options::OPT_ggnu_pubnames,
3694 options::OPT_gdwarf_aranges,
3695 options::OPT_fdebug_types_section,
3696 options::OPT_fno_debug_types_section,
3697 options::OPT_fdwarf_directory_asm,
3698 options::OPT_fno_dwarf_directory_asm,
3699 options::OPT_mrelax_all,
3700 options::OPT_mno_relax_all,
3701 options::OPT_ftrap_function_EQ,
3702 options::OPT_ffixed_r9,
3703 options::OPT_mfix_cortex_a53_835769,
3704 options::OPT_mno_fix_cortex_a53_835769,
3705 options::OPT_ffixed_x18,
3706 options::OPT_mglobal_merge,
3707 options::OPT_mno_global_merge,
3708 options::OPT_mred_zone,
3709 options::OPT_mno_red_zone,
3710 options::OPT_Wa_COMMA,
3711 options::OPT_Xassembler,
3712 options::OPT_mllvm,
3713 };
3714 for (const auto &A : Args)
Fangrui Song75e74e02019-03-31 08:48:19 +00003715 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003716 std::end(kBitcodeOptionBlacklist))
3717 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3718
3719 // Render the CodeGen options that need to be passed.
3720 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3721 options::OPT_fno_optimize_sibling_calls))
3722 CmdArgs.push_back("-mdisable-tail-calls");
3723
3724 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3725 CmdArgs);
3726
3727 // Render ABI arguments
3728 switch (TC.getArch()) {
3729 default: break;
3730 case llvm::Triple::arm:
3731 case llvm::Triple::armeb:
3732 case llvm::Triple::thumbeb:
3733 RenderARMABI(Triple, Args, CmdArgs);
3734 break;
3735 case llvm::Triple::aarch64:
3736 case llvm::Triple::aarch64_be:
3737 RenderAArch64ABI(Triple, Args, CmdArgs);
3738 break;
3739 }
3740
3741 // Optimization level for CodeGen.
3742 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3743 if (A->getOption().matches(options::OPT_O4)) {
3744 CmdArgs.push_back("-O3");
3745 D.Diag(diag::warn_O4_is_O3);
3746 } else {
3747 A->render(Args, CmdArgs);
3748 }
3749 }
3750
3751 // Input/Output file.
3752 if (Output.getType() == types::TY_Dependencies) {
3753 // Handled with other dependency code.
3754 } else if (Output.isFilename()) {
3755 CmdArgs.push_back("-o");
3756 CmdArgs.push_back(Output.getFilename());
3757 } else {
3758 assert(Output.isNothing() && "Input output.");
3759 }
3760
3761 for (const auto &II : Inputs) {
3762 addDashXForInput(Args, II, CmdArgs);
3763 if (II.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00003764 CmdArgs.push_back(II.getFilename());
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003765 else
3766 II.getInputArg().renderAsInput(Args, CmdArgs);
3767 }
3768
3769 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3770 CmdArgs, Inputs));
3771 return;
David L. Jonesf561aba2017-03-08 01:02:16 +00003772 }
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003773
David L. Jonesf561aba2017-03-08 01:02:16 +00003774 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3775 CmdArgs.push_back("-fembed-bitcode=marker");
3776
3777 // We normally speed up the clang process a bit by skipping destructors at
3778 // exit, but when we're generating diagnostics we can rely on some of the
3779 // cleanup.
3780 if (!C.isForDiagnostics())
3781 CmdArgs.push_back("-disable-free");
3782
David L. Jonesf561aba2017-03-08 01:02:16 +00003783#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003784 const bool IsAssertBuild = false;
3785#else
3786 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003787#endif
3788
Eric Fiselier123c7492018-02-07 18:36:51 +00003789 // Disable the verification pass in -asserts builds.
3790 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003791 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003792
3793 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003794 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3795 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003796 CmdArgs.push_back("-discard-value-names");
3797
David L. Jonesf561aba2017-03-08 01:02:16 +00003798 // Set the main file name, so that debug info works even with
3799 // -save-temps.
3800 CmdArgs.push_back("-main-file-name");
3801 CmdArgs.push_back(getBaseInputName(Args, Input));
3802
3803 // Some flags which affect the language (via preprocessor
3804 // defines).
3805 if (Args.hasArg(options::OPT_static))
3806 CmdArgs.push_back("-static-define");
3807
Martin Storsjo434ef832018-08-06 19:48:44 +00003808 if (Args.hasArg(options::OPT_municode))
3809 CmdArgs.push_back("-DUNICODE");
3810
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003811 if (isa<AnalyzeJobAction>(JA))
3812 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003813
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003814 // Enable compatilibily mode to avoid analyzer-config related errors.
3815 // Since we can't access frontend flags through hasArg, let's manually iterate
3816 // through them.
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003817 bool FoundAnalyzerConfig = false;
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003818 for (auto Arg : Args.filtered(options::OPT_Xclang))
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003819 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3820 FoundAnalyzerConfig = true;
3821 break;
3822 }
3823 if (!FoundAnalyzerConfig)
3824 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3825 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3826 FoundAnalyzerConfig = true;
3827 break;
3828 }
3829 if (FoundAnalyzerConfig)
3830 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003831
David L. Jonesf561aba2017-03-08 01:02:16 +00003832 CheckCodeGenerationOptions(D, Args);
3833
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003834 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003835 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3836 if (FunctionAlignment) {
3837 CmdArgs.push_back("-function-alignment");
3838 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3839 }
3840
David L. Jonesf561aba2017-03-08 01:02:16 +00003841 llvm::Reloc::Model RelocationModel;
3842 unsigned PICLevel;
3843 bool IsPIE;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003844 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003845
3846 const char *RMName = RelocationModelName(RelocationModel);
3847
3848 if ((RelocationModel == llvm::Reloc::ROPI ||
3849 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3850 types::isCXX(Input.getType()) &&
3851 !Args.hasArg(options::OPT_fallow_unsupported))
3852 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3853
3854 if (RMName) {
3855 CmdArgs.push_back("-mrelocation-model");
3856 CmdArgs.push_back(RMName);
3857 }
3858 if (PICLevel > 0) {
3859 CmdArgs.push_back("-pic-level");
3860 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3861 if (IsPIE)
3862 CmdArgs.push_back("-pic-is-pie");
3863 }
3864
Oliver Stannarde3c8ce82019-02-18 12:39:47 +00003865 if (RelocationModel == llvm::Reloc::ROPI ||
3866 RelocationModel == llvm::Reloc::ROPI_RWPI)
3867 CmdArgs.push_back("-fropi");
3868 if (RelocationModel == llvm::Reloc::RWPI ||
3869 RelocationModel == llvm::Reloc::ROPI_RWPI)
3870 CmdArgs.push_back("-frwpi");
3871
David L. Jonesf561aba2017-03-08 01:02:16 +00003872 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3873 CmdArgs.push_back("-meabi");
3874 CmdArgs.push_back(A->getValue());
3875 }
3876
3877 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003878 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003879 if (!TC.isThreadModelSupported(A->getValue()))
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003880 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3881 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003882 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003883 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003884 else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00003885 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003886
3887 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3888
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003889 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3890 options::OPT_fno_merge_all_constants, false))
3891 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003892
Manoj Guptada08f6a2018-07-19 00:44:52 +00003893 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3894 options::OPT_fdelete_null_pointer_checks, false))
3895 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3896
David L. Jonesf561aba2017-03-08 01:02:16 +00003897 // LLVM Code Generator Options.
3898
3899 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3900 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3901 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3902 options::OPT_frewrite_map_file_EQ)) {
3903 StringRef Map = A->getValue();
3904 if (!llvm::sys::fs::exists(Map)) {
3905 D.Diag(diag::err_drv_no_such_file) << Map;
3906 } else {
3907 CmdArgs.push_back("-frewrite-map-file");
3908 CmdArgs.push_back(A->getValue());
3909 A->claim();
3910 }
3911 }
3912 }
3913
3914 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3915 StringRef v = A->getValue();
3916 CmdArgs.push_back("-mllvm");
3917 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3918 A->claim();
3919 }
3920
3921 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3922 true))
3923 CmdArgs.push_back("-fno-jump-tables");
3924
Dehao Chen5e97f232017-08-24 21:37:33 +00003925 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3926 options::OPT_fno_profile_sample_accurate, false))
3927 CmdArgs.push_back("-fprofile-sample-accurate");
3928
David L. Jonesf561aba2017-03-08 01:02:16 +00003929 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3930 options::OPT_fno_preserve_as_comments, true))
3931 CmdArgs.push_back("-fno-preserve-as-comments");
3932
3933 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3934 CmdArgs.push_back("-mregparm");
3935 CmdArgs.push_back(A->getValue());
3936 }
3937
3938 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3939 options::OPT_freg_struct_return)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003940 if (TC.getArch() != llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003941 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003942 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003943 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3944 CmdArgs.push_back("-fpcc-struct-return");
3945 } else {
3946 assert(A->getOption().matches(options::OPT_freg_struct_return));
3947 CmdArgs.push_back("-freg-struct-return");
3948 }
3949 }
3950
3951 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3952 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3953
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003954 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003955 CmdArgs.push_back("-mdisable-fp-elim");
3956 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3957 options::OPT_fno_zero_initialized_in_bss))
3958 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3959
3960 bool OFastEnabled = isOptimizationLevelFast(Args);
3961 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3962 // enabled. This alias option is being used to simplify the hasFlag logic.
3963 OptSpecifier StrictAliasingAliasOption =
3964 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3965 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3966 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003967 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003968 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3969 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3970 CmdArgs.push_back("-relaxed-aliasing");
3971 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3972 options::OPT_fno_struct_path_tbaa))
3973 CmdArgs.push_back("-no-struct-path-tbaa");
3974 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3975 false))
3976 CmdArgs.push_back("-fstrict-enums");
3977 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3978 true))
3979 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003980 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3981 options::OPT_fno_allow_editor_placeholders, false))
3982 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003983 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3984 options::OPT_fno_strict_vtable_pointers,
3985 false))
3986 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003987 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3988 options::OPT_fno_force_emit_vtables,
3989 false))
3990 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00003991 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3992 options::OPT_fno_optimize_sibling_calls))
3993 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003994 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003995 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003996 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003997
Wei Mi9b3d6272017-10-16 16:50:27 +00003998 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3999 options::OPT_fno_fine_grained_bitfield_accesses);
4000
David L. Jonesf561aba2017-03-08 01:02:16 +00004001 // Handle segmented stacks.
4002 if (Args.hasArg(options::OPT_fsplit_stack))
4003 CmdArgs.push_back("-split-stacks");
4004
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004005 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004006
4007 // Decide whether to use verbose asm. Verbose assembly is the default on
4008 // toolchains which have the integrated assembler on by default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004009 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00004010 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4011 IsIntegratedAssemblerDefault) ||
4012 Args.hasArg(options::OPT_dA))
4013 CmdArgs.push_back("-masm-verbose");
4014
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004015 if (!TC.useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00004016 CmdArgs.push_back("-no-integrated-as");
4017
4018 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4019 CmdArgs.push_back("-mdebug-pass");
4020 CmdArgs.push_back("Structure");
4021 }
4022 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4023 CmdArgs.push_back("-mdebug-pass");
4024 CmdArgs.push_back("Arguments");
4025 }
4026
4027 // Enable -mconstructor-aliases except on darwin, where we have to work around
4028 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4029 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004030 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00004031 CmdArgs.push_back("-mconstructor-aliases");
4032
4033 // Darwin's kernel doesn't support guard variables; just die if we
4034 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004035 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00004036 CmdArgs.push_back("-fforbid-guard-variables");
4037
4038 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4039 false)) {
4040 CmdArgs.push_back("-mms-bitfields");
4041 }
4042
4043 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4044 options::OPT_mno_pie_copy_relocations,
4045 false)) {
4046 CmdArgs.push_back("-mpie-copy-relocations");
4047 }
4048
Sriraman Tallam5c651482017-11-07 19:37:51 +00004049 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4050 CmdArgs.push_back("-fno-plt");
4051 }
4052
Vedant Kumardf502592017-09-12 22:51:53 +00004053 // -fhosted is default.
4054 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4055 // use Freestanding.
4056 bool Freestanding =
4057 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4058 KernelOrKext;
4059 if (Freestanding)
4060 CmdArgs.push_back("-ffreestanding");
4061
David L. Jonesf561aba2017-03-08 01:02:16 +00004062 // This is a coarse approximation of what llvm-gcc actually does, both
4063 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4064 // complicated ways.
4065 bool AsynchronousUnwindTables =
4066 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4067 options::OPT_fno_asynchronous_unwind_tables,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004068 (TC.IsUnwindTablesDefault(Args) ||
4069 TC.getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00004070 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00004071 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4072 AsynchronousUnwindTables))
4073 CmdArgs.push_back("-munwind-tables");
4074
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004075 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00004076
David L. Jonesf561aba2017-03-08 01:02:16 +00004077 // FIXME: Handle -mtune=.
4078 (void)Args.hasArg(options::OPT_mtune_EQ);
4079
4080 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4081 CmdArgs.push_back("-mcode-model");
4082 CmdArgs.push_back(A->getValue());
4083 }
4084
4085 // Add the target cpu
4086 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4087 if (!CPU.empty()) {
4088 CmdArgs.push_back("-target-cpu");
4089 CmdArgs.push_back(Args.MakeArgString(CPU));
4090 }
4091
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00004092 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004093
David L. Jonesf561aba2017-03-08 01:02:16 +00004094 // These two are potentially updated by AddClangCLArgs.
4095 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4096 bool EmitCodeView = false;
4097
4098 // Add clang-cl arguments.
4099 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004100 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00004101 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4102
George Rimar91829ee2018-11-14 09:22:16 +00004103 DwarfFissionKind DwarfFission;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004104 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
George Rimar91829ee2018-11-14 09:22:16 +00004105 CmdArgs, DebugInfoKind, DwarfFission);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004106
4107 // Add the split debug info name to the command lines here so we
4108 // can propagate it to the backend.
George Rimar91829ee2018-11-14 09:22:16 +00004109 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
Fangrui Songee957e02019-03-28 08:24:00 +00004110 TC.getTriple().isOSBinFormatELF() &&
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004111 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4112 isa<BackendJobAction>(JA));
4113 const char *SplitDWARFOut;
4114 if (SplitDWARF) {
4115 CmdArgs.push_back("-split-dwarf-file");
George Rimar36d71da2019-03-27 11:00:03 +00004116 SplitDWARFOut = SplitDebugName(Args, Input, Output);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004117 CmdArgs.push_back(SplitDWARFOut);
4118 }
4119
David L. Jonesf561aba2017-03-08 01:02:16 +00004120 // Pass the linker version in use.
4121 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4122 CmdArgs.push_back("-target-linker-version");
4123 CmdArgs.push_back(A->getValue());
4124 }
4125
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004126 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00004127 CmdArgs.push_back("-momit-leaf-frame-pointer");
4128
4129 // Explicitly error on some things we know we don't support and can't just
4130 // ignore.
4131 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4132 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004133 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004134 TC.getArch() == llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004135 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4136 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4137 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4138 << Unsupported->getOption().getName();
4139 }
Eric Christopher758aad72017-03-21 22:06:18 +00004140 // The faltivec option has been superseded by the maltivec option.
4141 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4142 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4143 << Unsupported->getOption().getName()
4144 << "please use -maltivec and include altivec.h explicitly";
4145 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4146 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4147 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00004148 }
4149
4150 Args.AddAllArgs(CmdArgs, options::OPT_v);
4151 Args.AddLastArg(CmdArgs, options::OPT_H);
4152 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4153 CmdArgs.push_back("-header-include-file");
4154 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4155 : "-");
4156 }
4157 Args.AddLastArg(CmdArgs, options::OPT_P);
4158 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4159
4160 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4161 CmdArgs.push_back("-diagnostic-log-file");
4162 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4163 : "-");
4164 }
4165
David L. Jonesf561aba2017-03-08 01:02:16 +00004166 bool UseSeparateSections = isUseSeparateSections(Triple);
4167
4168 if (Args.hasFlag(options::OPT_ffunction_sections,
4169 options::OPT_fno_function_sections, UseSeparateSections)) {
4170 CmdArgs.push_back("-ffunction-sections");
4171 }
4172
4173 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4174 UseSeparateSections)) {
4175 CmdArgs.push_back("-fdata-sections");
4176 }
4177
4178 if (!Args.hasFlag(options::OPT_funique_section_names,
4179 options::OPT_fno_unique_section_names, true))
4180 CmdArgs.push_back("-fno-unique-section-names");
4181
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00004182 if (auto *A = Args.getLastArg(
4183 options::OPT_finstrument_functions,
4184 options::OPT_finstrument_functions_after_inlining,
4185 options::OPT_finstrument_function_entry_bare))
4186 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004187
Artem Belevichc30bcad2018-01-24 17:41:02 +00004188 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4189 // sampling, overhead of call arc collection is way too high and there's no
4190 // way to collect the output.
4191 if (!Triple.isNVPTX())
Russell Gallop7a9ccf82019-05-14 14:01:40 +00004192 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004193
Richard Smithf667ad52017-08-26 01:04:35 +00004194 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
4195 ABICompatArg->render(Args, CmdArgs);
4196
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004197 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
Pierre Gousseau53b5cfb2018-12-18 17:03:35 +00004198 if (RawTriple.isPS4CPU() &&
4199 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004200 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4201 PS4cpu::addSanitizerArgs(TC, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004202 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004203
4204 // Pass options for controlling the default header search paths.
4205 if (Args.hasArg(options::OPT_nostdinc)) {
4206 CmdArgs.push_back("-nostdsysteminc");
4207 CmdArgs.push_back("-nobuiltininc");
4208 } else {
4209 if (Args.hasArg(options::OPT_nostdlibinc))
4210 CmdArgs.push_back("-nostdsysteminc");
4211 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4212 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4213 }
4214
4215 // Pass the path to compiler resource files.
4216 CmdArgs.push_back("-resource-dir");
4217 CmdArgs.push_back(D.ResourceDir.c_str());
4218
4219 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4220
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00004221 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004222
4223 // Add preprocessing options like -I, -D, etc. if we are using the
4224 // preprocessor.
4225 //
4226 // FIXME: Support -fpreprocessed
4227 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4228 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4229
4230 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4231 // that "The compiler can only warn and ignore the option if not recognized".
4232 // When building with ccache, it will pass -D options to clang even on
4233 // preprocessed inputs and configure concludes that -fPIC is not supported.
4234 Args.ClaimAllArgs(options::OPT_D);
4235
4236 // Manually translate -O4 to -O3; let clang reject others.
4237 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4238 if (A->getOption().matches(options::OPT_O4)) {
4239 CmdArgs.push_back("-O3");
4240 D.Diag(diag::warn_O4_is_O3);
4241 } else {
4242 A->render(Args, CmdArgs);
4243 }
4244 }
4245
4246 // Warn about ignored options to clang.
4247 for (const Arg *A :
4248 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4249 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4250 A->claim();
4251 }
4252
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00004253 for (const Arg *A :
4254 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4255 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4256 A->claim();
4257 }
4258
David L. Jonesf561aba2017-03-08 01:02:16 +00004259 claimNoWarnArgs(Args);
4260
4261 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4262
4263 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4264 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4265 CmdArgs.push_back("-pedantic");
4266 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4267 Args.AddLastArg(CmdArgs, options::OPT_w);
4268
Leonard Chanf921d852018-06-04 16:07:52 +00004269 // Fixed point flags
4270 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4271 /*Default=*/false))
4272 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4273
David L. Jonesf561aba2017-03-08 01:02:16 +00004274 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4275 // (-ansi is equivalent to -std=c89 or -std=c++98).
4276 //
4277 // If a std is supplied, only add -trigraphs if it follows the
4278 // option.
4279 bool ImplyVCPPCXXVer = false;
Richard Smithb1b580e2019-04-14 11:11:37 +00004280 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
4281 if (Std) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004282 if (Std->getOption().matches(options::OPT_ansi))
4283 if (types::isCXX(InputType))
4284 CmdArgs.push_back("-std=c++98");
4285 else
4286 CmdArgs.push_back("-std=c89");
4287 else
4288 Std->render(Args, CmdArgs);
4289
4290 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4291 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4292 options::OPT_ftrigraphs,
4293 options::OPT_fno_trigraphs))
4294 if (A != Std)
4295 A->render(Args, CmdArgs);
4296 } else {
4297 // Honor -std-default.
4298 //
4299 // FIXME: Clang doesn't correctly handle -std= when the input language
4300 // doesn't match. For the time being just ignore this for C++ inputs;
4301 // eventually we want to do all the standard defaulting here instead of
4302 // splitting it between the driver and clang -cc1.
4303 if (!types::isCXX(InputType))
4304 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4305 /*Joined=*/true);
4306 else if (IsWindowsMSVC)
4307 ImplyVCPPCXXVer = true;
4308
4309 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4310 options::OPT_fno_trigraphs);
4311 }
4312
4313 // GCC's behavior for -Wwrite-strings is a bit strange:
4314 // * In C, this "warning flag" changes the types of string literals from
4315 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4316 // for the discarded qualifier.
4317 // * In C++, this is just a normal warning flag.
4318 //
4319 // Implementing this warning correctly in C is hard, so we follow GCC's
4320 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4321 // a non-const char* in C, rather than using this crude hack.
4322 if (!types::isCXX(InputType)) {
4323 // FIXME: This should behave just like a warning flag, and thus should also
4324 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4325 Arg *WriteStrings =
4326 Args.getLastArg(options::OPT_Wwrite_strings,
4327 options::OPT_Wno_write_strings, options::OPT_w);
4328 if (WriteStrings &&
4329 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4330 CmdArgs.push_back("-fconst-strings");
4331 }
4332
4333 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4334 // during C++ compilation, which it is by default. GCC keeps this define even
4335 // in the presence of '-w', match this behavior bug-for-bug.
4336 if (types::isCXX(InputType) &&
4337 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4338 true)) {
4339 CmdArgs.push_back("-fdeprecated-macro");
4340 }
4341
4342 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4343 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4344 if (Asm->getOption().matches(options::OPT_fasm))
4345 CmdArgs.push_back("-fgnu-keywords");
4346 else
4347 CmdArgs.push_back("-fno-gnu-keywords");
4348 }
4349
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004350 if (ShouldDisableDwarfDirectory(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004351 CmdArgs.push_back("-fno-dwarf-directory-asm");
4352
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004353 if (ShouldDisableAutolink(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004354 CmdArgs.push_back("-fno-autolink");
4355
4356 // Add in -fdebug-compilation-dir if necessary.
4357 addDebugCompDirArg(Args, CmdArgs);
4358
Paul Robinson9b292b42018-07-10 15:15:24 +00004359 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004360
4361 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4362 options::OPT_ftemplate_depth_EQ)) {
4363 CmdArgs.push_back("-ftemplate-depth");
4364 CmdArgs.push_back(A->getValue());
4365 }
4366
4367 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4368 CmdArgs.push_back("-foperator-arrow-depth");
4369 CmdArgs.push_back(A->getValue());
4370 }
4371
4372 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4373 CmdArgs.push_back("-fconstexpr-depth");
4374 CmdArgs.push_back(A->getValue());
4375 }
4376
4377 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4378 CmdArgs.push_back("-fconstexpr-steps");
4379 CmdArgs.push_back(A->getValue());
4380 }
4381
4382 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4383 CmdArgs.push_back("-fbracket-depth");
4384 CmdArgs.push_back(A->getValue());
4385 }
4386
4387 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4388 options::OPT_Wlarge_by_value_copy_def)) {
4389 if (A->getNumValues()) {
4390 StringRef bytes = A->getValue();
4391 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4392 } else
4393 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4394 }
4395
4396 if (Args.hasArg(options::OPT_relocatable_pch))
4397 CmdArgs.push_back("-relocatable-pch");
4398
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004399 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4400 static const char *kCFABIs[] = {
4401 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4402 };
4403
4404 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4405 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4406 else
4407 A->render(Args, CmdArgs);
4408 }
4409
David L. Jonesf561aba2017-03-08 01:02:16 +00004410 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4411 CmdArgs.push_back("-fconstant-string-class");
4412 CmdArgs.push_back(A->getValue());
4413 }
4414
4415 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4416 CmdArgs.push_back("-ftabstop");
4417 CmdArgs.push_back(A->getValue());
4418 }
4419
Sean Eveson5110d4f2018-01-08 13:42:26 +00004420 if (Args.hasFlag(options::OPT_fstack_size_section,
4421 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4422 CmdArgs.push_back("-fstack-size-section");
4423
David L. Jonesf561aba2017-03-08 01:02:16 +00004424 CmdArgs.push_back("-ferror-limit");
4425 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4426 CmdArgs.push_back(A->getValue());
4427 else
4428 CmdArgs.push_back("19");
4429
4430 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4431 CmdArgs.push_back("-fmacro-backtrace-limit");
4432 CmdArgs.push_back(A->getValue());
4433 }
4434
4435 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4436 CmdArgs.push_back("-ftemplate-backtrace-limit");
4437 CmdArgs.push_back(A->getValue());
4438 }
4439
4440 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4441 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4442 CmdArgs.push_back(A->getValue());
4443 }
4444
4445 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4446 CmdArgs.push_back("-fspell-checking-limit");
4447 CmdArgs.push_back(A->getValue());
4448 }
4449
4450 // Pass -fmessage-length=.
4451 CmdArgs.push_back("-fmessage-length");
4452 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4453 CmdArgs.push_back(A->getValue());
4454 } else {
4455 // If -fmessage-length=N was not specified, determine whether this is a
4456 // terminal and, if so, implicitly define -fmessage-length appropriately.
4457 unsigned N = llvm::sys::Process::StandardErrColumns();
4458 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4459 }
4460
4461 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4462 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4463 options::OPT_fvisibility_ms_compat)) {
4464 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4465 CmdArgs.push_back("-fvisibility");
4466 CmdArgs.push_back(A->getValue());
4467 } else {
4468 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4469 CmdArgs.push_back("-fvisibility");
4470 CmdArgs.push_back("hidden");
4471 CmdArgs.push_back("-ftype-visibility");
4472 CmdArgs.push_back("default");
4473 }
4474 }
4475
4476 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
Petr Hosek821b38f2018-12-04 03:25:25 +00004477 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
David L. Jonesf561aba2017-03-08 01:02:16 +00004478
4479 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4480
David L. Jonesf561aba2017-03-08 01:02:16 +00004481 // Forward -f (flag) options which we can pass directly.
4482 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4483 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004484 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004485 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004486 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4487 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004488 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004489
David L. Jonesf561aba2017-03-08 01:02:16 +00004490 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004491 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004492 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004493
David L. Jonesf561aba2017-03-08 01:02:16 +00004494 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4495 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4496
4497 // Forward flags for OpenMP. We don't do this if the current action is an
4498 // device offloading action other than OpenMP.
4499 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4500 options::OPT_fno_openmp, false) &&
4501 (JA.isDeviceOffloading(Action::OFK_None) ||
4502 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004503 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004504 case Driver::OMPRT_OMP:
4505 case Driver::OMPRT_IOMP5:
4506 // Clang can generate useful OpenMP code for these two runtime libraries.
4507 CmdArgs.push_back("-fopenmp");
4508
4509 // If no option regarding the use of TLS in OpenMP codegeneration is
4510 // given, decide a default based on the target. Otherwise rely on the
4511 // options and pass the right information to the frontend.
4512 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4513 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4514 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004515 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4516 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004517 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Alexey Bataeve4090182018-11-02 14:54:07 +00004518 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4519 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004520 Args.AddAllArgs(CmdArgs,
4521 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004522 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4523 options::OPT_fno_openmp_optimistic_collapse,
4524 /*Default=*/false))
4525 CmdArgs.push_back("-fopenmp-optimistic-collapse");
Carlo Bertolli79712092018-02-28 20:48:35 +00004526
4527 // When in OpenMP offloading mode with NVPTX target, forward
4528 // cuda-mode flag
Alexey Bataev80a9a612018-08-30 14:45:24 +00004529 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4530 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4531 CmdArgs.push_back("-fopenmp-cuda-mode");
4532
4533 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4534 // is required.
4535 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4536 options::OPT_fno_openmp_cuda_force_full_runtime,
4537 /*Default=*/false))
4538 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
David L. Jonesf561aba2017-03-08 01:02:16 +00004539 break;
4540 default:
4541 // By default, if Clang doesn't know how to generate useful OpenMP code
4542 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4543 // down to the actual compilation.
4544 // FIXME: It would be better to have a mode which *only* omits IR
4545 // generation based on the OpenMP support so that we get consistent
4546 // semantic analysis, etc.
4547 break;
4548 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004549 } else {
4550 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4551 options::OPT_fno_openmp_simd);
4552 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004553 }
4554
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004555 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4556 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
David L. Jonesf561aba2017-03-08 01:02:16 +00004557
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004558 const XRayArgs &XRay = TC.getXRayArgs();
4559 XRay.addArgs(TC, Args, CmdArgs, InputType);
Dean Michael Berris835832d2017-03-30 00:29:36 +00004560
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004561 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004562 Args.AddLastArg(CmdArgs, options::OPT_pg);
4563
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004564 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004565 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4566
4567 // -flax-vector-conversions is default.
4568 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4569 options::OPT_fno_lax_vector_conversions))
4570 CmdArgs.push_back("-fno-lax-vector-conversions");
4571
4572 if (Args.getLastArg(options::OPT_fapple_kext) ||
4573 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4574 CmdArgs.push_back("-fapple-kext");
4575
4576 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4577 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4578 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4579 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
Anton Afanasyevd880de22019-03-30 08:42:48 +00004580 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
David L. Jonesf561aba2017-03-08 01:02:16 +00004581 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
Craig Topper3205dbb2019-03-21 20:07:24 +00004582 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
David L. Jonesf561aba2017-03-08 01:02:16 +00004583
4584 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4585 CmdArgs.push_back("-ftrapv-handler");
4586 CmdArgs.push_back(A->getValue());
4587 }
4588
4589 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4590
4591 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4592 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4593 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4594 if (A->getOption().matches(options::OPT_fwrapv))
4595 CmdArgs.push_back("-fwrapv");
4596 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4597 options::OPT_fno_strict_overflow)) {
4598 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4599 CmdArgs.push_back("-fwrapv");
4600 }
4601
4602 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4603 options::OPT_fno_reroll_loops))
4604 if (A->getOption().matches(options::OPT_freroll_loops))
4605 CmdArgs.push_back("-freroll-loops");
4606
4607 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4608 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4609 options::OPT_fno_unroll_loops);
4610
4611 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4612
Zola Bridgesc8666792018-11-26 18:13:31 +00004613 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4614 false))
4615 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
Chandler Carruth664aa862018-09-04 12:38:00 +00004616
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004617 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
JF Bastien14daa202018-12-18 05:12:21 +00004618 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004619
4620 // Translate -mstackrealign
4621 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4622 false))
4623 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4624
4625 if (Args.hasArg(options::OPT_mstack_alignment)) {
4626 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4627 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4628 }
4629
4630 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4631 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4632
4633 if (!Size.empty())
4634 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4635 else
4636 CmdArgs.push_back("-mstack-probe-size=0");
4637 }
4638
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004639 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4640 options::OPT_mno_stack_arg_probe, true))
4641 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4642
David L. Jonesf561aba2017-03-08 01:02:16 +00004643 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4644 options::OPT_mno_restrict_it)) {
4645 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004646 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004647 CmdArgs.push_back("-arm-restrict-it");
4648 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004649 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004650 CmdArgs.push_back("-arm-no-restrict-it");
4651 }
4652 } else if (Triple.isOSWindows() &&
4653 (Triple.getArch() == llvm::Triple::arm ||
4654 Triple.getArch() == llvm::Triple::thumb)) {
4655 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004656 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004657 CmdArgs.push_back("-arm-restrict-it");
4658 }
4659
4660 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004661 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004662
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004663 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4664 CmdArgs.push_back(
4665 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4666 }
4667
David L. Jonesf561aba2017-03-08 01:02:16 +00004668 // Forward -f options with positive and negative forms; we translate
4669 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004670 if (Arg *A = getLastProfileSampleUseArg(Args)) {
Rong Xua4a09b22019-03-04 20:21:31 +00004671 auto *PGOArg = Args.getLastArg(
4672 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4673 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4674 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4675 if (PGOArg)
4676 D.Diag(diag::err_drv_argument_not_allowed_with)
4677 << "SampleUse with PGO options";
4678
David L. Jonesf561aba2017-03-08 01:02:16 +00004679 StringRef fname = A->getValue();
4680 if (!llvm::sys::fs::exists(fname))
4681 D.Diag(diag::err_drv_no_such_file) << fname;
4682 else
4683 A->render(Args, CmdArgs);
4684 }
Richard Smith8654ae52018-10-10 23:13:35 +00004685 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004686
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004687 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004688
4689 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4690 options::OPT_fno_assume_sane_operator_new))
4691 CmdArgs.push_back("-fno-assume-sane-operator-new");
4692
4693 // -fblocks=0 is default.
4694 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004695 TC.IsBlocksDefault()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004696 (Args.hasArg(options::OPT_fgnu_runtime) &&
4697 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4698 !Args.hasArg(options::OPT_fno_blocks))) {
4699 CmdArgs.push_back("-fblocks");
4700
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004701 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
David L. Jonesf561aba2017-03-08 01:02:16 +00004702 CmdArgs.push_back("-fblocks-runtime-optional");
4703 }
4704
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004705 // -fencode-extended-block-signature=1 is default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004706 if (TC.IsEncodeExtendedBlockSignatureDefault())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004707 CmdArgs.push_back("-fencode-extended-block-signature");
4708
David L. Jonesf561aba2017-03-08 01:02:16 +00004709 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4710 false) &&
4711 types::isCXX(InputType)) {
4712 CmdArgs.push_back("-fcoroutines-ts");
4713 }
4714
Aaron Ballman61736552017-10-21 20:28:58 +00004715 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4716 options::OPT_fno_double_square_bracket_attributes);
4717
David L. Jonesf561aba2017-03-08 01:02:16 +00004718 // -faccess-control is default.
4719 if (Args.hasFlag(options::OPT_fno_access_control,
4720 options::OPT_faccess_control, false))
4721 CmdArgs.push_back("-fno-access-control");
4722
4723 // -felide-constructors is the default.
4724 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4725 options::OPT_felide_constructors, false))
4726 CmdArgs.push_back("-fno-elide-constructors");
4727
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004728 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004729
4730 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004731 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004732 CmdArgs.push_back("-fno-rtti");
4733
4734 // -fshort-enums=0 is default for all architectures except Hexagon.
4735 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004736 TC.getArch() == llvm::Triple::hexagon))
David L. Jonesf561aba2017-03-08 01:02:16 +00004737 CmdArgs.push_back("-fshort-enums");
4738
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004739 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004740
4741 // -fuse-cxa-atexit is default.
4742 if (!Args.hasFlag(
4743 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004744 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004745 RawTriple.getOS() != llvm::Triple::Solaris &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004746 TC.getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004747 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4748 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004749 KernelOrKext)
4750 CmdArgs.push_back("-fno-use-cxa-atexit");
4751
Akira Hatanaka617e2612018-04-17 18:41:52 +00004752 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4753 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004754 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004755 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4756
David L. Jonesf561aba2017-03-08 01:02:16 +00004757 // -fms-extensions=0 is default.
4758 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4759 IsWindowsMSVC))
4760 CmdArgs.push_back("-fms-extensions");
4761
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004762 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004763 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004764 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004765 CmdArgs.push_back("-fuse-line-directives");
4766
4767 // -fms-compatibility=0 is default.
4768 if (Args.hasFlag(options::OPT_fms_compatibility,
4769 options::OPT_fno_ms_compatibility,
4770 (IsWindowsMSVC &&
4771 Args.hasFlag(options::OPT_fms_extensions,
4772 options::OPT_fno_ms_extensions, true))))
4773 CmdArgs.push_back("-fms-compatibility");
4774
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004775 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004776 if (!MSVT.empty())
4777 CmdArgs.push_back(
4778 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4779
4780 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4781 if (ImplyVCPPCXXVer) {
4782 StringRef LanguageStandard;
4783 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
Richard Smithb1b580e2019-04-14 11:11:37 +00004784 Std = StdArg;
David L. Jonesf561aba2017-03-08 01:02:16 +00004785 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4786 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004787 .Case("c++17", "-std=c++17")
4788 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004789 .Default("");
4790 if (LanguageStandard.empty())
4791 D.Diag(clang::diag::warn_drv_unused_argument)
4792 << StdArg->getAsString(Args);
4793 }
4794
4795 if (LanguageStandard.empty()) {
4796 if (IsMSVC2015Compatible)
4797 LanguageStandard = "-std=c++14";
4798 else
4799 LanguageStandard = "-std=c++11";
4800 }
4801
4802 CmdArgs.push_back(LanguageStandard.data());
4803 }
4804
4805 // -fno-borland-extensions is default.
4806 if (Args.hasFlag(options::OPT_fborland_extensions,
4807 options::OPT_fno_borland_extensions, false))
4808 CmdArgs.push_back("-fborland-extensions");
4809
4810 // -fno-declspec is default, except for PS4.
4811 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004812 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004813 CmdArgs.push_back("-fdeclspec");
4814 else if (Args.hasArg(options::OPT_fno_declspec))
4815 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4816
4817 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4818 // than 19.
4819 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4820 options::OPT_fno_threadsafe_statics,
4821 !IsWindowsMSVC || IsMSVC2015Compatible))
4822 CmdArgs.push_back("-fno-threadsafe-statics");
4823
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004824 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004825 // Many old Windows SDK versions require this to parse.
4826 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4827 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004828 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4829 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4830 CmdArgs.push_back("-fdelayed-template-parsing");
4831
4832 // -fgnu-keywords default varies depending on language; only pass if
4833 // specified.
4834 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4835 options::OPT_fno_gnu_keywords))
4836 A->render(Args, CmdArgs);
4837
4838 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4839 false))
4840 CmdArgs.push_back("-fgnu89-inline");
4841
4842 if (Args.hasArg(options::OPT_fno_inline))
4843 CmdArgs.push_back("-fno-inline");
4844
4845 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4846 options::OPT_finline_hint_functions,
4847 options::OPT_fno_inline_functions))
4848 InlineArg->render(Args, CmdArgs);
4849
Richard Smithb1b580e2019-04-14 11:11:37 +00004850 // FIXME: Find a better way to determine whether the language has modules
4851 // support by default, or just assume that all languages do.
4852 bool HaveModules =
4853 Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
4854 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4855
David L. Jonesf561aba2017-03-08 01:02:16 +00004856 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4857 options::OPT_fno_experimental_new_pass_manager);
4858
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004859 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004860 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4861 Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004862
4863 if (Args.hasFlag(options::OPT_fapplication_extension,
4864 options::OPT_fno_application_extension, false))
4865 CmdArgs.push_back("-fapplication-extension");
4866
4867 // Handle GCC-style exception args.
4868 if (!C.getDriver().IsCLMode())
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004869 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004870
Martell Malonec950c652017-11-29 07:25:12 +00004871 // Handle exception personalities
4872 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4873 options::OPT_fseh_exceptions,
4874 options::OPT_fdwarf_exceptions);
4875 if (A) {
4876 const Option &Opt = A->getOption();
4877 if (Opt.matches(options::OPT_fsjlj_exceptions))
4878 CmdArgs.push_back("-fsjlj-exceptions");
4879 if (Opt.matches(options::OPT_fseh_exceptions))
4880 CmdArgs.push_back("-fseh-exceptions");
4881 if (Opt.matches(options::OPT_fdwarf_exceptions))
4882 CmdArgs.push_back("-fdwarf-exceptions");
4883 } else {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004884 switch (TC.GetExceptionModel(Args)) {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004885 default:
4886 break;
4887 case llvm::ExceptionHandling::DwarfCFI:
4888 CmdArgs.push_back("-fdwarf-exceptions");
4889 break;
4890 case llvm::ExceptionHandling::SjLj:
4891 CmdArgs.push_back("-fsjlj-exceptions");
4892 break;
4893 case llvm::ExceptionHandling::WinEH:
4894 CmdArgs.push_back("-fseh-exceptions");
4895 break;
Martell Malonec950c652017-11-29 07:25:12 +00004896 }
4897 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004898
4899 // C++ "sane" operator new.
4900 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4901 options::OPT_fno_assume_sane_operator_new))
4902 CmdArgs.push_back("-fno-assume-sane-operator-new");
4903
4904 // -frelaxed-template-template-args is off by default, as it is a severe
4905 // breaking change until a corresponding change to template partial ordering
4906 // is provided.
4907 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4908 options::OPT_fno_relaxed_template_template_args, false))
4909 CmdArgs.push_back("-frelaxed-template-template-args");
4910
4911 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4912 // most platforms.
4913 if (Args.hasFlag(options::OPT_fsized_deallocation,
4914 options::OPT_fno_sized_deallocation, false))
4915 CmdArgs.push_back("-fsized-deallocation");
4916
4917 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4918 // by default.
4919 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4920 options::OPT_fno_aligned_allocation,
4921 options::OPT_faligned_new_EQ)) {
4922 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4923 CmdArgs.push_back("-fno-aligned-allocation");
4924 else
4925 CmdArgs.push_back("-faligned-allocation");
4926 }
4927
4928 // The default new alignment can be specified using a dedicated option or via
4929 // a GCC-compatible option that also turns on aligned allocation.
4930 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4931 options::OPT_faligned_new_EQ))
4932 CmdArgs.push_back(
4933 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4934
4935 // -fconstant-cfstrings is default, and may be subject to argument translation
4936 // on Darwin.
4937 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4938 options::OPT_fno_constant_cfstrings) ||
4939 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4940 options::OPT_mno_constant_cfstrings))
4941 CmdArgs.push_back("-fno-constant-cfstrings");
4942
David L. Jonesf561aba2017-03-08 01:02:16 +00004943 // -fno-pascal-strings is default, only pass non-default.
4944 if (Args.hasFlag(options::OPT_fpascal_strings,
4945 options::OPT_fno_pascal_strings, false))
4946 CmdArgs.push_back("-fpascal-strings");
4947
4948 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4949 // -fno-pack-struct doesn't apply to -fpack-struct=.
4950 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4951 std::string PackStructStr = "-fpack-struct=";
4952 PackStructStr += A->getValue();
4953 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4954 } else if (Args.hasFlag(options::OPT_fpack_struct,
4955 options::OPT_fno_pack_struct, false)) {
4956 CmdArgs.push_back("-fpack-struct=1");
4957 }
4958
4959 // Handle -fmax-type-align=N and -fno-type-align
4960 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4961 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4962 if (!SkipMaxTypeAlign) {
4963 std::string MaxTypeAlignStr = "-fmax-type-align=";
4964 MaxTypeAlignStr += A->getValue();
4965 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4966 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004967 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004968 if (!SkipMaxTypeAlign) {
4969 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4970 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4971 }
4972 }
4973
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004974 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4975 CmdArgs.push_back("-Qn");
4976
David L. Jonesf561aba2017-03-08 01:02:16 +00004977 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004978 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004979 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4980 !NoCommonDefault))
4981 CmdArgs.push_back("-fno-common");
4982
4983 // -fsigned-bitfields is default, and clang doesn't yet support
4984 // -funsigned-bitfields.
4985 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4986 options::OPT_funsigned_bitfields))
4987 D.Diag(diag::warn_drv_clang_unsupported)
4988 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4989
4990 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4991 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4992 D.Diag(diag::err_drv_clang_unsupported)
4993 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4994
4995 // -finput_charset=UTF-8 is default. Reject others
4996 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4997 StringRef value = inputCharset->getValue();
4998 if (!value.equals_lower("utf-8"))
4999 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5000 << value;
5001 }
5002
5003 // -fexec_charset=UTF-8 is default. Reject others
5004 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5005 StringRef value = execCharset->getValue();
5006 if (!value.equals_lower("utf-8"))
5007 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5008 << value;
5009 }
5010
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00005011 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005012
5013 // -fno-asm-blocks is default.
5014 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5015 false))
5016 CmdArgs.push_back("-fasm-blocks");
5017
5018 // -fgnu-inline-asm is default.
5019 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5020 options::OPT_fno_gnu_inline_asm, true))
5021 CmdArgs.push_back("-fno-gnu-inline-asm");
5022
5023 // Enable vectorization per default according to the optimization level
5024 // selected. For optimization levels that want vectorization we use the alias
5025 // option to simplify the hasFlag logic.
5026 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5027 OptSpecifier VectorizeAliasOption =
5028 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5029 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5030 options::OPT_fno_vectorize, EnableVec))
5031 CmdArgs.push_back("-vectorize-loops");
5032
5033 // -fslp-vectorize is enabled based on the optimization level selected.
5034 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5035 OptSpecifier SLPVectAliasOption =
5036 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5037 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5038 options::OPT_fno_slp_vectorize, EnableSLPVec))
5039 CmdArgs.push_back("-vectorize-slp");
5040
Craig Topper9a724aa2017-12-11 21:09:19 +00005041 ParseMPreferVectorWidth(D, Args, CmdArgs);
5042
David L. Jonesf561aba2017-03-08 01:02:16 +00005043 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5044 A->render(Args, CmdArgs);
5045
5046 if (Arg *A = Args.getLastArg(
5047 options::OPT_fsanitize_undefined_strip_path_components_EQ))
5048 A->render(Args, CmdArgs);
5049
5050 // -fdollars-in-identifiers default varies depending on platform and
5051 // language; only pass if specified.
5052 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5053 options::OPT_fno_dollars_in_identifiers)) {
5054 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5055 CmdArgs.push_back("-fdollars-in-identifiers");
5056 else
5057 CmdArgs.push_back("-fno-dollars-in-identifiers");
5058 }
5059
5060 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5061 // practical purposes.
5062 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5063 options::OPT_fno_unit_at_a_time)) {
5064 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5065 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5066 }
5067
5068 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5069 options::OPT_fno_apple_pragma_pack, false))
5070 CmdArgs.push_back("-fapple-pragma-pack");
5071
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005072 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
David L. Jonesf561aba2017-03-08 01:02:16 +00005073 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00005074 options::OPT_foptimization_record_file_EQ,
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005075 options::OPT_fno_save_optimization_record, false) ||
5076 Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00005077 options::OPT_fno_save_optimization_record, false)) {
5078 CmdArgs.push_back("-opt-record-file");
5079
5080 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5081 if (A) {
5082 CmdArgs.push_back(A->getValue());
5083 } else {
5084 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00005085
5086 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5087 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5088 F = FinalOutput->getValue();
5089 }
5090
5091 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005092 // Use the input filename.
5093 F = llvm::sys::path::stem(Input.getBaseInput());
5094
5095 // If we're compiling for an offload architecture (i.e. a CUDA device),
5096 // we need to make the file name for the device compilation different
5097 // from the host compilation.
5098 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5099 !JA.isDeviceOffloading(Action::OFK_Host)) {
5100 llvm::sys::path::replace_extension(F, "");
5101 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5102 Triple.normalize());
5103 F += "-";
5104 F += JA.getOffloadingArch();
5105 }
5106 }
5107
5108 llvm::sys::path::replace_extension(F, "opt.yaml");
5109 CmdArgs.push_back(Args.MakeArgString(F));
5110 }
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005111 if (const Arg *A =
5112 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5113 CmdArgs.push_back("-opt-record-passes");
5114 CmdArgs.push_back(A->getValue());
5115 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005116 }
5117
Richard Smith86a3ef52017-06-09 21:24:02 +00005118 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5119 options::OPT_fno_rewrite_imports, false);
5120 if (RewriteImports)
5121 CmdArgs.push_back("-frewrite-imports");
5122
David L. Jonesf561aba2017-03-08 01:02:16 +00005123 // Enable rewrite includes if the user's asked for it or if we're generating
5124 // diagnostics.
5125 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5126 // nice to enable this when doing a crashdump for modules as well.
5127 if (Args.hasFlag(options::OPT_frewrite_includes,
5128 options::OPT_fno_rewrite_includes, false) ||
David Blaikiea99b8e42018-11-15 03:04:19 +00005129 (C.isForDiagnostics() && !HaveModules))
David L. Jonesf561aba2017-03-08 01:02:16 +00005130 CmdArgs.push_back("-frewrite-includes");
5131
5132 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5133 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5134 options::OPT_traditional_cpp)) {
5135 if (isa<PreprocessJobAction>(JA))
5136 CmdArgs.push_back("-traditional-cpp");
5137 else
5138 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5139 }
5140
5141 Args.AddLastArg(CmdArgs, options::OPT_dM);
5142 Args.AddLastArg(CmdArgs, options::OPT_dD);
5143
5144 // Handle serialized diagnostics.
5145 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5146 CmdArgs.push_back("-serialize-diagnostic-file");
5147 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5148 }
5149
5150 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5151 CmdArgs.push_back("-fretain-comments-from-system-headers");
5152
5153 // Forward -fcomment-block-commands to -cc1.
5154 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5155 // Forward -fparse-all-comments to -cc1.
5156 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5157
5158 // Turn -fplugin=name.so into -load name.so
5159 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5160 CmdArgs.push_back("-load");
5161 CmdArgs.push_back(A->getValue());
5162 A->claim();
5163 }
5164
Philip Pfaffee3f105c2019-02-02 23:19:32 +00005165 // Forward -fpass-plugin=name.so to -cc1.
5166 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5167 CmdArgs.push_back(
5168 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5169 A->claim();
5170 }
5171
David L. Jonesf561aba2017-03-08 01:02:16 +00005172 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00005173 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5174 if (!StatsFile.empty())
5175 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00005176
5177 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5178 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00005179 // -finclude-default-header flag is for preprocessor,
5180 // do not pass it to other cc1 commands when save-temps is enabled
5181 if (C.getDriver().isSaveTempsEnabled() &&
5182 !isa<PreprocessJobAction>(JA)) {
5183 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5184 Arg->claim();
5185 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5186 CmdArgs.push_back(Arg->getValue());
5187 }
5188 }
5189 else {
5190 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5191 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005192 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5193 A->claim();
5194
5195 // We translate this by hand to the -cc1 argument, since nightly test uses
5196 // it and developers have been trained to spell it with -mllvm. Both
5197 // spellings are now deprecated and should be removed.
5198 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5199 CmdArgs.push_back("-disable-llvm-optzns");
5200 } else {
5201 A->render(Args, CmdArgs);
5202 }
5203 }
5204
5205 // With -save-temps, we want to save the unoptimized bitcode output from the
5206 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5207 // by the frontend.
5208 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5209 // has slightly different breakdown between stages.
5210 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5211 // pristine IR generated by the frontend. Ideally, a new compile action should
5212 // be added so both IR can be captured.
5213 if (C.getDriver().isSaveTempsEnabled() &&
5214 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5215 isa<CompileJobAction>(JA))
5216 CmdArgs.push_back("-disable-llvm-passes");
5217
David L. Jonesf561aba2017-03-08 01:02:16 +00005218 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5219
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00005220 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00005221
Scott Linderde6beb02018-12-14 15:38:15 +00005222 // Optionally embed the -cc1 level arguments into the debug info or a
5223 // section, for build analysis.
Eric Christopherca325172017-03-29 23:34:20 +00005224 // Also record command line arguments into the debug info if
5225 // -grecord-gcc-switches options is set on.
5226 // By default, -gno-record-gcc-switches is set on and no recording.
Scott Linderde6beb02018-12-14 15:38:15 +00005227 auto GRecordSwitches =
5228 Args.hasFlag(options::OPT_grecord_command_line,
5229 options::OPT_gno_record_command_line, false);
5230 auto FRecordSwitches =
5231 Args.hasFlag(options::OPT_frecord_command_line,
5232 options::OPT_fno_record_command_line, false);
5233 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5234 D.Diag(diag::err_drv_unsupported_opt_for_target)
5235 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5236 << TripleStr;
5237 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005238 ArgStringList OriginalArgs;
5239 for (const auto &Arg : Args)
5240 Arg->render(Args, OriginalArgs);
5241
5242 SmallString<256> Flags;
5243 Flags += Exec;
5244 for (const char *OriginalArg : OriginalArgs) {
5245 SmallString<128> EscapedArg;
5246 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5247 Flags += " ";
5248 Flags += EscapedArg;
5249 }
Scott Linderde6beb02018-12-14 15:38:15 +00005250 auto FlagsArgString = Args.MakeArgString(Flags);
5251 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5252 CmdArgs.push_back("-dwarf-debug-flags");
5253 CmdArgs.push_back(FlagsArgString);
5254 }
5255 if (FRecordSwitches) {
5256 CmdArgs.push_back("-record-command-line");
5257 CmdArgs.push_back(FlagsArgString);
5258 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005259 }
5260
Yaxun Liu97670892018-10-02 17:48:54 +00005261 // Host-side cuda compilation receives all device-side outputs in a single
5262 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5263 if ((IsCuda || IsHIP) && CudaDeviceInput) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00005264 CmdArgs.push_back("-fcuda-include-gpubinary");
Richard Smithcd35eff2018-09-15 01:21:16 +00005265 CmdArgs.push_back(CudaDeviceInput->getFilename());
Yaxun Liu97670892018-10-02 17:48:54 +00005266 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5267 CmdArgs.push_back("-fgpu-rdc");
5268 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005269
Yaxun Liu97670892018-10-02 17:48:54 +00005270 if (IsCuda) {
Artem Belevich679dafe2018-05-09 23:10:09 +00005271 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5272 options::OPT_fno_cuda_short_ptr, false))
5273 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00005274 }
5275
David L. Jonesf561aba2017-03-08 01:02:16 +00005276 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5277 // to specify the result of the compile phase on the host, so the meaningful
5278 // device declarations can be identified. Also, -fopenmp-is-device is passed
5279 // along to tell the frontend that it is generating code for a device, so that
5280 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005281 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005282 CmdArgs.push_back("-fopenmp-is-device");
Richard Smithcd35eff2018-09-15 01:21:16 +00005283 if (OpenMPDeviceInput) {
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005284 CmdArgs.push_back("-fopenmp-host-ir-file-path");
Richard Smithcd35eff2018-09-15 01:21:16 +00005285 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005286 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005287 }
5288
5289 // For all the host OpenMP offloading compile jobs we need to pass the targets
5290 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00005291 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005292 SmallString<128> TargetInfo("-fopenmp-targets=");
5293
5294 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5295 assert(Tgts && Tgts->getNumValues() &&
5296 "OpenMP offloading has to have targets specified.");
5297 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5298 if (i)
5299 TargetInfo += ',';
5300 // We need to get the string from the triple because it may be not exactly
5301 // the same as the one we get directly from the arguments.
5302 llvm::Triple T(Tgts->getValue(i));
5303 TargetInfo += T.getTriple();
5304 }
5305 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5306 }
5307
5308 bool WholeProgramVTables =
5309 Args.hasFlag(options::OPT_fwhole_program_vtables,
5310 options::OPT_fno_whole_program_vtables, false);
5311 if (WholeProgramVTables) {
5312 if (!D.isUsingLTO())
5313 D.Diag(diag::err_drv_argument_only_allowed_with)
5314 << "-fwhole-program-vtables"
5315 << "-flto";
5316 CmdArgs.push_back("-fwhole-program-vtables");
5317 }
5318
Teresa Johnson84cecfc2019-01-11 18:32:07 +00005319 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5320 bool SplitLTOUnit =
5321 Args.hasFlag(options::OPT_fsplit_lto_unit,
5322 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5323 if (RequiresSplitLTOUnit && !SplitLTOUnit)
5324 D.Diag(diag::err_drv_argument_not_allowed_with)
5325 << "-fno-split-lto-unit"
5326 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5327 if (SplitLTOUnit)
5328 CmdArgs.push_back("-fsplit-lto-unit");
5329
Amara Emerson4ee9f822018-01-26 00:27:22 +00005330 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5331 options::OPT_fno_experimental_isel)) {
5332 CmdArgs.push_back("-mllvm");
5333 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5334 CmdArgs.push_back("-global-isel=1");
5335
5336 // GISel is on by default on AArch64 -O0, so don't bother adding
5337 // the fallback remarks for it. Other combinations will add a warning of
5338 // some kind.
5339 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5340 bool IsOptLevelSupported = false;
5341
5342 Arg *A = Args.getLastArg(options::OPT_O_Group);
5343 if (Triple.getArch() == llvm::Triple::aarch64) {
5344 if (!A || A->getOption().matches(options::OPT_O0))
5345 IsOptLevelSupported = true;
5346 }
5347 if (!IsArchSupported || !IsOptLevelSupported) {
5348 CmdArgs.push_back("-mllvm");
5349 CmdArgs.push_back("-global-isel-abort=2");
5350
5351 if (!IsArchSupported)
5352 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5353 else
5354 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5355 }
5356 } else {
5357 CmdArgs.push_back("-global-isel=0");
5358 }
5359 }
5360
Manman Ren394d4cc2019-03-04 20:30:30 +00005361 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5362 CmdArgs.push_back("-forder-file-instrumentation");
5363 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5364 // on, we need to pass these flags as linker flags and that will be handled
5365 // outside of the compiler.
5366 if (!D.isUsingLTO()) {
5367 CmdArgs.push_back("-mllvm");
5368 CmdArgs.push_back("-enable-order-file-instrumentation");
5369 }
5370 }
5371
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00005372 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5373 options::OPT_fno_force_enable_int128)) {
5374 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5375 CmdArgs.push_back("-fforce-enable-int128");
5376 }
5377
Peter Collingbourne54d13b42018-05-30 03:40:04 +00005378 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5379 options::OPT_fno_complete_member_pointers, false))
5380 CmdArgs.push_back("-fcomplete-member-pointers");
5381
Erik Pilkington5a559e62018-08-21 17:24:06 +00005382 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5383 options::OPT_fno_cxx_static_destructors, true))
5384 CmdArgs.push_back("-fno-c++-static-destructors");
5385
Jessica Paquette36a25672018-06-29 18:06:10 +00005386 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5387 options::OPT_mno_outline)) {
5388 if (A->getOption().matches(options::OPT_moutline)) {
5389 // We only support -moutline in AArch64 right now. If we're not compiling
5390 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5391 // proper mllvm flags.
5392 if (Triple.getArch() != llvm::Triple::aarch64) {
5393 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5394 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00005395 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00005396 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005397 }
Jessica Paquette36a25672018-06-29 18:06:10 +00005398 } else {
5399 // Disable all outlining behaviour.
5400 CmdArgs.push_back("-mllvm");
5401 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005402 }
5403 }
5404
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005405 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00005406 (TC.getTriple().isOSBinFormatELF() ||
5407 TC.getTriple().isOSBinFormatCOFF()) &&
Douglas Yung25f04772018-12-19 22:45:26 +00005408 !TC.getTriple().isPS4() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005409 !TC.getTriple().isOSNetBSD() &&
Michal Gornydae01c32018-12-23 15:07:26 +00005410 !Distro(D.getVFS()).IsGentoo() &&
Dan Albertdd142342019-01-08 22:33:59 +00005411 !TC.getTriple().isAndroid() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005412 TC.useIntegratedAs()))
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005413 CmdArgs.push_back("-faddrsig");
5414
Reid Kleckner549ed542019-05-23 18:35:43 +00005415 // Add the "-o out -x type src.c" flags last. This is done primarily to make
5416 // the -cc1 command easier to edit when reproducing compiler crashes.
5417 if (Output.getType() == types::TY_Dependencies) {
5418 // Handled with other dependency code.
5419 } else if (Output.isFilename()) {
5420 CmdArgs.push_back("-o");
5421 CmdArgs.push_back(Output.getFilename());
5422 } else {
5423 assert(Output.isNothing() && "Invalid output.");
5424 }
5425
5426 addDashXForInput(Args, Input, CmdArgs);
5427
5428 ArrayRef<InputInfo> FrontendInputs = Input;
5429 if (IsHeaderModulePrecompile)
5430 FrontendInputs = ModuleHeaderInputs;
5431 else if (Input.isNothing())
5432 FrontendInputs = {};
5433
5434 for (const InputInfo &Input : FrontendInputs) {
5435 if (Input.isFilename())
5436 CmdArgs.push_back(Input.getFilename());
5437 else
5438 Input.getInputArg().renderAsInput(Args, CmdArgs);
5439 }
5440
David L. Jonesf561aba2017-03-08 01:02:16 +00005441 // Finally add the compile command to the compilation.
5442 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5443 Output.getType() == types::TY_Object &&
5444 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5445 auto CLCommand =
5446 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5447 C.addCommand(llvm::make_unique<FallbackCommand>(
5448 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5449 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5450 isa<PrecompileJobAction>(JA)) {
5451 // In /fallback builds, run the main compilation even if the pch generation
5452 // fails, so that the main compilation's fallback to cl.exe runs.
5453 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5454 CmdArgs, Inputs));
5455 } else {
5456 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5457 }
5458
Hans Wennborg2fe01042018-10-13 19:13:14 +00005459 // Make the compile command echo its inputs for /showFilenames.
5460 if (Output.getType() == types::TY_Object &&
5461 Args.hasFlag(options::OPT__SLASH_showFilenames,
5462 options::OPT__SLASH_showFilenames_, false)) {
5463 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5464 }
5465
David L. Jonesf561aba2017-03-08 01:02:16 +00005466 if (Arg *A = Args.getLastArg(options::OPT_pg))
David Blaikie5941da32018-09-18 20:11:45 +00005467 if (!shouldUseFramePointer(Args, Triple))
David L. Jonesf561aba2017-03-08 01:02:16 +00005468 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5469 << A->getAsString(Args);
5470
5471 // Claim some arguments which clang supports automatically.
5472
5473 // -fpch-preprocess is used with gcc to add a special marker in the output to
Erich Keane0a6b5b62018-12-04 14:34:09 +00005474 // include the PCH file.
David L. Jonesf561aba2017-03-08 01:02:16 +00005475 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5476
5477 // Claim some arguments which clang doesn't support, but we don't
5478 // care to warn the user about.
5479 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5480 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5481
5482 // Disable warnings for clang -E -emit-llvm foo.c
5483 Args.ClaimAllArgs(options::OPT_emit_llvm);
5484}
5485
5486Clang::Clang(const ToolChain &TC)
5487 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5488 // as it is for other tools. Some operations on a Tool actually test
5489 // whether that tool is Clang based on the Tool's Name as a string.
5490 : Tool("clang", "clang frontend", TC, RF_Full) {}
5491
5492Clang::~Clang() {}
5493
5494/// Add options related to the Objective-C runtime/ABI.
5495///
5496/// Returns true if the runtime is non-fragile.
5497ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5498 ArgStringList &cmdArgs,
5499 RewriteKind rewriteKind) const {
5500 // Look for the controlling runtime option.
5501 Arg *runtimeArg =
5502 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5503 options::OPT_fobjc_runtime_EQ);
5504
5505 // Just forward -fobjc-runtime= to the frontend. This supercedes
5506 // options about fragility.
5507 if (runtimeArg &&
5508 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5509 ObjCRuntime runtime;
5510 StringRef value = runtimeArg->getValue();
5511 if (runtime.tryParse(value)) {
5512 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5513 << value;
5514 }
David Chisnall404bbcb2018-05-22 10:13:06 +00005515 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5516 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnallef16ea72018-09-04 10:07:27 +00005517 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5518 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00005519 getToolChain().getDriver().Diag(
5520 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5521 << runtime.getVersion().getMajor();
5522 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005523
5524 runtimeArg->render(args, cmdArgs);
5525 return runtime;
5526 }
5527
5528 // Otherwise, we'll need the ABI "version". Version numbers are
5529 // slightly confusing for historical reasons:
5530 // 1 - Traditional "fragile" ABI
5531 // 2 - Non-fragile ABI, version 1
5532 // 3 - Non-fragile ABI, version 2
5533 unsigned objcABIVersion = 1;
5534 // If -fobjc-abi-version= is present, use that to set the version.
5535 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5536 StringRef value = abiArg->getValue();
5537 if (value == "1")
5538 objcABIVersion = 1;
5539 else if (value == "2")
5540 objcABIVersion = 2;
5541 else if (value == "3")
5542 objcABIVersion = 3;
5543 else
5544 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5545 } else {
5546 // Otherwise, determine if we are using the non-fragile ABI.
5547 bool nonFragileABIIsDefault =
5548 (rewriteKind == RK_NonFragile ||
5549 (rewriteKind == RK_None &&
5550 getToolChain().IsObjCNonFragileABIDefault()));
5551 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5552 options::OPT_fno_objc_nonfragile_abi,
5553 nonFragileABIIsDefault)) {
5554// Determine the non-fragile ABI version to use.
5555#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5556 unsigned nonFragileABIVersion = 1;
5557#else
5558 unsigned nonFragileABIVersion = 2;
5559#endif
5560
5561 if (Arg *abiArg =
5562 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5563 StringRef value = abiArg->getValue();
5564 if (value == "1")
5565 nonFragileABIVersion = 1;
5566 else if (value == "2")
5567 nonFragileABIVersion = 2;
5568 else
5569 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5570 << value;
5571 }
5572
5573 objcABIVersion = 1 + nonFragileABIVersion;
5574 } else {
5575 objcABIVersion = 1;
5576 }
5577 }
5578
5579 // We don't actually care about the ABI version other than whether
5580 // it's non-fragile.
5581 bool isNonFragile = objcABIVersion != 1;
5582
5583 // If we have no runtime argument, ask the toolchain for its default runtime.
5584 // However, the rewriter only really supports the Mac runtime, so assume that.
5585 ObjCRuntime runtime;
5586 if (!runtimeArg) {
5587 switch (rewriteKind) {
5588 case RK_None:
5589 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5590 break;
5591 case RK_Fragile:
5592 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5593 break;
5594 case RK_NonFragile:
5595 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5596 break;
5597 }
5598
5599 // -fnext-runtime
5600 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5601 // On Darwin, make this use the default behavior for the toolchain.
5602 if (getToolChain().getTriple().isOSDarwin()) {
5603 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5604
5605 // Otherwise, build for a generic macosx port.
5606 } else {
5607 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5608 }
5609
5610 // -fgnu-runtime
5611 } else {
5612 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5613 // Legacy behaviour is to target the gnustep runtime if we are in
5614 // non-fragile mode or the GCC runtime in fragile mode.
5615 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005616 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005617 else
5618 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5619 }
5620
5621 cmdArgs.push_back(
5622 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5623 return runtime;
5624}
5625
5626static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5627 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5628 I += HaveDash;
5629 return !HaveDash;
5630}
5631
5632namespace {
5633struct EHFlags {
5634 bool Synch = false;
5635 bool Asynch = false;
5636 bool NoUnwindC = false;
5637};
5638} // end anonymous namespace
5639
5640/// /EH controls whether to run destructor cleanups when exceptions are
5641/// thrown. There are three modifiers:
5642/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5643/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5644/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5645/// - c: Assume that extern "C" functions are implicitly nounwind.
5646/// The default is /EHs-c-, meaning cleanups are disabled.
5647static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5648 EHFlags EH;
5649
5650 std::vector<std::string> EHArgs =
5651 Args.getAllArgValues(options::OPT__SLASH_EH);
5652 for (auto EHVal : EHArgs) {
5653 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5654 switch (EHVal[I]) {
5655 case 'a':
5656 EH.Asynch = maybeConsumeDash(EHVal, I);
5657 if (EH.Asynch)
5658 EH.Synch = false;
5659 continue;
5660 case 'c':
5661 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5662 continue;
5663 case 's':
5664 EH.Synch = maybeConsumeDash(EHVal, I);
5665 if (EH.Synch)
5666 EH.Asynch = false;
5667 continue;
5668 default:
5669 break;
5670 }
5671 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5672 break;
5673 }
5674 }
5675 // The /GX, /GX- flags are only processed if there are not /EH flags.
5676 // The default is that /GX is not specified.
5677 if (EHArgs.empty() &&
5678 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5679 /*default=*/false)) {
5680 EH.Synch = true;
5681 EH.NoUnwindC = true;
5682 }
5683
5684 return EH;
5685}
5686
5687void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5688 ArgStringList &CmdArgs,
5689 codegenoptions::DebugInfoKind *DebugInfoKind,
5690 bool *EmitCodeView) const {
5691 unsigned RTOptionID = options::OPT__SLASH_MT;
5692
5693 if (Args.hasArg(options::OPT__SLASH_LDd))
5694 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5695 // but defining _DEBUG is sticky.
5696 RTOptionID = options::OPT__SLASH_MTd;
5697
5698 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5699 RTOptionID = A->getOption().getID();
5700
5701 StringRef FlagForCRT;
5702 switch (RTOptionID) {
5703 case options::OPT__SLASH_MD:
5704 if (Args.hasArg(options::OPT__SLASH_LDd))
5705 CmdArgs.push_back("-D_DEBUG");
5706 CmdArgs.push_back("-D_MT");
5707 CmdArgs.push_back("-D_DLL");
5708 FlagForCRT = "--dependent-lib=msvcrt";
5709 break;
5710 case options::OPT__SLASH_MDd:
5711 CmdArgs.push_back("-D_DEBUG");
5712 CmdArgs.push_back("-D_MT");
5713 CmdArgs.push_back("-D_DLL");
5714 FlagForCRT = "--dependent-lib=msvcrtd";
5715 break;
5716 case options::OPT__SLASH_MT:
5717 if (Args.hasArg(options::OPT__SLASH_LDd))
5718 CmdArgs.push_back("-D_DEBUG");
5719 CmdArgs.push_back("-D_MT");
5720 CmdArgs.push_back("-flto-visibility-public-std");
5721 FlagForCRT = "--dependent-lib=libcmt";
5722 break;
5723 case options::OPT__SLASH_MTd:
5724 CmdArgs.push_back("-D_DEBUG");
5725 CmdArgs.push_back("-D_MT");
5726 CmdArgs.push_back("-flto-visibility-public-std");
5727 FlagForCRT = "--dependent-lib=libcmtd";
5728 break;
5729 default:
5730 llvm_unreachable("Unexpected option ID.");
5731 }
5732
5733 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5734 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5735 } else {
5736 CmdArgs.push_back(FlagForCRT.data());
5737
5738 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5739 // users want. The /Za flag to cl.exe turns this off, but it's not
5740 // implemented in clang.
5741 CmdArgs.push_back("--dependent-lib=oldnames");
5742 }
5743
Erich Keane425f48d2018-05-04 15:58:31 +00005744 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5745 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005746
5747 // This controls whether or not we emit RTTI data for polymorphic types.
5748 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5749 /*default=*/false))
5750 CmdArgs.push_back("-fno-rtti-data");
5751
5752 // This controls whether or not we emit stack-protector instrumentation.
5753 // In MSVC, Buffer Security Check (/GS) is on by default.
5754 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5755 /*default=*/true)) {
5756 CmdArgs.push_back("-stack-protector");
5757 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5758 }
5759
5760 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5761 if (Arg *DebugInfoArg =
5762 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5763 options::OPT_gline_tables_only)) {
5764 *EmitCodeView = true;
5765 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5766 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5767 else
5768 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +00005769 } else {
5770 *EmitCodeView = false;
5771 }
5772
5773 const Driver &D = getToolChain().getDriver();
5774 EHFlags EH = parseClangCLEHFlags(D, Args);
5775 if (EH.Synch || EH.Asynch) {
5776 if (types::isCXX(InputType))
5777 CmdArgs.push_back("-fcxx-exceptions");
5778 CmdArgs.push_back("-fexceptions");
5779 }
5780 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5781 CmdArgs.push_back("-fexternc-nounwind");
5782
5783 // /EP should expand to -E -P.
5784 if (Args.hasArg(options::OPT__SLASH_EP)) {
5785 CmdArgs.push_back("-E");
5786 CmdArgs.push_back("-P");
5787 }
5788
5789 unsigned VolatileOptionID;
5790 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5791 getToolChain().getArch() == llvm::Triple::x86)
5792 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5793 else
5794 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5795
5796 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5797 VolatileOptionID = A->getOption().getID();
5798
5799 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5800 CmdArgs.push_back("-fms-volatile");
5801
Takuto Ikuta302c6432018-11-03 06:45:00 +00005802 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5803 options::OPT__SLASH_Zc_dllexportInlines,
Takuto Ikuta245d9472018-11-13 04:14:09 +00005804 false)) {
5805 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5806 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5807 } else {
Takuto Ikuta302c6432018-11-03 06:45:00 +00005808 CmdArgs.push_back("-fno-dllexport-inlines");
Takuto Ikuta245d9472018-11-13 04:14:09 +00005809 }
5810 }
Takuto Ikuta302c6432018-11-03 06:45:00 +00005811
David L. Jonesf561aba2017-03-08 01:02:16 +00005812 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5813 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5814 if (MostGeneralArg && BestCaseArg)
5815 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5816 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5817
5818 if (MostGeneralArg) {
5819 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5820 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5821 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5822
5823 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5824 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5825 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5826 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5827 << FirstConflict->getAsString(Args)
5828 << SecondConflict->getAsString(Args);
5829
5830 if (SingleArg)
5831 CmdArgs.push_back("-fms-memptr-rep=single");
5832 else if (MultipleArg)
5833 CmdArgs.push_back("-fms-memptr-rep=multiple");
5834 else
5835 CmdArgs.push_back("-fms-memptr-rep=virtual");
5836 }
5837
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005838 // Parse the default calling convention options.
5839 if (Arg *CCArg =
5840 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005841 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5842 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005843 unsigned DCCOptId = CCArg->getOption().getID();
5844 const char *DCCFlag = nullptr;
5845 bool ArchSupported = true;
5846 llvm::Triple::ArchType Arch = getToolChain().getArch();
5847 switch (DCCOptId) {
5848 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005849 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005850 break;
5851 case options::OPT__SLASH_Gr:
5852 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005853 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005854 break;
5855 case options::OPT__SLASH_Gz:
5856 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005857 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005858 break;
5859 case options::OPT__SLASH_Gv:
5860 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005861 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005862 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005863 case options::OPT__SLASH_Gregcall:
5864 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5865 DCCFlag = "-fdefault-calling-conv=regcall";
5866 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005867 }
5868
5869 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5870 if (ArchSupported && DCCFlag)
5871 CmdArgs.push_back(DCCFlag);
5872 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005873
5874 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5875 A->render(Args, CmdArgs);
5876
5877 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5878 CmdArgs.push_back("-fdiagnostics-format");
5879 if (Args.hasArg(options::OPT__SLASH_fallback))
5880 CmdArgs.push_back("msvc-fallback");
5881 else
5882 CmdArgs.push_back("msvc");
5883 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005884
Hans Wennborga912e3e2018-08-10 09:49:21 +00005885 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5886 SmallVector<StringRef, 1> SplitArgs;
5887 StringRef(A->getValue()).split(SplitArgs, ",");
5888 bool Instrument = false;
5889 bool NoChecks = false;
5890 for (StringRef Arg : SplitArgs) {
5891 if (Arg.equals_lower("cf"))
5892 Instrument = true;
5893 else if (Arg.equals_lower("cf-"))
5894 Instrument = false;
5895 else if (Arg.equals_lower("nochecks"))
5896 NoChecks = true;
5897 else if (Arg.equals_lower("nochecks-"))
5898 NoChecks = false;
5899 else
5900 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5901 }
5902 // Currently there's no support emitting CFG instrumentation; the flag only
5903 // emits the table of address-taken functions.
5904 if (Instrument || NoChecks)
5905 CmdArgs.push_back("-cfguard");
5906 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005907}
5908
5909visualstudio::Compiler *Clang::getCLFallback() const {
5910 if (!CLFallback)
5911 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5912 return CLFallback.get();
5913}
5914
5915
5916const char *Clang::getBaseInputName(const ArgList &Args,
5917 const InputInfo &Input) {
5918 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5919}
5920
5921const char *Clang::getBaseInputStem(const ArgList &Args,
5922 const InputInfoList &Inputs) {
5923 const char *Str = getBaseInputName(Args, Inputs[0]);
5924
5925 if (const char *End = strrchr(Str, '.'))
5926 return Args.MakeArgString(std::string(Str, End));
5927
5928 return Str;
5929}
5930
5931const char *Clang::getDependencyFileName(const ArgList &Args,
5932 const InputInfoList &Inputs) {
5933 // FIXME: Think about this more.
5934 std::string Res;
5935
5936 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5937 std::string Str(OutputOpt->getValue());
5938 Res = Str.substr(0, Str.rfind('.'));
5939 } else {
5940 Res = getBaseInputStem(Args, Inputs);
5941 }
5942 return Args.MakeArgString(Res + ".d");
5943}
5944
5945// Begin ClangAs
5946
5947void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5948 ArgStringList &CmdArgs) const {
5949 StringRef CPUName;
5950 StringRef ABIName;
5951 const llvm::Triple &Triple = getToolChain().getTriple();
5952 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5953
5954 CmdArgs.push_back("-target-abi");
5955 CmdArgs.push_back(ABIName.data());
5956}
5957
5958void ClangAs::AddX86TargetArgs(const ArgList &Args,
5959 ArgStringList &CmdArgs) const {
5960 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5961 StringRef Value = A->getValue();
5962 if (Value == "intel" || Value == "att") {
5963 CmdArgs.push_back("-mllvm");
5964 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5965 } else {
5966 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5967 << A->getOption().getName() << Value;
5968 }
5969 }
5970}
5971
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00005972void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
5973 ArgStringList &CmdArgs) const {
5974 const llvm::Triple &Triple = getToolChain().getTriple();
5975 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
5976
5977 CmdArgs.push_back("-target-abi");
5978 CmdArgs.push_back(ABIName.data());
5979}
5980
David L. Jonesf561aba2017-03-08 01:02:16 +00005981void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5982 const InputInfo &Output, const InputInfoList &Inputs,
5983 const ArgList &Args,
5984 const char *LinkingOutput) const {
5985 ArgStringList CmdArgs;
5986
5987 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5988 const InputInfo &Input = Inputs[0];
5989
Martin Storsjob547ef22018-10-26 08:33:29 +00005990 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00005991 const std::string &TripleStr = Triple.getTriple();
Martin Storsjob547ef22018-10-26 08:33:29 +00005992 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005993
5994 // Don't warn about "clang -w -c foo.s"
5995 Args.ClaimAllArgs(options::OPT_w);
5996 // and "clang -emit-llvm -c foo.s"
5997 Args.ClaimAllArgs(options::OPT_emit_llvm);
5998
5999 claimNoWarnArgs(Args);
6000
6001 // Invoke ourselves in -cc1as mode.
6002 //
6003 // FIXME: Implement custom jobs for internal actions.
6004 CmdArgs.push_back("-cc1as");
6005
6006 // Add the "effective" target triple.
6007 CmdArgs.push_back("-triple");
6008 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6009
6010 // Set the output mode, we currently only expect to be used as a real
6011 // assembler.
6012 CmdArgs.push_back("-filetype");
6013 CmdArgs.push_back("obj");
6014
6015 // Set the main file name, so that debug info works even with
6016 // -save-temps or preprocessed assembly.
6017 CmdArgs.push_back("-main-file-name");
6018 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6019
6020 // Add the target cpu
6021 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6022 if (!CPU.empty()) {
6023 CmdArgs.push_back("-target-cpu");
6024 CmdArgs.push_back(Args.MakeArgString(CPU));
6025 }
6026
6027 // Add the target features
6028 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6029
6030 // Ignore explicit -force_cpusubtype_ALL option.
6031 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6032
6033 // Pass along any -I options so we get proper .include search paths.
6034 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6035
6036 // Determine the original source input.
6037 const Action *SourceAction = &JA;
6038 while (SourceAction->getKind() != Action::InputClass) {
6039 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6040 SourceAction = SourceAction->getInputs()[0];
6041 }
6042
6043 // Forward -g and handle debug info related flags, assuming we are dealing
6044 // with an actual assembly file.
6045 bool WantDebug = false;
6046 unsigned DwarfVersion = 0;
6047 Args.ClaimAllArgs(options::OPT_g_Group);
6048 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6049 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6050 !A->getOption().matches(options::OPT_ggdb0);
6051 if (WantDebug)
6052 DwarfVersion = DwarfVersionNum(A->getSpelling());
6053 }
6054 if (DwarfVersion == 0)
6055 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6056
6057 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6058
6059 if (SourceAction->getType() == types::TY_Asm ||
6060 SourceAction->getType() == types::TY_PP_Asm) {
6061 // You might think that it would be ok to set DebugInfoKind outside of
6062 // the guard for source type, however there is a test which asserts
6063 // that some assembler invocation receives no -debug-info-kind,
6064 // and it's not clear whether that test is just overly restrictive.
6065 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6066 : codegenoptions::NoDebugInfo);
6067 // Add the -fdebug-compilation-dir flag if needed.
6068 addDebugCompDirArg(Args, CmdArgs);
6069
Paul Robinson9b292b42018-07-10 15:15:24 +00006070 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6071
David L. Jonesf561aba2017-03-08 01:02:16 +00006072 // Set the AT_producer to the clang version when using the integrated
6073 // assembler on assembly source files.
6074 CmdArgs.push_back("-dwarf-debug-producer");
6075 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6076
6077 // And pass along -I options
6078 Args.AddAllArgs(CmdArgs, options::OPT_I);
6079 }
6080 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6081 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00006082 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00006083
David L. Jonesf561aba2017-03-08 01:02:16 +00006084
6085 // Handle -fPIC et al -- the relocation-model affects the assembler
6086 // for some targets.
6087 llvm::Reloc::Model RelocationModel;
6088 unsigned PICLevel;
6089 bool IsPIE;
6090 std::tie(RelocationModel, PICLevel, IsPIE) =
6091 ParsePICArgs(getToolChain(), Args);
6092
6093 const char *RMName = RelocationModelName(RelocationModel);
6094 if (RMName) {
6095 CmdArgs.push_back("-mrelocation-model");
6096 CmdArgs.push_back(RMName);
6097 }
6098
6099 // Optionally embed the -cc1as level arguments into the debug info, for build
6100 // analysis.
6101 if (getToolChain().UseDwarfDebugFlags()) {
6102 ArgStringList OriginalArgs;
6103 for (const auto &Arg : Args)
6104 Arg->render(Args, OriginalArgs);
6105
6106 SmallString<256> Flags;
6107 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6108 Flags += Exec;
6109 for (const char *OriginalArg : OriginalArgs) {
6110 SmallString<128> EscapedArg;
6111 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6112 Flags += " ";
6113 Flags += EscapedArg;
6114 }
6115 CmdArgs.push_back("-dwarf-debug-flags");
6116 CmdArgs.push_back(Args.MakeArgString(Flags));
6117 }
6118
6119 // FIXME: Add -static support, once we have it.
6120
6121 // Add target specific flags.
6122 switch (getToolChain().getArch()) {
6123 default:
6124 break;
6125
6126 case llvm::Triple::mips:
6127 case llvm::Triple::mipsel:
6128 case llvm::Triple::mips64:
6129 case llvm::Triple::mips64el:
6130 AddMIPSTargetArgs(Args, CmdArgs);
6131 break;
6132
6133 case llvm::Triple::x86:
6134 case llvm::Triple::x86_64:
6135 AddX86TargetArgs(Args, CmdArgs);
6136 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00006137
6138 case llvm::Triple::arm:
6139 case llvm::Triple::armeb:
6140 case llvm::Triple::thumb:
6141 case llvm::Triple::thumbeb:
6142 // This isn't in AddARMTargetArgs because we want to do this for assembly
6143 // only, not C/C++.
6144 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6145 options::OPT_mno_default_build_attributes, true)) {
6146 CmdArgs.push_back("-mllvm");
6147 CmdArgs.push_back("-arm-add-build-attributes");
6148 }
6149 break;
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006150
6151 case llvm::Triple::riscv32:
6152 case llvm::Triple::riscv64:
6153 AddRISCVTargetArgs(Args, CmdArgs);
6154 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00006155 }
6156
6157 // Consume all the warning flags. Usually this would be handled more
6158 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6159 // doesn't handle that so rather than warning about unused flags that are
6160 // actually used, we'll lie by omission instead.
6161 // FIXME: Stop lying and consume only the appropriate driver flags
6162 Args.ClaimAllArgs(options::OPT_W_Group);
6163
6164 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6165 getToolChain().getDriver());
6166
6167 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6168
6169 assert(Output.isFilename() && "Unexpected lipo output.");
6170 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00006171 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006172
Petr Hosekd3265352018-10-15 21:30:32 +00006173 const llvm::Triple &T = getToolChain().getTriple();
George Rimar91829ee2018-11-14 09:22:16 +00006174 Arg *A;
Fangrui Songee957e02019-03-28 08:24:00 +00006175 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6176 T.isOSBinFormatELF()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00006177 CmdArgs.push_back("-split-dwarf-file");
George Rimar36d71da2019-03-27 11:00:03 +00006178 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
Peter Collingbourne91d02842018-05-22 18:52:37 +00006179 }
6180
David L. Jonesf561aba2017-03-08 01:02:16 +00006181 assert(Input.isFilename() && "Invalid input.");
Martin Storsjob547ef22018-10-26 08:33:29 +00006182 CmdArgs.push_back(Input.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006183
6184 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6185 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00006186}
6187
6188// Begin OffloadBundler
6189
6190void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6191 const InputInfo &Output,
6192 const InputInfoList &Inputs,
6193 const llvm::opt::ArgList &TCArgs,
6194 const char *LinkingOutput) const {
6195 // The version with only one output is expected to refer to a bundling job.
6196 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6197
6198 // The bundling command looks like this:
6199 // clang-offload-bundler -type=bc
6200 // -targets=host-triple,openmp-triple1,openmp-triple2
6201 // -outputs=input_file
6202 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6203
6204 ArgStringList CmdArgs;
6205
6206 // Get the type.
6207 CmdArgs.push_back(TCArgs.MakeArgString(
6208 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6209
6210 assert(JA.getInputs().size() == Inputs.size() &&
6211 "Not have inputs for all dependence actions??");
6212
6213 // Get the targets.
6214 SmallString<128> Triples;
6215 Triples += "-targets=";
6216 for (unsigned I = 0; I < Inputs.size(); ++I) {
6217 if (I)
6218 Triples += ',';
6219
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006220 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00006221 Action::OffloadKind CurKind = Action::OFK_Host;
6222 const ToolChain *CurTC = &getToolChain();
6223 const Action *CurDep = JA.getInputs()[I];
6224
6225 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006226 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00006227 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006228 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00006229 CurKind = A->getOffloadingDeviceKind();
6230 CurTC = TC;
6231 });
6232 }
6233 Triples += Action::GetOffloadKindName(CurKind);
6234 Triples += '-';
6235 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006236 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6237 Triples += '-';
6238 Triples += CurDep->getOffloadingArch();
6239 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006240 }
6241 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6242
6243 // Get bundled file command.
6244 CmdArgs.push_back(
6245 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6246
6247 // Get unbundled files command.
6248 SmallString<128> UB;
6249 UB += "-inputs=";
6250 for (unsigned I = 0; I < Inputs.size(); ++I) {
6251 if (I)
6252 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006253
6254 // Find ToolChain for this input.
6255 const ToolChain *CurTC = &getToolChain();
6256 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6257 CurTC = nullptr;
6258 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6259 assert(CurTC == nullptr && "Expected one dependence!");
6260 CurTC = TC;
6261 });
6262 }
6263 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006264 }
6265 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6266
6267 // All the inputs are encoded as commands.
6268 C.addCommand(llvm::make_unique<Command>(
6269 JA, *this,
6270 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6271 CmdArgs, None));
6272}
6273
6274void OffloadBundler::ConstructJobMultipleOutputs(
6275 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6276 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6277 const char *LinkingOutput) const {
6278 // The version with multiple outputs is expected to refer to a unbundling job.
6279 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6280
6281 // The unbundling command looks like this:
6282 // clang-offload-bundler -type=bc
6283 // -targets=host-triple,openmp-triple1,openmp-triple2
6284 // -inputs=input_file
6285 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6286 // -unbundle
6287
6288 ArgStringList CmdArgs;
6289
6290 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6291 InputInfo Input = Inputs.front();
6292
6293 // Get the type.
6294 CmdArgs.push_back(TCArgs.MakeArgString(
6295 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6296
6297 // Get the targets.
6298 SmallString<128> Triples;
6299 Triples += "-targets=";
6300 auto DepInfo = UA.getDependentActionsInfo();
6301 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6302 if (I)
6303 Triples += ',';
6304
6305 auto &Dep = DepInfo[I];
6306 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6307 Triples += '-';
6308 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006309 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6310 !Dep.DependentBoundArch.empty()) {
6311 Triples += '-';
6312 Triples += Dep.DependentBoundArch;
6313 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006314 }
6315
6316 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6317
6318 // Get bundled file command.
6319 CmdArgs.push_back(
6320 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6321
6322 // Get unbundled files command.
6323 SmallString<128> UB;
6324 UB += "-outputs=";
6325 for (unsigned I = 0; I < Outputs.size(); ++I) {
6326 if (I)
6327 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006328 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006329 }
6330 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6331 CmdArgs.push_back("-unbundle");
6332
6333 // All the inputs are encoded as commands.
6334 C.addCommand(llvm::make_unique<Command>(
6335 JA, *this,
6336 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6337 CmdArgs, None));
6338}