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