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