blob: 5bffd96222ce732619e06ea2afc5fdb83e24c1ab [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.
1476 bool NoABICalls =
1477 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1478 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1479 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1480 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1481 CmdArgs.push_back("-mllvm");
1482 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001483
1484 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1485 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001486 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001487 options::OPT_mno_extern_sdata);
1488 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1489 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001490 if (LocalSData) {
1491 CmdArgs.push_back("-mllvm");
1492 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1493 CmdArgs.push_back("-mlocal-sdata=1");
1494 } else {
1495 CmdArgs.push_back("-mlocal-sdata=0");
1496 }
1497 LocalSData->claim();
1498 }
1499
Simon Dardis7d318782017-07-24 14:02:09 +00001500 if (ExternSData) {
1501 CmdArgs.push_back("-mllvm");
1502 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1503 CmdArgs.push_back("-mextern-sdata=1");
1504 } else {
1505 CmdArgs.push_back("-mextern-sdata=0");
1506 }
1507 ExternSData->claim();
1508 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001509
1510 if (EmbeddedData) {
1511 CmdArgs.push_back("-mllvm");
1512 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1513 CmdArgs.push_back("-membedded-data=1");
1514 } else {
1515 CmdArgs.push_back("-membedded-data=0");
1516 }
1517 EmbeddedData->claim();
1518 }
1519
Simon Dardis31636a12017-07-20 14:04:12 +00001520 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1521 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1522
1523 if (GPOpt)
1524 GPOpt->claim();
1525
David L. Jonesf561aba2017-03-08 01:02:16 +00001526 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1527 StringRef Val = StringRef(A->getValue());
1528 if (mips::hasCompactBranches(CPUName)) {
1529 if (Val == "never" || Val == "always" || Val == "optimal") {
1530 CmdArgs.push_back("-mllvm");
1531 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1532 } else
1533 D.Diag(diag::err_drv_unsupported_option_argument)
1534 << A->getOption().getName() << Val;
1535 } else
1536 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1537 }
1538}
1539
1540void Clang::AddPPCTargetArgs(const ArgList &Args,
1541 ArgStringList &CmdArgs) const {
1542 // Select the ABI to use.
1543 const char *ABIName = nullptr;
1544 if (getToolChain().getTriple().isOSLinux())
1545 switch (getToolChain().getArch()) {
1546 case llvm::Triple::ppc64: {
1547 // When targeting a processor that supports QPX, or if QPX is
1548 // specifically enabled, default to using the ABI that supports QPX (so
1549 // long as it is not specifically disabled).
1550 bool HasQPX = false;
1551 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1552 HasQPX = A->getValue() == StringRef("a2q");
1553 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1554 if (HasQPX) {
1555 ABIName = "elfv1-qpx";
1556 break;
1557 }
1558
1559 ABIName = "elfv1";
1560 break;
1561 }
1562 case llvm::Triple::ppc64le:
1563 ABIName = "elfv2";
1564 break;
1565 default:
1566 break;
1567 }
1568
1569 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1570 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1571 // the option if given as we don't have backend support for any targets
1572 // that don't use the altivec abi.
1573 if (StringRef(A->getValue()) != "altivec")
1574 ABIName = A->getValue();
1575
1576 ppc::FloatABI FloatABI =
1577 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1578
1579 if (FloatABI == ppc::FloatABI::Soft) {
1580 // Floating point operations and argument passing are soft.
1581 CmdArgs.push_back("-msoft-float");
1582 CmdArgs.push_back("-mfloat-abi");
1583 CmdArgs.push_back("soft");
1584 } else {
1585 // Floating point operations and argument passing are hard.
1586 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1587 CmdArgs.push_back("-mfloat-abi");
1588 CmdArgs.push_back("hard");
1589 }
1590
1591 if (ABIName) {
1592 CmdArgs.push_back("-target-abi");
1593 CmdArgs.push_back(ABIName);
1594 }
1595}
1596
1597void Clang::AddSparcTargetArgs(const ArgList &Args,
1598 ArgStringList &CmdArgs) const {
1599 sparc::FloatABI FloatABI =
1600 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1601
1602 if (FloatABI == sparc::FloatABI::Soft) {
1603 // Floating point operations and argument passing are soft.
1604 CmdArgs.push_back("-msoft-float");
1605 CmdArgs.push_back("-mfloat-abi");
1606 CmdArgs.push_back("soft");
1607 } else {
1608 // Floating point operations and argument passing are hard.
1609 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1610 CmdArgs.push_back("-mfloat-abi");
1611 CmdArgs.push_back("hard");
1612 }
1613}
1614
1615void Clang::AddSystemZTargetArgs(const ArgList &Args,
1616 ArgStringList &CmdArgs) const {
1617 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1618 CmdArgs.push_back("-mbackchain");
1619}
1620
1621void Clang::AddX86TargetArgs(const ArgList &Args,
1622 ArgStringList &CmdArgs) const {
1623 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1624 Args.hasArg(options::OPT_mkernel) ||
1625 Args.hasArg(options::OPT_fapple_kext))
1626 CmdArgs.push_back("-disable-red-zone");
1627
1628 // Default to avoid implicit floating-point for kernel/kext code, but allow
1629 // that to be overridden with -mno-soft-float.
1630 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1631 Args.hasArg(options::OPT_fapple_kext));
1632 if (Arg *A = Args.getLastArg(
1633 options::OPT_msoft_float, options::OPT_mno_soft_float,
1634 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1635 const Option &O = A->getOption();
1636 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1637 O.matches(options::OPT_msoft_float));
1638 }
1639 if (NoImplicitFloat)
1640 CmdArgs.push_back("-no-implicit-float");
1641
1642 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1643 StringRef Value = A->getValue();
1644 if (Value == "intel" || Value == "att") {
1645 CmdArgs.push_back("-mllvm");
1646 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1647 } else {
1648 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1649 << A->getOption().getName() << Value;
1650 }
1651 }
1652
1653 // Set flags to support MCU ABI.
1654 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1655 CmdArgs.push_back("-mfloat-abi");
1656 CmdArgs.push_back("soft");
1657 CmdArgs.push_back("-mstack-alignment=4");
1658 }
1659}
1660
1661void Clang::AddHexagonTargetArgs(const ArgList &Args,
1662 ArgStringList &CmdArgs) const {
1663 CmdArgs.push_back("-mqdsp6-compat");
1664 CmdArgs.push_back("-Wreturn-type");
1665
1666 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1667 std::string N = llvm::utostr(G.getValue());
1668 std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
1669 CmdArgs.push_back("-mllvm");
1670 CmdArgs.push_back(Args.MakeArgString(Opt));
1671 }
1672
1673 if (!Args.hasArg(options::OPT_fno_short_enums))
1674 CmdArgs.push_back("-fshort-enums");
1675 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1676 CmdArgs.push_back("-mllvm");
1677 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1678 }
1679 CmdArgs.push_back("-mllvm");
1680 CmdArgs.push_back("-machine-sink-split=0");
1681}
1682
1683void Clang::AddLanaiTargetArgs(const ArgList &Args,
1684 ArgStringList &CmdArgs) const {
1685 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1686 StringRef CPUName = A->getValue();
1687
1688 CmdArgs.push_back("-target-cpu");
1689 CmdArgs.push_back(Args.MakeArgString(CPUName));
1690 }
1691 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1692 StringRef Value = A->getValue();
1693 // Only support mregparm=4 to support old usage. Report error for all other
1694 // cases.
1695 int Mregparm;
1696 if (Value.getAsInteger(10, Mregparm)) {
1697 if (Mregparm != 4) {
1698 getToolChain().getDriver().Diag(
1699 diag::err_drv_unsupported_option_argument)
1700 << A->getOption().getName() << Value;
1701 }
1702 }
1703 }
1704}
1705
1706void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1707 ArgStringList &CmdArgs) const {
1708 // Default to "hidden" visibility.
1709 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1710 options::OPT_fvisibility_ms_compat)) {
1711 CmdArgs.push_back("-fvisibility");
1712 CmdArgs.push_back("hidden");
1713 }
1714}
1715
1716void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1717 StringRef Target, const InputInfo &Output,
1718 const InputInfo &Input, const ArgList &Args) const {
1719 // If this is a dry run, do not create the compilation database file.
1720 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1721 return;
1722
1723 using llvm::yaml::escape;
1724 const Driver &D = getToolChain().getDriver();
1725
1726 if (!CompilationDatabase) {
1727 std::error_code EC;
1728 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1729 if (EC) {
1730 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1731 << EC.message();
1732 return;
1733 }
1734 CompilationDatabase = std::move(File);
1735 }
1736 auto &CDB = *CompilationDatabase;
1737 SmallString<128> Buf;
1738 if (llvm::sys::fs::current_path(Buf))
1739 Buf = ".";
1740 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1741 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1742 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1743 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1744 Buf = "-x";
1745 Buf += types::getTypeName(Input.getType());
1746 CDB << ", \"" << escape(Buf) << "\"";
1747 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1748 Buf = "--sysroot=";
1749 Buf += D.SysRoot;
1750 CDB << ", \"" << escape(Buf) << "\"";
1751 }
1752 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1753 for (auto &A: Args) {
1754 auto &O = A->getOption();
1755 // Skip language selection, which is positional.
1756 if (O.getID() == options::OPT_x)
1757 continue;
1758 // Skip writing dependency output and the compilation database itself.
1759 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1760 continue;
1761 // Skip inputs.
1762 if (O.getKind() == Option::InputClass)
1763 continue;
1764 // All other arguments are quoted and appended.
1765 ArgStringList ASL;
1766 A->render(Args, ASL);
1767 for (auto &it: ASL)
1768 CDB << ", \"" << escape(it) << "\"";
1769 }
1770 Buf = "--target=";
1771 Buf += Target;
1772 CDB << ", \"" << escape(Buf) << "\"]},\n";
1773}
1774
1775static void CollectArgsForIntegratedAssembler(Compilation &C,
1776 const ArgList &Args,
1777 ArgStringList &CmdArgs,
1778 const Driver &D) {
1779 if (UseRelaxAll(C, Args))
1780 CmdArgs.push_back("-mrelax-all");
1781
1782 // Only default to -mincremental-linker-compatible if we think we are
1783 // targeting the MSVC linker.
1784 bool DefaultIncrementalLinkerCompatible =
1785 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1786 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1787 options::OPT_mno_incremental_linker_compatible,
1788 DefaultIncrementalLinkerCompatible))
1789 CmdArgs.push_back("-mincremental-linker-compatible");
1790
1791 switch (C.getDefaultToolChain().getArch()) {
1792 case llvm::Triple::arm:
1793 case llvm::Triple::armeb:
1794 case llvm::Triple::thumb:
1795 case llvm::Triple::thumbeb:
1796 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1797 StringRef Value = A->getValue();
1798 if (Value == "always" || Value == "never" || Value == "arm" ||
1799 Value == "thumb") {
1800 CmdArgs.push_back("-mllvm");
1801 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1802 } else {
1803 D.Diag(diag::err_drv_unsupported_option_argument)
1804 << A->getOption().getName() << Value;
1805 }
1806 }
1807 break;
1808 default:
1809 break;
1810 }
1811
1812 // When passing -I arguments to the assembler we sometimes need to
1813 // unconditionally take the next argument. For example, when parsing
1814 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1815 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1816 // arg after parsing the '-I' arg.
1817 bool TakeNextArg = false;
1818
David L. Jonesf561aba2017-03-08 01:02:16 +00001819 bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
1820 const char *MipsTargetFeature = nullptr;
1821 for (const Arg *A :
1822 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1823 A->claim();
1824
1825 for (StringRef Value : A->getValues()) {
1826 if (TakeNextArg) {
1827 CmdArgs.push_back(Value.data());
1828 TakeNextArg = false;
1829 continue;
1830 }
1831
1832 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1833 Value == "-mbig-obj")
1834 continue; // LLVM handles bigobj automatically
1835
1836 switch (C.getDefaultToolChain().getArch()) {
1837 default:
1838 break;
1839 case llvm::Triple::mips:
1840 case llvm::Triple::mipsel:
1841 case llvm::Triple::mips64:
1842 case llvm::Triple::mips64el:
1843 if (Value == "--trap") {
1844 CmdArgs.push_back("-target-feature");
1845 CmdArgs.push_back("+use-tcc-in-div");
1846 continue;
1847 }
1848 if (Value == "--break") {
1849 CmdArgs.push_back("-target-feature");
1850 CmdArgs.push_back("-use-tcc-in-div");
1851 continue;
1852 }
1853 if (Value.startswith("-msoft-float")) {
1854 CmdArgs.push_back("-target-feature");
1855 CmdArgs.push_back("+soft-float");
1856 continue;
1857 }
1858 if (Value.startswith("-mhard-float")) {
1859 CmdArgs.push_back("-target-feature");
1860 CmdArgs.push_back("-soft-float");
1861 continue;
1862 }
1863
1864 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1865 .Case("-mips1", "+mips1")
1866 .Case("-mips2", "+mips2")
1867 .Case("-mips3", "+mips3")
1868 .Case("-mips4", "+mips4")
1869 .Case("-mips5", "+mips5")
1870 .Case("-mips32", "+mips32")
1871 .Case("-mips32r2", "+mips32r2")
1872 .Case("-mips32r3", "+mips32r3")
1873 .Case("-mips32r5", "+mips32r5")
1874 .Case("-mips32r6", "+mips32r6")
1875 .Case("-mips64", "+mips64")
1876 .Case("-mips64r2", "+mips64r2")
1877 .Case("-mips64r3", "+mips64r3")
1878 .Case("-mips64r5", "+mips64r5")
1879 .Case("-mips64r6", "+mips64r6")
1880 .Default(nullptr);
1881 if (MipsTargetFeature)
1882 continue;
1883 }
1884
1885 if (Value == "-force_cpusubtype_ALL") {
1886 // Do nothing, this is the default and we don't support anything else.
1887 } else if (Value == "-L") {
1888 CmdArgs.push_back("-msave-temp-labels");
1889 } else if (Value == "--fatal-warnings") {
1890 CmdArgs.push_back("-massembler-fatal-warnings");
1891 } else if (Value == "--noexecstack") {
1892 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001893 } else if (Value.startswith("-compress-debug-sections") ||
1894 Value.startswith("--compress-debug-sections") ||
1895 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00001896 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001897 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00001898 } else if (Value == "-mrelax-relocations=yes" ||
1899 Value == "--mrelax-relocations=yes") {
1900 UseRelaxRelocations = true;
1901 } else if (Value == "-mrelax-relocations=no" ||
1902 Value == "--mrelax-relocations=no") {
1903 UseRelaxRelocations = false;
1904 } else if (Value.startswith("-I")) {
1905 CmdArgs.push_back(Value.data());
1906 // We need to consume the next argument if the current arg is a plain
1907 // -I. The next arg will be the include directory.
1908 if (Value == "-I")
1909 TakeNextArg = true;
1910 } else if (Value.startswith("-gdwarf-")) {
1911 // "-gdwarf-N" options are not cc1as options.
1912 unsigned DwarfVersion = DwarfVersionNum(Value);
1913 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
1914 CmdArgs.push_back(Value.data());
1915 } else {
1916 RenderDebugEnablingArgs(Args, CmdArgs,
1917 codegenoptions::LimitedDebugInfo,
1918 DwarfVersion, llvm::DebuggerKind::Default);
1919 }
1920 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
1921 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
1922 // Do nothing, we'll validate it later.
1923 } else if (Value == "-defsym") {
1924 if (A->getNumValues() != 2) {
1925 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
1926 break;
1927 }
1928 const char *S = A->getValue(1);
1929 auto Pair = StringRef(S).split('=');
1930 auto Sym = Pair.first;
1931 auto SVal = Pair.second;
1932
1933 if (Sym.empty() || SVal.empty()) {
1934 D.Diag(diag::err_drv_defsym_invalid_format) << S;
1935 break;
1936 }
1937 int64_t IVal;
1938 if (SVal.getAsInteger(0, IVal)) {
1939 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
1940 break;
1941 }
1942 CmdArgs.push_back(Value.data());
1943 TakeNextArg = true;
1944 } else {
1945 D.Diag(diag::err_drv_unsupported_option_argument)
1946 << A->getOption().getName() << Value;
1947 }
1948 }
1949 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001950 if (UseRelaxRelocations)
1951 CmdArgs.push_back("--mrelax-relocations");
1952 if (MipsTargetFeature != nullptr) {
1953 CmdArgs.push_back("-target-feature");
1954 CmdArgs.push_back(MipsTargetFeature);
1955 }
1956}
1957
1958void Clang::ConstructJob(Compilation &C, const JobAction &JA,
1959 const InputInfo &Output, const InputInfoList &Inputs,
1960 const ArgList &Args, const char *LinkingOutput) const {
1961 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1962 const std::string &TripleStr = Triple.getTriple();
1963
1964 bool KernelOrKext =
1965 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1966 const Driver &D = getToolChain().getDriver();
1967 ArgStringList CmdArgs;
1968
1969 // Check number of inputs for sanity. We need at least one input.
1970 assert(Inputs.size() >= 1 && "Must have at least one input.");
1971 const InputInfo &Input = Inputs[0];
1972 // CUDA compilation may have multiple inputs (source file + results of
1973 // device-side compilations). OpenMP device jobs also take the host IR as a
1974 // second input. All other jobs are expected to have exactly one
1975 // input.
1976 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
1977 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
1978 assert((IsCuda || (IsOpenMPDevice && Inputs.size() == 2) ||
1979 Inputs.size() == 1) &&
1980 "Unable to handle multiple inputs.");
1981
1982 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
1983 bool IsWindowsCygnus =
1984 getToolChain().getTriple().isWindowsCygwinEnvironment();
1985 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
1986 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
1987 bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1988
1989 // Adjust IsWindowsXYZ for CUDA compilations. Even when compiling in device
1990 // mode (i.e., getToolchain().getTriple() is NVPTX, not Windows), we need to
1991 // pass Windows-specific flags to cc1.
1992 if (IsCuda) {
1993 const llvm::Triple *AuxTriple = getToolChain().getAuxTriple();
1994 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
1995 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
1996 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
1997 }
1998
1999 // C++ is not supported for IAMCU.
2000 if (IsIAMCU && types::isCXX(Input.getType()))
2001 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
2002
2003 // Invoke ourselves in -cc1 mode.
2004 //
2005 // FIXME: Implement custom jobs for internal actions.
2006 CmdArgs.push_back("-cc1");
2007
2008 // Add the "effective" target triple.
2009 CmdArgs.push_back("-triple");
2010 CmdArgs.push_back(Args.MakeArgString(TripleStr));
2011
2012 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
2013 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
2014 Args.ClaimAllArgs(options::OPT_MJ);
2015 }
2016
2017 if (IsCuda) {
2018 // We have to pass the triple of the host if compiling for a CUDA device and
2019 // vice-versa.
2020 std::string NormalizedTriple;
2021 if (JA.isDeviceOffloading(Action::OFK_Cuda))
2022 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
2023 ->getTriple()
2024 .normalize();
2025 else
2026 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2027 ->getTriple()
2028 .normalize();
2029
2030 CmdArgs.push_back("-aux-triple");
2031 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
2032 }
2033
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00002034 if (IsOpenMPDevice) {
2035 // We have to pass the triple of the host if compiling for an OpenMP device.
2036 std::string NormalizedTriple =
2037 C.getSingleOffloadToolChain<Action::OFK_Host>()
2038 ->getTriple()
2039 .normalize();
2040 CmdArgs.push_back("-aux-triple");
2041 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
2042 }
2043
David L. Jonesf561aba2017-03-08 01:02:16 +00002044 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
2045 Triple.getArch() == llvm::Triple::thumb)) {
2046 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
2047 unsigned Version;
2048 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
2049 if (Version < 7)
2050 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
2051 << TripleStr;
2052 }
2053
2054 // Push all default warning arguments that are specific to
2055 // the given target. These come before user provided warning options
2056 // are provided.
2057 getToolChain().addClangWarningOptions(CmdArgs);
2058
2059 // Select the appropriate action.
2060 RewriteKind rewriteKind = RK_None;
2061
2062 if (isa<AnalyzeJobAction>(JA)) {
2063 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2064 CmdArgs.push_back("-analyze");
2065 } else if (isa<MigrateJobAction>(JA)) {
2066 CmdArgs.push_back("-migrate");
2067 } else if (isa<PreprocessJobAction>(JA)) {
2068 if (Output.getType() == types::TY_Dependencies)
2069 CmdArgs.push_back("-Eonly");
2070 else {
2071 CmdArgs.push_back("-E");
2072 if (Args.hasArg(options::OPT_rewrite_objc) &&
2073 !Args.hasArg(options::OPT_g_Group))
2074 CmdArgs.push_back("-P");
2075 }
2076 } else if (isa<AssembleJobAction>(JA)) {
2077 CmdArgs.push_back("-emit-obj");
2078
2079 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2080
2081 // Also ignore explicit -force_cpusubtype_ALL option.
2082 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
2083 } else if (isa<PrecompileJobAction>(JA)) {
2084 // Use PCH if the user requested it.
2085 bool UsePCH = D.CCCUsePCH;
2086
2087 if (JA.getType() == types::TY_Nothing)
2088 CmdArgs.push_back("-fsyntax-only");
2089 else if (JA.getType() == types::TY_ModuleFile)
2090 CmdArgs.push_back("-emit-module-interface");
2091 else if (UsePCH)
2092 CmdArgs.push_back("-emit-pch");
2093 else
2094 CmdArgs.push_back("-emit-pth");
2095 } else if (isa<VerifyPCHJobAction>(JA)) {
2096 CmdArgs.push_back("-verify-pch");
2097 } else {
2098 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
2099 "Invalid action for clang tool.");
2100 if (JA.getType() == types::TY_Nothing) {
2101 CmdArgs.push_back("-fsyntax-only");
2102 } else if (JA.getType() == types::TY_LLVM_IR ||
2103 JA.getType() == types::TY_LTO_IR) {
2104 CmdArgs.push_back("-emit-llvm");
2105 } else if (JA.getType() == types::TY_LLVM_BC ||
2106 JA.getType() == types::TY_LTO_BC) {
2107 CmdArgs.push_back("-emit-llvm-bc");
2108 } else if (JA.getType() == types::TY_PP_Asm) {
2109 CmdArgs.push_back("-S");
2110 } else if (JA.getType() == types::TY_AST) {
2111 CmdArgs.push_back("-emit-pch");
2112 } else if (JA.getType() == types::TY_ModuleFile) {
2113 CmdArgs.push_back("-module-file-info");
2114 } else if (JA.getType() == types::TY_RewrittenObjC) {
2115 CmdArgs.push_back("-rewrite-objc");
2116 rewriteKind = RK_NonFragile;
2117 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2118 CmdArgs.push_back("-rewrite-objc");
2119 rewriteKind = RK_Fragile;
2120 } else {
2121 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
2122 }
2123
2124 // Preserve use-list order by default when emitting bitcode, so that
2125 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
2126 // same result as running passes here. For LTO, we don't need to preserve
2127 // the use-list order, since serialization to bitcode is part of the flow.
2128 if (JA.getType() == types::TY_LLVM_BC)
2129 CmdArgs.push_back("-emit-llvm-uselists");
2130
2131 if (D.isUsingLTO()) {
2132 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
2133
Paul Robinsond23f2a82017-07-13 21:25:47 +00002134 // The Darwin and PS4 linkers currently use the legacy LTO API, which
2135 // does not support LTO unit features (CFI, whole program vtable opt)
2136 // under ThinLTO.
2137 if (!(getToolChain().getTriple().isOSDarwin() ||
2138 getToolChain().getTriple().isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002139 D.getLTOMode() == LTOK_Full)
2140 CmdArgs.push_back("-flto-unit");
2141 }
2142 }
2143
2144 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
2145 if (!types::isLLVMIR(Input.getType()))
2146 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
2147 << "-x ir";
2148 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
2149 }
2150
2151 // Embed-bitcode option.
2152 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
2153 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
2154 // Add flags implied by -fembed-bitcode.
2155 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2156 // Disable all llvm IR level optimizations.
2157 CmdArgs.push_back("-disable-llvm-passes");
2158 }
2159 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
2160 CmdArgs.push_back("-fembed-bitcode=marker");
2161
2162 // We normally speed up the clang process a bit by skipping destructors at
2163 // exit, but when we're generating diagnostics we can rely on some of the
2164 // cleanup.
2165 if (!C.isForDiagnostics())
2166 CmdArgs.push_back("-disable-free");
2167
2168// Disable the verification pass in -asserts builds.
2169#ifdef NDEBUG
2170 CmdArgs.push_back("-disable-llvm-verifier");
2171 // Discard LLVM value names in -asserts builds.
2172 CmdArgs.push_back("-discard-value-names");
2173#endif
2174
2175 // Set the main file name, so that debug info works even with
2176 // -save-temps.
2177 CmdArgs.push_back("-main-file-name");
2178 CmdArgs.push_back(getBaseInputName(Args, Input));
2179
2180 // Some flags which affect the language (via preprocessor
2181 // defines).
2182 if (Args.hasArg(options::OPT_static))
2183 CmdArgs.push_back("-static-define");
2184
2185 if (isa<AnalyzeJobAction>(JA)) {
2186 // Enable region store model by default.
2187 CmdArgs.push_back("-analyzer-store=region");
2188
2189 // Treat blocks as analysis entry points.
2190 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2191
2192 CmdArgs.push_back("-analyzer-eagerly-assume");
2193
2194 // Add default argument set.
2195 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2196 CmdArgs.push_back("-analyzer-checker=core");
2197 CmdArgs.push_back("-analyzer-checker=apiModeling");
2198
2199 if (!IsWindowsMSVC) {
2200 CmdArgs.push_back("-analyzer-checker=unix");
2201 } else {
2202 // Enable "unix" checkers that also work on Windows.
2203 CmdArgs.push_back("-analyzer-checker=unix.API");
2204 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2205 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2206 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2207 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2208 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2209 }
2210
2211 // Disable some unix checkers for PS4.
2212 if (IsPS4CPU) {
2213 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2214 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2215 }
2216
2217 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2218 CmdArgs.push_back("-analyzer-checker=osx");
2219
2220 CmdArgs.push_back("-analyzer-checker=deadcode");
2221
2222 if (types::isCXX(Input.getType()))
2223 CmdArgs.push_back("-analyzer-checker=cplusplus");
2224
2225 if (!IsPS4CPU) {
2226 CmdArgs.push_back(
2227 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
2228 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2229 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2230 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2231 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2232 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2233 }
2234
2235 // Default nullability checks.
2236 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2237 CmdArgs.push_back(
2238 "-analyzer-checker=nullability.NullReturnedFromNonnull");
2239 }
2240
2241 // Set the output format. The default is plist, for (lame) historical
2242 // reasons.
2243 CmdArgs.push_back("-analyzer-output");
2244 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2245 CmdArgs.push_back(A->getValue());
2246 else
2247 CmdArgs.push_back("plist");
2248
2249 // Disable the presentation of standard compiler warnings when
2250 // using --analyze. We only want to show static analyzer diagnostics
2251 // or frontend errors.
2252 CmdArgs.push_back("-w");
2253
2254 // Add -Xanalyzer arguments when running as analyzer.
2255 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2256 }
2257
2258 CheckCodeGenerationOptions(D, Args);
2259
2260 llvm::Reloc::Model RelocationModel;
2261 unsigned PICLevel;
2262 bool IsPIE;
2263 std::tie(RelocationModel, PICLevel, IsPIE) =
2264 ParsePICArgs(getToolChain(), Args);
2265
2266 const char *RMName = RelocationModelName(RelocationModel);
2267
2268 if ((RelocationModel == llvm::Reloc::ROPI ||
2269 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
2270 types::isCXX(Input.getType()) &&
2271 !Args.hasArg(options::OPT_fallow_unsupported))
2272 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
2273
2274 if (RMName) {
2275 CmdArgs.push_back("-mrelocation-model");
2276 CmdArgs.push_back(RMName);
2277 }
2278 if (PICLevel > 0) {
2279 CmdArgs.push_back("-pic-level");
2280 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
2281 if (IsPIE)
2282 CmdArgs.push_back("-pic-is-pie");
2283 }
2284
2285 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
2286 CmdArgs.push_back("-meabi");
2287 CmdArgs.push_back(A->getValue());
2288 }
2289
2290 CmdArgs.push_back("-mthread-model");
2291 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
2292 CmdArgs.push_back(A->getValue());
2293 else
2294 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
2295
2296 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
2297
2298 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
2299 options::OPT_fno_merge_all_constants))
2300 CmdArgs.push_back("-fno-merge-all-constants");
2301
2302 // LLVM Code Generator Options.
2303
2304 if (Args.hasArg(options::OPT_frewrite_map_file) ||
2305 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
2306 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
2307 options::OPT_frewrite_map_file_EQ)) {
2308 StringRef Map = A->getValue();
2309 if (!llvm::sys::fs::exists(Map)) {
2310 D.Diag(diag::err_drv_no_such_file) << Map;
2311 } else {
2312 CmdArgs.push_back("-frewrite-map-file");
2313 CmdArgs.push_back(A->getValue());
2314 A->claim();
2315 }
2316 }
2317 }
2318
2319 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
2320 StringRef v = A->getValue();
2321 CmdArgs.push_back("-mllvm");
2322 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
2323 A->claim();
2324 }
2325
2326 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
2327 true))
2328 CmdArgs.push_back("-fno-jump-tables");
2329
2330 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
2331 options::OPT_fno_preserve_as_comments, true))
2332 CmdArgs.push_back("-fno-preserve-as-comments");
2333
2334 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2335 CmdArgs.push_back("-mregparm");
2336 CmdArgs.push_back(A->getValue());
2337 }
2338
2339 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
2340 options::OPT_freg_struct_return)) {
2341 if (getToolChain().getArch() != llvm::Triple::x86) {
2342 D.Diag(diag::err_drv_unsupported_opt_for_target)
2343 << A->getSpelling() << getToolChain().getTriple().str();
2344 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
2345 CmdArgs.push_back("-fpcc-struct-return");
2346 } else {
2347 assert(A->getOption().matches(options::OPT_freg_struct_return));
2348 CmdArgs.push_back("-freg-struct-return");
2349 }
2350 }
2351
2352 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
2353 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
2354
2355 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
2356 CmdArgs.push_back("-mdisable-fp-elim");
2357 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
2358 options::OPT_fno_zero_initialized_in_bss))
2359 CmdArgs.push_back("-mno-zero-initialized-in-bss");
2360
2361 bool OFastEnabled = isOptimizationLevelFast(Args);
2362 // If -Ofast is the optimization level, then -fstrict-aliasing should be
2363 // enabled. This alias option is being used to simplify the hasFlag logic.
2364 OptSpecifier StrictAliasingAliasOption =
2365 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
2366 // We turn strict aliasing off by default if we're in CL mode, since MSVC
2367 // doesn't do any TBAA.
2368 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
2369 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
2370 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
2371 CmdArgs.push_back("-relaxed-aliasing");
2372 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
2373 options::OPT_fno_struct_path_tbaa))
2374 CmdArgs.push_back("-no-struct-path-tbaa");
2375 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
2376 false))
2377 CmdArgs.push_back("-fstrict-enums");
2378 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
2379 true))
2380 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00002381 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
2382 options::OPT_fno_allow_editor_placeholders, false))
2383 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00002384 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
2385 options::OPT_fno_strict_vtable_pointers,
2386 false))
2387 CmdArgs.push_back("-fstrict-vtable-pointers");
2388 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
2389 options::OPT_fno_optimize_sibling_calls))
2390 CmdArgs.push_back("-mdisable-tail-calls");
2391
2392 // Handle segmented stacks.
2393 if (Args.hasArg(options::OPT_fsplit_stack))
2394 CmdArgs.push_back("-split-stacks");
2395
David L. Jonesf561aba2017-03-08 01:02:16 +00002396 // Handle various floating point optimization flags, mapping them to the
John Brawn5c4c6112017-03-15 14:03:32 +00002397 // appropriate LLVM code generation flags. This is complicated by several
2398 // "umbrella" flags, so we do this by stepping through the flags incrementally
2399 // adjusting what we think is enabled/disabled, then at the end settting the
2400 // LLVM flags based on the final state.
2401 bool HonorInfs = true;
2402 bool HonorNans = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002403 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2404 bool MathErrno = getToolChain().IsMathErrnoDefault();
John Brawn5c4c6112017-03-15 14:03:32 +00002405 bool AssociativeMath = false;
2406 bool ReciprocalMath = false;
2407 bool SignedZeros = true;
2408 bool TrappingMath = true;
2409 StringRef DenormalFpMath = "";
2410 StringRef FpContract = "";
2411
2412 for (Arg *A : Args) {
2413 switch (A->getOption().getID()) {
2414 // If this isn't an FP option skip the claim below
2415 default:
2416 continue;
2417
2418 // Options controlling individual features
2419 case options::OPT_fhonor_infinities: HonorInfs = true; break;
2420 case options::OPT_fno_honor_infinities: HonorInfs = false; break;
2421 case options::OPT_fhonor_nans: HonorNans = true; break;
2422 case options::OPT_fno_honor_nans: HonorNans = false; break;
2423 case options::OPT_fmath_errno: MathErrno = true; break;
2424 case options::OPT_fno_math_errno: MathErrno = false; break;
2425 case options::OPT_fassociative_math: AssociativeMath = true; break;
2426 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2427 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2428 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2429 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2430 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2431 case options::OPT_ftrapping_math: TrappingMath = true; break;
2432 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2433
2434 case options::OPT_fdenormal_fp_math_EQ:
2435 DenormalFpMath = A->getValue();
2436 break;
2437
2438 // Validate and pass through -fp-contract option.
2439 case options::OPT_ffp_contract: {
2440 StringRef Val = A->getValue();
2441 if (Val == "fast" || Val == "on" || Val == "off") {
2442 FpContract = Val;
2443 } else {
2444 D.Diag(diag::err_drv_unsupported_option_argument)
2445 << A->getOption().getName() << Val;
2446 }
2447 break;
2448 }
2449
2450 case options::OPT_ffinite_math_only:
2451 HonorInfs = false;
2452 HonorNans = false;
2453 break;
2454 case options::OPT_fno_finite_math_only:
2455 HonorInfs = true;
2456 HonorNans = true;
2457 break;
2458
2459 case options::OPT_funsafe_math_optimizations:
2460 AssociativeMath = true;
2461 ReciprocalMath = true;
2462 SignedZeros = false;
2463 TrappingMath = false;
2464 break;
2465 case options::OPT_fno_unsafe_math_optimizations:
2466 AssociativeMath = false;
2467 ReciprocalMath = false;
2468 SignedZeros = true;
2469 TrappingMath = true;
2470 // -fno_unsafe_math_optimizations restores default denormal handling
2471 DenormalFpMath = "";
2472 break;
2473
2474 case options::OPT_Ofast:
2475 // If -Ofast is the optimization level, then -ffast-math should be enabled
2476 if (!OFastEnabled)
2477 continue;
2478 LLVM_FALLTHROUGH;
2479 case options::OPT_ffast_math:
2480 HonorInfs = false;
2481 HonorNans = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00002482 MathErrno = false;
John Brawn5c4c6112017-03-15 14:03:32 +00002483 AssociativeMath = true;
2484 ReciprocalMath = true;
2485 SignedZeros = false;
2486 TrappingMath = false;
2487 // If fast-math is set then set the fp-contract mode to fast.
2488 FpContract = "fast";
2489 break;
2490 case options::OPT_fno_fast_math:
2491 HonorInfs = true;
2492 HonorNans = true;
2493 // Turning on -ffast-math (with either flag) removes the need for
2494 // MathErrno. However, turning *off* -ffast-math merely restores the
2495 // toolchain default (which may be false).
2496 MathErrno = getToolChain().IsMathErrnoDefault();
2497 AssociativeMath = false;
2498 ReciprocalMath = false;
2499 SignedZeros = true;
2500 TrappingMath = true;
2501 // -fno_fast_math restores default denormal and fpcontract handling
2502 DenormalFpMath = "";
2503 FpContract = "";
2504 break;
2505 }
2506 // If we handled this option claim it
2507 A->claim();
David L. Jonesf561aba2017-03-08 01:02:16 +00002508 }
John Brawn5c4c6112017-03-15 14:03:32 +00002509
2510 if (!HonorInfs)
2511 CmdArgs.push_back("-menable-no-infs");
2512
2513 if (!HonorNans)
2514 CmdArgs.push_back("-menable-no-nans");
2515
David L. Jonesf561aba2017-03-08 01:02:16 +00002516 if (MathErrno)
2517 CmdArgs.push_back("-fmath-errno");
2518
David L. Jonesf561aba2017-03-08 01:02:16 +00002519 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2520 !TrappingMath)
2521 CmdArgs.push_back("-menable-unsafe-fp-math");
2522
2523 if (!SignedZeros)
2524 CmdArgs.push_back("-fno-signed-zeros");
2525
2526 if (ReciprocalMath)
2527 CmdArgs.push_back("-freciprocal-math");
2528
2529 if (!TrappingMath)
2530 CmdArgs.push_back("-fno-trapping-math");
2531
John Brawn5c4c6112017-03-15 14:03:32 +00002532 if (!DenormalFpMath.empty())
2533 CmdArgs.push_back(Args.MakeArgString("-fdenormal-fp-math="+DenormalFpMath));
David L. Jonesf561aba2017-03-08 01:02:16 +00002534
John Brawn5c4c6112017-03-15 14:03:32 +00002535 if (!FpContract.empty())
2536 CmdArgs.push_back(Args.MakeArgString("-ffp-contract="+FpContract));
David L. Jonesf561aba2017-03-08 01:02:16 +00002537
2538 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
2539
John Brawn5c4c6112017-03-15 14:03:32 +00002540 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2541 // individual features enabled by -ffast-math instead of the option itself as
2542 // that's consistent with gcc's behaviour.
2543 if (!HonorInfs && !HonorNans && !MathErrno && AssociativeMath &&
2544 ReciprocalMath && !SignedZeros && !TrappingMath)
2545 CmdArgs.push_back("-ffast-math");
2546
2547 // Handle __FINITE_MATH_ONLY__ similarly.
2548 if (!HonorInfs && !HonorNans)
2549 CmdArgs.push_back("-ffinite-math-only");
David L. Jonesf561aba2017-03-08 01:02:16 +00002550
2551 // Decide whether to use verbose asm. Verbose assembly is the default on
2552 // toolchains which have the integrated assembler on by default.
2553 bool IsIntegratedAssemblerDefault =
2554 getToolChain().IsIntegratedAssemblerDefault();
2555 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2556 IsIntegratedAssemblerDefault) ||
2557 Args.hasArg(options::OPT_dA))
2558 CmdArgs.push_back("-masm-verbose");
2559
2560 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
2561 IsIntegratedAssemblerDefault))
2562 CmdArgs.push_back("-no-integrated-as");
2563
2564 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2565 CmdArgs.push_back("-mdebug-pass");
2566 CmdArgs.push_back("Structure");
2567 }
2568 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2569 CmdArgs.push_back("-mdebug-pass");
2570 CmdArgs.push_back("Arguments");
2571 }
2572
2573 // Enable -mconstructor-aliases except on darwin, where we have to work around
2574 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
2575 // aliases aren't supported.
2576 if (!getToolChain().getTriple().isOSDarwin() &&
2577 !getToolChain().getTriple().isNVPTX())
2578 CmdArgs.push_back("-mconstructor-aliases");
2579
2580 // Darwin's kernel doesn't support guard variables; just die if we
2581 // try to use them.
2582 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2583 CmdArgs.push_back("-fforbid-guard-variables");
2584
2585 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
2586 false)) {
2587 CmdArgs.push_back("-mms-bitfields");
2588 }
2589
2590 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
2591 options::OPT_mno_pie_copy_relocations,
2592 false)) {
2593 CmdArgs.push_back("-mpie-copy-relocations");
2594 }
2595
2596 // This is a coarse approximation of what llvm-gcc actually does, both
2597 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2598 // complicated ways.
2599 bool AsynchronousUnwindTables =
2600 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2601 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00002602 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002603 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
2604 !KernelOrKext);
2605 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2606 AsynchronousUnwindTables))
2607 CmdArgs.push_back("-munwind-tables");
2608
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00002609 getToolChain().addClangTargetOptions(Args, CmdArgs,
2610 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00002611
2612 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2613 CmdArgs.push_back("-mlimit-float-precision");
2614 CmdArgs.push_back(A->getValue());
2615 }
2616
2617 // FIXME: Handle -mtune=.
2618 (void)Args.hasArg(options::OPT_mtune_EQ);
2619
2620 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2621 CmdArgs.push_back("-mcode-model");
2622 CmdArgs.push_back(A->getValue());
2623 }
2624
2625 // Add the target cpu
2626 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
2627 if (!CPU.empty()) {
2628 CmdArgs.push_back("-target-cpu");
2629 CmdArgs.push_back(Args.MakeArgString(CPU));
2630 }
2631
2632 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2633 CmdArgs.push_back("-mfpmath");
2634 CmdArgs.push_back(A->getValue());
2635 }
2636
2637 // Add the target features
2638 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
2639
2640 // Add target specific flags.
2641 switch (getToolChain().getArch()) {
2642 default:
2643 break;
2644
2645 case llvm::Triple::arm:
2646 case llvm::Triple::armeb:
2647 case llvm::Triple::thumb:
2648 case llvm::Triple::thumbeb:
2649 // Use the effective triple, which takes into account the deployment target.
2650 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
2651 break;
2652
2653 case llvm::Triple::aarch64:
2654 case llvm::Triple::aarch64_be:
2655 AddAArch64TargetArgs(Args, CmdArgs);
2656 break;
2657
2658 case llvm::Triple::mips:
2659 case llvm::Triple::mipsel:
2660 case llvm::Triple::mips64:
2661 case llvm::Triple::mips64el:
2662 AddMIPSTargetArgs(Args, CmdArgs);
2663 break;
2664
2665 case llvm::Triple::ppc:
2666 case llvm::Triple::ppc64:
2667 case llvm::Triple::ppc64le:
2668 AddPPCTargetArgs(Args, CmdArgs);
2669 break;
2670
2671 case llvm::Triple::sparc:
2672 case llvm::Triple::sparcel:
2673 case llvm::Triple::sparcv9:
2674 AddSparcTargetArgs(Args, CmdArgs);
2675 break;
2676
2677 case llvm::Triple::systemz:
2678 AddSystemZTargetArgs(Args, CmdArgs);
2679 break;
2680
2681 case llvm::Triple::x86:
2682 case llvm::Triple::x86_64:
2683 AddX86TargetArgs(Args, CmdArgs);
2684 break;
2685
2686 case llvm::Triple::lanai:
2687 AddLanaiTargetArgs(Args, CmdArgs);
2688 break;
2689
2690 case llvm::Triple::hexagon:
2691 AddHexagonTargetArgs(Args, CmdArgs);
2692 break;
2693
2694 case llvm::Triple::wasm32:
2695 case llvm::Triple::wasm64:
2696 AddWebAssemblyTargetArgs(Args, CmdArgs);
2697 break;
2698 }
2699
2700 // The 'g' groups options involve a somewhat intricate sequence of decisions
2701 // about what to pass from the driver to the frontend, but by the time they
2702 // reach cc1 they've been factored into three well-defined orthogonal choices:
2703 // * what level of debug info to generate
2704 // * what dwarf version to write
2705 // * what debugger tuning to use
2706 // This avoids having to monkey around further in cc1 other than to disable
2707 // codeview if not running in a Windows environment. Perhaps even that
2708 // decision should be made in the driver as well though.
2709 unsigned DwarfVersion = 0;
2710 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
2711 // These two are potentially updated by AddClangCLArgs.
2712 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
2713 bool EmitCodeView = false;
2714
2715 // Add clang-cl arguments.
2716 types::ID InputType = Input.getType();
2717 if (getToolChain().getDriver().IsCLMode())
2718 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
2719
2720 // Pass the linker version in use.
2721 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2722 CmdArgs.push_back("-target-linker-version");
2723 CmdArgs.push_back(A->getValue());
2724 }
2725
2726 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
2727 CmdArgs.push_back("-momit-leaf-frame-pointer");
2728
2729 // Explicitly error on some things we know we don't support and can't just
2730 // ignore.
2731 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
2732 Arg *Unsupported;
2733 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
2734 getToolChain().getArch() == llvm::Triple::x86) {
2735 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
2736 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
2737 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
2738 << Unsupported->getOption().getName();
2739 }
Eric Christopher758aad72017-03-21 22:06:18 +00002740 // The faltivec option has been superseded by the maltivec option.
2741 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
2742 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
2743 << Unsupported->getOption().getName()
2744 << "please use -maltivec and include altivec.h explicitly";
2745 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
2746 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
2747 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00002748 }
2749
2750 Args.AddAllArgs(CmdArgs, options::OPT_v);
2751 Args.AddLastArg(CmdArgs, options::OPT_H);
2752 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
2753 CmdArgs.push_back("-header-include-file");
2754 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
2755 : "-");
2756 }
2757 Args.AddLastArg(CmdArgs, options::OPT_P);
2758 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
2759
2760 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
2761 CmdArgs.push_back("-diagnostic-log-file");
2762 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
2763 : "-");
2764 }
2765
2766 bool splitDwarfInlining =
2767 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2768 options::OPT_fno_split_dwarf_inlining, true);
2769
2770 Args.ClaimAllArgs(options::OPT_g_Group);
2771 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2772 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2773 // If the last option explicitly specified a debug-info level, use it.
2774 if (A->getOption().matches(options::OPT_gN_Group)) {
2775 DebugInfoKind = DebugLevelToInfoKind(*A);
2776 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2777 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2778 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
2779 // This gets a bit more complicated if you've disabled inline info in the
2780 // skeleton CUs (splitDwarfInlining) - then there's value in composing
2781 // split-dwarf and line-tables-only, so let those compose naturally in
2782 // that case.
2783 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2784 if (SplitDwarfArg) {
2785 if (A->getIndex() > SplitDwarfArg->getIndex()) {
2786 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2787 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2788 splitDwarfInlining))
2789 SplitDwarfArg = nullptr;
2790 } else if (splitDwarfInlining)
2791 DebugInfoKind = codegenoptions::NoDebugInfo;
2792 }
2793 } else
2794 // For any other 'g' option, use Limited.
2795 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2796 }
2797
2798 // If a debugger tuning argument appeared, remember it.
2799 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2800 options::OPT_ggdbN_Group)) {
2801 if (A->getOption().matches(options::OPT_glldb))
2802 DebuggerTuning = llvm::DebuggerKind::LLDB;
2803 else if (A->getOption().matches(options::OPT_gsce))
2804 DebuggerTuning = llvm::DebuggerKind::SCE;
2805 else
2806 DebuggerTuning = llvm::DebuggerKind::GDB;
2807 }
2808
2809 // If a -gdwarf argument appeared, remember it.
2810 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2811 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2812 DwarfVersion = DwarfVersionNum(A->getSpelling());
2813
2814 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2815 // argument parsing.
2816 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
2817 // DwarfVersion remains at 0 if no explicit choice was made.
2818 CmdArgs.push_back("-gcodeview");
2819 } else if (DwarfVersion == 0 &&
2820 DebugInfoKind != codegenoptions::NoDebugInfo) {
2821 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
2822 }
2823
Eric Christopherca325172017-03-29 23:34:20 +00002824 // We ignore flag -gstrict-dwarf for now.
2825 // And we handle flag -grecord-gcc-switches later with DwarfDebugFlags.
David L. Jonesf561aba2017-03-08 01:02:16 +00002826 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2827
2828 // Column info is included by default for everything except PS4 and CodeView.
2829 // Clang doesn't track end columns, just starting columns, which, in theory,
2830 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2831 // debuggers don't handle missing end columns well, so it's better not to
2832 // include any column info.
2833 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
2834 /*Default=*/ !IsPS4CPU && !(IsWindowsMSVC && EmitCodeView)))
2835 CmdArgs.push_back("-dwarf-column-info");
2836
2837 // FIXME: Move backend command line options to the module.
2838 // If -gline-tables-only is the last option it wins.
2839 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2840 Args.hasArg(options::OPT_gmodules)) {
2841 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2842 CmdArgs.push_back("-dwarf-ext-refs");
2843 CmdArgs.push_back("-fmodule-format=obj");
2844 }
2845
2846 // -gsplit-dwarf should turn on -g and enable the backend dwarf
2847 // splitting and extraction.
2848 // FIXME: Currently only works on Linux.
David Blaikie9bb296c2017-04-28 20:50:25 +00002849 if (getToolChain().getTriple().isOSLinux()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00002850 if (!splitDwarfInlining)
2851 CmdArgs.push_back("-fno-split-dwarf-inlining");
David Blaikie9bb296c2017-04-28 20:50:25 +00002852 if (SplitDwarfArg) {
2853 if (DebugInfoKind == codegenoptions::NoDebugInfo)
2854 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2855 CmdArgs.push_back("-enable-split-dwarf");
2856 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002857 }
2858
2859 // After we've dealt with all combinations of things that could
2860 // make DebugInfoKind be other than None or DebugLineTablesOnly,
2861 // figure out if we need to "upgrade" it to standalone debug info.
2862 // We parse these two '-f' options whether or not they will be used,
2863 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
2864 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
2865 options::OPT_fno_standalone_debug,
2866 getToolChain().GetDefaultStandaloneDebug());
2867 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
2868 DebugInfoKind = codegenoptions::FullDebugInfo;
2869 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
2870 DebuggerTuning);
2871
2872 // -fdebug-macro turns on macro debug info generation.
2873 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
2874 false))
2875 CmdArgs.push_back("-debug-info-macro");
2876
2877 // -ggnu-pubnames turns on gnu style pubnames in the backend.
2878 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
2879 CmdArgs.push_back("-backend-option");
2880 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
2881 }
2882
2883 // -gdwarf-aranges turns on the emission of the aranges section in the
2884 // backend.
2885 // Always enabled on the PS4.
2886 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
2887 CmdArgs.push_back("-backend-option");
2888 CmdArgs.push_back("-generate-arange-section");
2889 }
2890
2891 if (Args.hasFlag(options::OPT_fdebug_types_section,
2892 options::OPT_fno_debug_types_section, false)) {
2893 CmdArgs.push_back("-backend-option");
2894 CmdArgs.push_back("-generate-type-units");
2895 }
2896
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002897 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
2898
David L. Jonesf561aba2017-03-08 01:02:16 +00002899 bool UseSeparateSections = isUseSeparateSections(Triple);
2900
2901 if (Args.hasFlag(options::OPT_ffunction_sections,
2902 options::OPT_fno_function_sections, UseSeparateSections)) {
2903 CmdArgs.push_back("-ffunction-sections");
2904 }
2905
2906 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
2907 UseSeparateSections)) {
2908 CmdArgs.push_back("-fdata-sections");
2909 }
2910
2911 if (!Args.hasFlag(options::OPT_funique_section_names,
2912 options::OPT_fno_unique_section_names, true))
2913 CmdArgs.push_back("-fno-unique-section-names");
2914
2915 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2916
David L. Jonesf561aba2017-03-08 01:02:16 +00002917 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
2918
2919 // Add runtime flag for PS4 when PGO or Coverage are enabled.
2920 if (getToolChain().getTriple().isPS4CPU())
2921 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
2922
2923 // Pass options for controlling the default header search paths.
2924 if (Args.hasArg(options::OPT_nostdinc)) {
2925 CmdArgs.push_back("-nostdsysteminc");
2926 CmdArgs.push_back("-nobuiltininc");
2927 } else {
2928 if (Args.hasArg(options::OPT_nostdlibinc))
2929 CmdArgs.push_back("-nostdsysteminc");
2930 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2931 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2932 }
2933
2934 // Pass the path to compiler resource files.
2935 CmdArgs.push_back("-resource-dir");
2936 CmdArgs.push_back(D.ResourceDir.c_str());
2937
2938 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2939
2940 bool ARCMTEnabled = false;
2941 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2942 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2943 options::OPT_ccc_arcmt_modify,
2944 options::OPT_ccc_arcmt_migrate)) {
2945 ARCMTEnabled = true;
2946 switch (A->getOption().getID()) {
2947 default:
2948 llvm_unreachable("missed a case");
2949 case options::OPT_ccc_arcmt_check:
2950 CmdArgs.push_back("-arcmt-check");
2951 break;
2952 case options::OPT_ccc_arcmt_modify:
2953 CmdArgs.push_back("-arcmt-modify");
2954 break;
2955 case options::OPT_ccc_arcmt_migrate:
2956 CmdArgs.push_back("-arcmt-migrate");
2957 CmdArgs.push_back("-mt-migrate-directory");
2958 CmdArgs.push_back(A->getValue());
2959
2960 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2961 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2962 break;
2963 }
2964 }
2965 } else {
2966 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2967 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2968 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2969 }
2970
2971 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2972 if (ARCMTEnabled) {
2973 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
2974 << "-ccc-arcmt-migrate";
2975 }
2976 CmdArgs.push_back("-mt-migrate-directory");
2977 CmdArgs.push_back(A->getValue());
2978
2979 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2980 options::OPT_objcmt_migrate_subscripting,
2981 options::OPT_objcmt_migrate_property)) {
2982 // None specified, means enable them all.
2983 CmdArgs.push_back("-objcmt-migrate-literals");
2984 CmdArgs.push_back("-objcmt-migrate-subscripting");
2985 CmdArgs.push_back("-objcmt-migrate-property");
2986 } else {
2987 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2988 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2989 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2990 }
2991 } else {
2992 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2993 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2994 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2995 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2996 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2997 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2998 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2999 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3000 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3001 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3002 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3003 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3004 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3005 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3006 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3007 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3008 }
3009
3010 // Add preprocessing options like -I, -D, etc. if we are using the
3011 // preprocessor.
3012 //
3013 // FIXME: Support -fpreprocessed
3014 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3015 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3016
3017 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3018 // that "The compiler can only warn and ignore the option if not recognized".
3019 // When building with ccache, it will pass -D options to clang even on
3020 // preprocessed inputs and configure concludes that -fPIC is not supported.
3021 Args.ClaimAllArgs(options::OPT_D);
3022
3023 // Manually translate -O4 to -O3; let clang reject others.
3024 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3025 if (A->getOption().matches(options::OPT_O4)) {
3026 CmdArgs.push_back("-O3");
3027 D.Diag(diag::warn_O4_is_O3);
3028 } else {
3029 A->render(Args, CmdArgs);
3030 }
3031 }
3032
3033 // Warn about ignored options to clang.
3034 for (const Arg *A :
3035 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3036 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3037 A->claim();
3038 }
3039
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003040 for (const Arg *A :
3041 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3042 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3043 A->claim();
3044 }
3045
David L. Jonesf561aba2017-03-08 01:02:16 +00003046 claimNoWarnArgs(Args);
3047
3048 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3049
3050 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3051 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3052 CmdArgs.push_back("-pedantic");
3053 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3054 Args.AddLastArg(CmdArgs, options::OPT_w);
3055
3056 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3057 // (-ansi is equivalent to -std=c89 or -std=c++98).
3058 //
3059 // If a std is supplied, only add -trigraphs if it follows the
3060 // option.
3061 bool ImplyVCPPCXXVer = false;
3062 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3063 if (Std->getOption().matches(options::OPT_ansi))
3064 if (types::isCXX(InputType))
3065 CmdArgs.push_back("-std=c++98");
3066 else
3067 CmdArgs.push_back("-std=c89");
3068 else
3069 Std->render(Args, CmdArgs);
3070
3071 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3072 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3073 options::OPT_ftrigraphs,
3074 options::OPT_fno_trigraphs))
3075 if (A != Std)
3076 A->render(Args, CmdArgs);
3077 } else {
3078 // Honor -std-default.
3079 //
3080 // FIXME: Clang doesn't correctly handle -std= when the input language
3081 // doesn't match. For the time being just ignore this for C++ inputs;
3082 // eventually we want to do all the standard defaulting here instead of
3083 // splitting it between the driver and clang -cc1.
3084 if (!types::isCXX(InputType))
3085 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3086 /*Joined=*/true);
3087 else if (IsWindowsMSVC)
3088 ImplyVCPPCXXVer = true;
3089
3090 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3091 options::OPT_fno_trigraphs);
3092 }
3093
3094 // GCC's behavior for -Wwrite-strings is a bit strange:
3095 // * In C, this "warning flag" changes the types of string literals from
3096 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3097 // for the discarded qualifier.
3098 // * In C++, this is just a normal warning flag.
3099 //
3100 // Implementing this warning correctly in C is hard, so we follow GCC's
3101 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3102 // a non-const char* in C, rather than using this crude hack.
3103 if (!types::isCXX(InputType)) {
3104 // FIXME: This should behave just like a warning flag, and thus should also
3105 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3106 Arg *WriteStrings =
3107 Args.getLastArg(options::OPT_Wwrite_strings,
3108 options::OPT_Wno_write_strings, options::OPT_w);
3109 if (WriteStrings &&
3110 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3111 CmdArgs.push_back("-fconst-strings");
3112 }
3113
3114 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3115 // during C++ compilation, which it is by default. GCC keeps this define even
3116 // in the presence of '-w', match this behavior bug-for-bug.
3117 if (types::isCXX(InputType) &&
3118 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3119 true)) {
3120 CmdArgs.push_back("-fdeprecated-macro");
3121 }
3122
3123 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3124 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3125 if (Asm->getOption().matches(options::OPT_fasm))
3126 CmdArgs.push_back("-fgnu-keywords");
3127 else
3128 CmdArgs.push_back("-fno-gnu-keywords");
3129 }
3130
3131 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3132 CmdArgs.push_back("-fno-dwarf-directory-asm");
3133
3134 if (ShouldDisableAutolink(Args, getToolChain()))
3135 CmdArgs.push_back("-fno-autolink");
3136
3137 // Add in -fdebug-compilation-dir if necessary.
3138 addDebugCompDirArg(Args, CmdArgs);
3139
3140 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3141 StringRef Map = A->getValue();
3142 if (Map.find('=') == StringRef::npos)
3143 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3144 else
3145 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3146 A->claim();
3147 }
3148
3149 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3150 options::OPT_ftemplate_depth_EQ)) {
3151 CmdArgs.push_back("-ftemplate-depth");
3152 CmdArgs.push_back(A->getValue());
3153 }
3154
3155 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3156 CmdArgs.push_back("-foperator-arrow-depth");
3157 CmdArgs.push_back(A->getValue());
3158 }
3159
3160 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3161 CmdArgs.push_back("-fconstexpr-depth");
3162 CmdArgs.push_back(A->getValue());
3163 }
3164
3165 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3166 CmdArgs.push_back("-fconstexpr-steps");
3167 CmdArgs.push_back(A->getValue());
3168 }
3169
3170 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3171 CmdArgs.push_back("-fbracket-depth");
3172 CmdArgs.push_back(A->getValue());
3173 }
3174
3175 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3176 options::OPT_Wlarge_by_value_copy_def)) {
3177 if (A->getNumValues()) {
3178 StringRef bytes = A->getValue();
3179 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3180 } else
3181 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3182 }
3183
3184 if (Args.hasArg(options::OPT_relocatable_pch))
3185 CmdArgs.push_back("-relocatable-pch");
3186
3187 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3188 CmdArgs.push_back("-fconstant-string-class");
3189 CmdArgs.push_back(A->getValue());
3190 }
3191
3192 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3193 CmdArgs.push_back("-ftabstop");
3194 CmdArgs.push_back(A->getValue());
3195 }
3196
3197 CmdArgs.push_back("-ferror-limit");
3198 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3199 CmdArgs.push_back(A->getValue());
3200 else
3201 CmdArgs.push_back("19");
3202
3203 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3204 CmdArgs.push_back("-fmacro-backtrace-limit");
3205 CmdArgs.push_back(A->getValue());
3206 }
3207
3208 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3209 CmdArgs.push_back("-ftemplate-backtrace-limit");
3210 CmdArgs.push_back(A->getValue());
3211 }
3212
3213 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3214 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3215 CmdArgs.push_back(A->getValue());
3216 }
3217
3218 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3219 CmdArgs.push_back("-fspell-checking-limit");
3220 CmdArgs.push_back(A->getValue());
3221 }
3222
3223 // Pass -fmessage-length=.
3224 CmdArgs.push_back("-fmessage-length");
3225 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3226 CmdArgs.push_back(A->getValue());
3227 } else {
3228 // If -fmessage-length=N was not specified, determine whether this is a
3229 // terminal and, if so, implicitly define -fmessage-length appropriately.
3230 unsigned N = llvm::sys::Process::StandardErrColumns();
3231 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3232 }
3233
3234 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3235 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3236 options::OPT_fvisibility_ms_compat)) {
3237 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3238 CmdArgs.push_back("-fvisibility");
3239 CmdArgs.push_back(A->getValue());
3240 } else {
3241 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3242 CmdArgs.push_back("-fvisibility");
3243 CmdArgs.push_back("hidden");
3244 CmdArgs.push_back("-ftype-visibility");
3245 CmdArgs.push_back("default");
3246 }
3247 }
3248
3249 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3250
3251 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3252
3253 // -fhosted is default.
3254 bool IsHosted = true;
3255 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3256 KernelOrKext) {
3257 CmdArgs.push_back("-ffreestanding");
3258 IsHosted = false;
3259 }
3260
3261 // Forward -f (flag) options which we can pass directly.
3262 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3263 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3264 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Brad Smith733fe192017-07-17 00:49:31 +00003265 // Emulated TLS is enabled by default on Android and OpenBSD, and can be enabled
3266 // manually with -femulated-tls.
3267 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isOSOpenBSD() ||
3268 Triple.isWindowsCygwinEnvironment();
David L. Jonesf561aba2017-03-08 01:02:16 +00003269 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
3270 EmulatedTLSDefault))
3271 CmdArgs.push_back("-femulated-tls");
3272 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003273 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003274 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003275
David L. Jonesf561aba2017-03-08 01:02:16 +00003276 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3277 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3278
3279 // Forward flags for OpenMP. We don't do this if the current action is an
3280 // device offloading action other than OpenMP.
3281 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3282 options::OPT_fno_openmp, false) &&
3283 (JA.isDeviceOffloading(Action::OFK_None) ||
3284 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
3285 switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
3286 case Driver::OMPRT_OMP:
3287 case Driver::OMPRT_IOMP5:
3288 // Clang can generate useful OpenMP code for these two runtime libraries.
3289 CmdArgs.push_back("-fopenmp");
3290
3291 // If no option regarding the use of TLS in OpenMP codegeneration is
3292 // given, decide a default based on the target. Otherwise rely on the
3293 // options and pass the right information to the frontend.
3294 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3295 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3296 CmdArgs.push_back("-fnoopenmp-use-tls");
3297 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
3298 break;
3299 default:
3300 // By default, if Clang doesn't know how to generate useful OpenMP code
3301 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3302 // down to the actual compilation.
3303 // FIXME: It would be better to have a mode which *only* omits IR
3304 // generation based on the OpenMP support so that we get consistent
3305 // semantic analysis, etc.
3306 break;
3307 }
3308 }
3309
3310 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3311 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3312
Dean Michael Berris835832d2017-03-30 00:29:36 +00003313 const XRayArgs &XRay = getToolChain().getXRayArgs();
3314 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
3315
David L. Jonesf561aba2017-03-08 01:02:16 +00003316 if (getToolChain().SupportsProfiling())
3317 Args.AddLastArg(CmdArgs, options::OPT_pg);
3318
3319 if (getToolChain().SupportsProfiling())
3320 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
3321
3322 // -flax-vector-conversions is default.
3323 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3324 options::OPT_fno_lax_vector_conversions))
3325 CmdArgs.push_back("-fno-lax-vector-conversions");
3326
3327 if (Args.getLastArg(options::OPT_fapple_kext) ||
3328 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
3329 CmdArgs.push_back("-fapple-kext");
3330
3331 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3332 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3333 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3334 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3335 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3336
3337 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3338 CmdArgs.push_back("-ftrapv-handler");
3339 CmdArgs.push_back(A->getValue());
3340 }
3341
3342 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3343
3344 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3345 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3346 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3347 if (A->getOption().matches(options::OPT_fwrapv))
3348 CmdArgs.push_back("-fwrapv");
3349 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3350 options::OPT_fno_strict_overflow)) {
3351 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3352 CmdArgs.push_back("-fwrapv");
3353 }
3354
3355 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3356 options::OPT_fno_reroll_loops))
3357 if (A->getOption().matches(options::OPT_freroll_loops))
3358 CmdArgs.push_back("-freroll-loops");
3359
3360 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3361 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3362 options::OPT_fno_unroll_loops);
3363
3364 Args.AddLastArg(CmdArgs, options::OPT_pthread);
3365
3366 // -stack-protector=0 is default.
3367 unsigned StackProtectorLevel = 0;
3368 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3369 // doesn't even have a stack!
3370 if (!Triple.isNVPTX()) {
3371 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3372 options::OPT_fstack_protector_all,
3373 options::OPT_fstack_protector_strong,
3374 options::OPT_fstack_protector)) {
3375 if (A->getOption().matches(options::OPT_fstack_protector)) {
3376 StackProtectorLevel = std::max<unsigned>(
3377 LangOptions::SSPOn,
3378 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
3379 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3380 StackProtectorLevel = LangOptions::SSPStrong;
3381 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3382 StackProtectorLevel = LangOptions::SSPReq;
3383 } else {
3384 StackProtectorLevel =
3385 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3386 // Only use a default stack protector on Darwin in case -ffreestanding
3387 // is not specified.
3388 if (Triple.isOSDarwin() && !IsHosted)
3389 StackProtectorLevel = 0;
3390 }
3391 }
3392 if (StackProtectorLevel) {
3393 CmdArgs.push_back("-stack-protector");
3394 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3395 }
3396
3397 // --param ssp-buffer-size=
3398 for (const Arg *A : Args.filtered(options::OPT__param)) {
3399 StringRef Str(A->getValue());
3400 if (Str.startswith("ssp-buffer-size=")) {
3401 if (StackProtectorLevel) {
3402 CmdArgs.push_back("-stack-protector-buffer-size");
3403 // FIXME: Verify the argument is a valid integer.
3404 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3405 }
3406 A->claim();
3407 }
3408 }
3409
3410 // Translate -mstackrealign
3411 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3412 false))
3413 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3414
3415 if (Args.hasArg(options::OPT_mstack_alignment)) {
3416 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3417 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3418 }
3419
3420 if (Args.hasArg(options::OPT_mstack_probe_size)) {
3421 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
3422
3423 if (!Size.empty())
3424 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
3425 else
3426 CmdArgs.push_back("-mstack-probe-size=0");
3427 }
3428
3429 switch (getToolChain().getArch()) {
3430 case llvm::Triple::aarch64:
3431 case llvm::Triple::aarch64_be:
3432 case llvm::Triple::arm:
3433 case llvm::Triple::armeb:
3434 case llvm::Triple::thumb:
3435 case llvm::Triple::thumbeb:
3436 CmdArgs.push_back("-fallow-half-arguments-and-returns");
3437 break;
3438
3439 default:
3440 break;
3441 }
3442
3443 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3444 options::OPT_mno_restrict_it)) {
3445 if (A->getOption().matches(options::OPT_mrestrict_it)) {
3446 CmdArgs.push_back("-backend-option");
3447 CmdArgs.push_back("-arm-restrict-it");
3448 } else {
3449 CmdArgs.push_back("-backend-option");
3450 CmdArgs.push_back("-arm-no-restrict-it");
3451 }
3452 } else if (Triple.isOSWindows() &&
3453 (Triple.getArch() == llvm::Triple::arm ||
3454 Triple.getArch() == llvm::Triple::thumb)) {
3455 // Windows on ARM expects restricted IT blocks
3456 CmdArgs.push_back("-backend-option");
3457 CmdArgs.push_back("-arm-restrict-it");
3458 }
3459
3460 // Forward -cl options to -cc1
3461 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
3462 CmdArgs.push_back("-cl-opt-disable");
3463 }
3464 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
3465 CmdArgs.push_back("-cl-strict-aliasing");
3466 }
3467 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
3468 CmdArgs.push_back("-cl-single-precision-constant");
3469 }
3470 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
3471 CmdArgs.push_back("-cl-finite-math-only");
3472 }
3473 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
3474 CmdArgs.push_back("-cl-kernel-arg-info");
3475 }
3476 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
3477 CmdArgs.push_back("-cl-unsafe-math-optimizations");
3478 }
3479 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
3480 CmdArgs.push_back("-cl-fast-relaxed-math");
3481 }
3482 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
3483 CmdArgs.push_back("-cl-mad-enable");
3484 }
3485 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
3486 CmdArgs.push_back("-cl-no-signed-zeros");
3487 }
3488 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3489 std::string CLStdStr = "-cl-std=";
3490 CLStdStr += A->getValue();
3491 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3492 }
3493 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
3494 CmdArgs.push_back("-cl-denorms-are-zero");
3495 }
3496 if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
3497 CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
3498 }
3499
3500 // Forward -f options with positive and negative forms; we translate
3501 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00003502 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003503 StringRef fname = A->getValue();
3504 if (!llvm::sys::fs::exists(fname))
3505 D.Diag(diag::err_drv_no_such_file) << fname;
3506 else
3507 A->render(Args, CmdArgs);
3508 }
3509
3510 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3511 options::OPT_fno_debug_info_for_profiling, false))
3512 CmdArgs.push_back("-fdebug-info-for-profiling");
3513
3514 // -fbuiltin is default unless -mkernel is used.
3515 bool UseBuiltins =
3516 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3517 !Args.hasArg(options::OPT_mkernel));
3518 if (!UseBuiltins)
3519 CmdArgs.push_back("-fno-builtin");
3520
3521 // -ffreestanding implies -fno-builtin.
3522 if (Args.hasArg(options::OPT_ffreestanding))
3523 UseBuiltins = false;
3524
3525 // Process the -fno-builtin-* options.
3526 for (const auto &Arg : Args) {
3527 const Option &O = Arg->getOption();
3528 if (!O.matches(options::OPT_fno_builtin_))
3529 continue;
3530
3531 Arg->claim();
3532 // If -fno-builtin is specified, then there's no need to pass the option to
3533 // the frontend.
3534 if (!UseBuiltins)
3535 continue;
3536
3537 StringRef FuncName = Arg->getValue();
3538 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3539 }
3540
3541 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3542 options::OPT_fno_assume_sane_operator_new))
3543 CmdArgs.push_back("-fno-assume-sane-operator-new");
3544
3545 // -fblocks=0 is default.
3546 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3547 getToolChain().IsBlocksDefault()) ||
3548 (Args.hasArg(options::OPT_fgnu_runtime) &&
3549 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3550 !Args.hasArg(options::OPT_fno_blocks))) {
3551 CmdArgs.push_back("-fblocks");
3552
3553 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
3554 !getToolChain().hasBlocksRuntime())
3555 CmdArgs.push_back("-fblocks-runtime-optional");
3556 }
3557
3558 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
3559 false) &&
3560 types::isCXX(InputType)) {
3561 CmdArgs.push_back("-fcoroutines-ts");
3562 }
3563
3564 // -fmodules enables the use of precompiled modules (off by default).
3565 // Users can pass -fno-cxx-modules to turn off modules support for
3566 // C++/Objective-C++ programs.
3567 bool HaveClangModules = false;
3568 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3569 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3570 options::OPT_fno_cxx_modules, true);
3571 if (AllowedInCXX || !types::isCXX(InputType)) {
3572 CmdArgs.push_back("-fmodules");
3573 HaveClangModules = true;
3574 }
3575 }
3576
3577 bool HaveAnyModules = HaveClangModules;
3578 if (Args.hasArg(options::OPT_fmodules_ts)) {
3579 CmdArgs.push_back("-fmodules-ts");
3580 HaveAnyModules = true;
3581 }
3582
3583 // -fmodule-maps enables implicit reading of module map files. By default,
3584 // this is enabled if we are using Clang's flavor of precompiled modules.
3585 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3586 options::OPT_fno_implicit_module_maps, HaveClangModules)) {
3587 CmdArgs.push_back("-fimplicit-module-maps");
3588 }
3589
3590 // -fmodules-decluse checks that modules used are declared so (off by
3591 // default).
3592 if (Args.hasFlag(options::OPT_fmodules_decluse,
3593 options::OPT_fno_modules_decluse, false)) {
3594 CmdArgs.push_back("-fmodules-decluse");
3595 }
3596
3597 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3598 // all #included headers are part of modules.
3599 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3600 options::OPT_fno_modules_strict_decluse, false)) {
3601 CmdArgs.push_back("-fmodules-strict-decluse");
3602 }
3603
3604 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3605 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3606 options::OPT_fno_implicit_modules, HaveClangModules)) {
3607 if (HaveAnyModules)
3608 CmdArgs.push_back("-fno-implicit-modules");
3609 } else if (HaveAnyModules) {
3610 // -fmodule-cache-path specifies where our implicitly-built module files
3611 // should be written.
3612 SmallString<128> Path;
3613 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3614 Path = A->getValue();
3615 if (C.isForDiagnostics()) {
3616 // When generating crash reports, we want to emit the modules along with
3617 // the reproduction sources, so we ignore any provided module path.
3618 Path = Output.getFilename();
3619 llvm::sys::path::replace_extension(Path, ".cache");
3620 llvm::sys::path::append(Path, "modules");
3621 } else if (Path.empty()) {
3622 // No module path was provided: use the default.
3623 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
3624 llvm::sys::path::append(Path, "org.llvm.clang.");
3625 appendUserToPath(Path);
3626 llvm::sys::path::append(Path, "ModuleCache");
3627 }
3628 const char Arg[] = "-fmodules-cache-path=";
3629 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3630 CmdArgs.push_back(Args.MakeArgString(Path));
3631 }
3632
3633 if (HaveAnyModules) {
3634 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3635 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path))
3636 CmdArgs.push_back(Args.MakeArgString(
3637 std::string("-fprebuilt-module-path=") + A->getValue()));
3638 }
3639
3640 // -fmodule-name specifies the module that is currently being built (or
3641 // used for header checking by -fmodule-maps).
3642 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3643
3644 // -fmodule-map-file can be used to specify files containing module
3645 // definitions.
3646 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3647
3648 // -fbuiltin-module-map can be used to load the clang
3649 // builtin headers modulemap file.
3650 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3651 SmallString<128> BuiltinModuleMap(getToolChain().getDriver().ResourceDir);
3652 llvm::sys::path::append(BuiltinModuleMap, "include");
3653 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3654 if (llvm::sys::fs::exists(BuiltinModuleMap)) {
3655 CmdArgs.push_back(Args.MakeArgString("-fmodule-map-file=" +
3656 BuiltinModuleMap));
3657 }
3658 }
3659
3660 // -fmodule-file can be used to specify files containing precompiled modules.
3661 if (HaveAnyModules)
3662 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3663 else
3664 Args.ClaimAllArgs(options::OPT_fmodule_file);
3665
3666 // When building modules and generating crashdumps, we need to dump a module
3667 // dependency VFS alongside the output.
3668 if (HaveClangModules && C.isForDiagnostics()) {
3669 SmallString<128> VFSDir(Output.getFilename());
3670 llvm::sys::path::replace_extension(VFSDir, ".cache");
3671 // Add the cache directory as a temp so the crash diagnostics pick it up.
3672 C.addTempFile(Args.MakeArgString(VFSDir));
3673
3674 llvm::sys::path::append(VFSDir, "vfs");
3675 CmdArgs.push_back("-module-dependency-dir");
3676 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3677 }
3678
3679 if (HaveClangModules)
3680 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3681
3682 // Pass through all -fmodules-ignore-macro arguments.
3683 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3684 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3685 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3686
3687 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3688
3689 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3690 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3691 D.Diag(diag::err_drv_argument_not_allowed_with)
3692 << A->getAsString(Args) << "-fbuild-session-timestamp";
3693
3694 llvm::sys::fs::file_status Status;
3695 if (llvm::sys::fs::status(A->getValue(), Status))
3696 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3697 CmdArgs.push_back(
3698 Args.MakeArgString("-fbuild-session-timestamp=" +
3699 Twine((uint64_t)Status.getLastModificationTime()
3700 .time_since_epoch()
3701 .count())));
3702 }
3703
3704 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3705 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3706 options::OPT_fbuild_session_file))
3707 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3708
3709 Args.AddLastArg(CmdArgs,
3710 options::OPT_fmodules_validate_once_per_build_session);
3711 }
3712
3713 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
3714 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3715
3716 // -faccess-control is default.
3717 if (Args.hasFlag(options::OPT_fno_access_control,
3718 options::OPT_faccess_control, false))
3719 CmdArgs.push_back("-fno-access-control");
3720
3721 // -felide-constructors is the default.
3722 if (Args.hasFlag(options::OPT_fno_elide_constructors,
3723 options::OPT_felide_constructors, false))
3724 CmdArgs.push_back("-fno-elide-constructors");
3725
3726 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
3727
3728 if (KernelOrKext || (types::isCXX(InputType) &&
3729 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
3730 RTTIMode == ToolChain::RM_DisabledImplicitly)))
3731 CmdArgs.push_back("-fno-rtti");
3732
3733 // -fshort-enums=0 is default for all architectures except Hexagon.
3734 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
3735 getToolChain().getArch() == llvm::Triple::hexagon))
3736 CmdArgs.push_back("-fshort-enums");
3737
3738 // -fsigned-char is default.
3739 if (Arg *A = Args.getLastArg(
3740 options::OPT_fsigned_char, options::OPT_fno_signed_char,
3741 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
3742 if (A->getOption().matches(options::OPT_funsigned_char) ||
3743 A->getOption().matches(options::OPT_fno_signed_char)) {
3744 CmdArgs.push_back("-fno-signed-char");
3745 }
3746 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
3747 CmdArgs.push_back("-fno-signed-char");
3748 }
3749
3750 // -fuse-cxa-atexit is default.
3751 if (!Args.hasFlag(
3752 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
3753 !IsWindowsCygnus && !IsWindowsGNU &&
3754 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
3755 getToolChain().getArch() != llvm::Triple::hexagon &&
3756 getToolChain().getArch() != llvm::Triple::xcore &&
3757 ((getToolChain().getTriple().getVendor() !=
3758 llvm::Triple::MipsTechnologies) ||
3759 getToolChain().getTriple().hasEnvironment())) ||
3760 KernelOrKext)
3761 CmdArgs.push_back("-fno-use-cxa-atexit");
3762
3763 // -fms-extensions=0 is default.
3764 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3765 IsWindowsMSVC))
3766 CmdArgs.push_back("-fms-extensions");
3767
3768 // -fno-use-line-directives is default.
3769 if (Args.hasFlag(options::OPT_fuse_line_directives,
3770 options::OPT_fno_use_line_directives, false))
3771 CmdArgs.push_back("-fuse-line-directives");
3772
3773 // -fms-compatibility=0 is default.
3774 if (Args.hasFlag(options::OPT_fms_compatibility,
3775 options::OPT_fno_ms_compatibility,
3776 (IsWindowsMSVC &&
3777 Args.hasFlag(options::OPT_fms_extensions,
3778 options::OPT_fno_ms_extensions, true))))
3779 CmdArgs.push_back("-fms-compatibility");
3780
3781 VersionTuple MSVT =
3782 getToolChain().computeMSVCVersion(&getToolChain().getDriver(), Args);
3783 if (!MSVT.empty())
3784 CmdArgs.push_back(
3785 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
3786
3787 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
3788 if (ImplyVCPPCXXVer) {
3789 StringRef LanguageStandard;
3790 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
3791 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
3792 .Case("c++14", "-std=c++14")
3793 .Case("c++latest", "-std=c++1z")
3794 .Default("");
3795 if (LanguageStandard.empty())
3796 D.Diag(clang::diag::warn_drv_unused_argument)
3797 << StdArg->getAsString(Args);
3798 }
3799
3800 if (LanguageStandard.empty()) {
3801 if (IsMSVC2015Compatible)
3802 LanguageStandard = "-std=c++14";
3803 else
3804 LanguageStandard = "-std=c++11";
3805 }
3806
3807 CmdArgs.push_back(LanguageStandard.data());
3808 }
3809
3810 // -fno-borland-extensions is default.
3811 if (Args.hasFlag(options::OPT_fborland_extensions,
3812 options::OPT_fno_borland_extensions, false))
3813 CmdArgs.push_back("-fborland-extensions");
3814
3815 // -fno-declspec is default, except for PS4.
3816 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
3817 getToolChain().getTriple().isPS4()))
3818 CmdArgs.push_back("-fdeclspec");
3819 else if (Args.hasArg(options::OPT_fno_declspec))
3820 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
3821
3822 // -fthreadsafe-static is default, except for MSVC compatibility versions less
3823 // than 19.
3824 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3825 options::OPT_fno_threadsafe_statics,
3826 !IsWindowsMSVC || IsMSVC2015Compatible))
3827 CmdArgs.push_back("-fno-threadsafe-statics");
3828
3829 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
3830 // needs it.
3831 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
3832 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
3833 CmdArgs.push_back("-fdelayed-template-parsing");
3834
3835 // -fgnu-keywords default varies depending on language; only pass if
3836 // specified.
3837 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3838 options::OPT_fno_gnu_keywords))
3839 A->render(Args, CmdArgs);
3840
3841 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
3842 false))
3843 CmdArgs.push_back("-fgnu89-inline");
3844
3845 if (Args.hasArg(options::OPT_fno_inline))
3846 CmdArgs.push_back("-fno-inline");
3847
3848 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
3849 options::OPT_finline_hint_functions,
3850 options::OPT_fno_inline_functions))
3851 InlineArg->render(Args, CmdArgs);
3852
3853 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
3854 options::OPT_fno_experimental_new_pass_manager);
3855
3856 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3857
3858 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3859 // legacy is the default. Except for deployment target of 10.5,
3860 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
3861 // gets ignored silently.
3862 if (objcRuntime.isNonFragile()) {
3863 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3864 options::OPT_fno_objc_legacy_dispatch,
3865 objcRuntime.isLegacyDispatchDefaultForArch(
3866 getToolChain().getArch()))) {
3867 if (getToolChain().UseObjCMixedDispatch())
3868 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3869 else
3870 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3871 }
3872 }
3873
3874 // When ObjectiveC legacy runtime is in effect on MacOSX,
3875 // turn on the option to do Array/Dictionary subscripting
3876 // by default.
3877 if (getToolChain().getArch() == llvm::Triple::x86 &&
3878 getToolChain().getTriple().isMacOSX() &&
3879 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
3880 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
3881 objcRuntime.isNeXTFamily())
3882 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3883
3884 // -fencode-extended-block-signature=1 is default.
3885 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3886 CmdArgs.push_back("-fencode-extended-block-signature");
3887 }
3888
3889 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3890 // NOTE: This logic is duplicated in ToolChains.cpp.
3891 bool ARC = isObjCAutoRefCount(Args);
3892 if (ARC) {
3893 getToolChain().CheckObjCARC();
3894
3895 CmdArgs.push_back("-fobjc-arc");
3896
3897 // FIXME: It seems like this entire block, and several around it should be
3898 // wrapped in isObjC, but for now we just use it here as this is where it
3899 // was being used previously.
3900 if (types::isCXX(InputType) && types::isObjC(InputType)) {
3901 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3902 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3903 else
3904 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3905 }
3906
3907 // Allow the user to enable full exceptions code emission.
3908 // We define off for Objective-CC, on for Objective-C++.
3909 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3910 options::OPT_fno_objc_arc_exceptions,
3911 /*default*/ types::isCXX(InputType)))
3912 CmdArgs.push_back("-fobjc-arc-exceptions");
3913 }
3914
3915 // Silence warning for full exception code emission options when explicitly
3916 // set to use no ARC.
3917 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3918 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3919 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3920 }
3921
3922 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3923 // rewriter.
3924 if (rewriteKind != RK_None)
3925 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3926
3927 // Pass down -fobjc-weak or -fno-objc-weak if present.
3928 if (types::isObjC(InputType)) {
3929 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
3930 options::OPT_fno_objc_weak);
3931 if (!WeakArg) {
3932 // nothing to do
3933 } else if (!objcRuntime.allowsWeak()) {
3934 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3935 D.Diag(diag::err_objc_weak_unsupported);
3936 } else {
3937 WeakArg->render(Args, CmdArgs);
3938 }
3939 }
3940
3941 if (Args.hasFlag(options::OPT_fapplication_extension,
3942 options::OPT_fno_application_extension, false))
3943 CmdArgs.push_back("-fapplication-extension");
3944
3945 // Handle GCC-style exception args.
3946 if (!C.getDriver().IsCLMode())
3947 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
3948 CmdArgs);
3949
3950 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
3951 getToolChain().UseSjLjExceptions(Args))
3952 CmdArgs.push_back("-fsjlj-exceptions");
3953
3954 // C++ "sane" operator new.
3955 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3956 options::OPT_fno_assume_sane_operator_new))
3957 CmdArgs.push_back("-fno-assume-sane-operator-new");
3958
3959 // -frelaxed-template-template-args is off by default, as it is a severe
3960 // breaking change until a corresponding change to template partial ordering
3961 // is provided.
3962 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
3963 options::OPT_fno_relaxed_template_template_args, false))
3964 CmdArgs.push_back("-frelaxed-template-template-args");
3965
3966 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
3967 // most platforms.
3968 if (Args.hasFlag(options::OPT_fsized_deallocation,
3969 options::OPT_fno_sized_deallocation, false))
3970 CmdArgs.push_back("-fsized-deallocation");
3971
3972 // -faligned-allocation is on by default in C++17 onwards and otherwise off
3973 // by default.
3974 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
3975 options::OPT_fno_aligned_allocation,
3976 options::OPT_faligned_new_EQ)) {
3977 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
3978 CmdArgs.push_back("-fno-aligned-allocation");
3979 else
3980 CmdArgs.push_back("-faligned-allocation");
3981 }
3982
3983 // The default new alignment can be specified using a dedicated option or via
3984 // a GCC-compatible option that also turns on aligned allocation.
3985 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
3986 options::OPT_faligned_new_EQ))
3987 CmdArgs.push_back(
3988 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
3989
3990 // -fconstant-cfstrings is default, and may be subject to argument translation
3991 // on Darwin.
3992 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
3993 options::OPT_fno_constant_cfstrings) ||
3994 !Args.hasFlag(options::OPT_mconstant_cfstrings,
3995 options::OPT_mno_constant_cfstrings))
3996 CmdArgs.push_back("-fno-constant-cfstrings");
3997
3998 // -fshort-wchar default varies depending on platform; only
3999 // pass if specified.
4000 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4001 options::OPT_fno_short_wchar))
4002 A->render(Args, CmdArgs);
4003
4004 // -fno-pascal-strings is default, only pass non-default.
4005 if (Args.hasFlag(options::OPT_fpascal_strings,
4006 options::OPT_fno_pascal_strings, false))
4007 CmdArgs.push_back("-fpascal-strings");
4008
4009 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4010 // -fno-pack-struct doesn't apply to -fpack-struct=.
4011 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4012 std::string PackStructStr = "-fpack-struct=";
4013 PackStructStr += A->getValue();
4014 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4015 } else if (Args.hasFlag(options::OPT_fpack_struct,
4016 options::OPT_fno_pack_struct, false)) {
4017 CmdArgs.push_back("-fpack-struct=1");
4018 }
4019
4020 // Handle -fmax-type-align=N and -fno-type-align
4021 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4022 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4023 if (!SkipMaxTypeAlign) {
4024 std::string MaxTypeAlignStr = "-fmax-type-align=";
4025 MaxTypeAlignStr += A->getValue();
4026 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4027 }
4028 } else if (getToolChain().getTriple().isOSDarwin()) {
4029 if (!SkipMaxTypeAlign) {
4030 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4031 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4032 }
4033 }
4034
4035 // -fcommon is the default unless compiling kernel code or the target says so
4036 bool NoCommonDefault =
4037 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
4038 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4039 !NoCommonDefault))
4040 CmdArgs.push_back("-fno-common");
4041
4042 // -fsigned-bitfields is default, and clang doesn't yet support
4043 // -funsigned-bitfields.
4044 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4045 options::OPT_funsigned_bitfields))
4046 D.Diag(diag::warn_drv_clang_unsupported)
4047 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4048
4049 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4050 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4051 D.Diag(diag::err_drv_clang_unsupported)
4052 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4053
4054 // -finput_charset=UTF-8 is default. Reject others
4055 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4056 StringRef value = inputCharset->getValue();
4057 if (!value.equals_lower("utf-8"))
4058 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4059 << value;
4060 }
4061
4062 // -fexec_charset=UTF-8 is default. Reject others
4063 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4064 StringRef value = execCharset->getValue();
4065 if (!value.equals_lower("utf-8"))
4066 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4067 << value;
4068 }
4069
Reid Klecknerca77dd52017-05-31 17:37:49 +00004070 bool CaretDefault = true;
4071 bool ColumnDefault = true;
4072 if (Arg *DiagArg = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4073 options::OPT__SLASH_diagnostics_column,
4074 options::OPT__SLASH_diagnostics_caret)) {
4075 switch (DiagArg->getOption().getID()) {
4076 case options::OPT__SLASH_diagnostics_caret:
4077 CaretDefault = true;
4078 ColumnDefault = true;
4079 break;
4080 case options::OPT__SLASH_diagnostics_column:
4081 CaretDefault = false;
4082 ColumnDefault = true;
4083 break;
4084 case options::OPT__SLASH_diagnostics_classic:
4085 CaretDefault = false;
4086 ColumnDefault = false;
4087 break;
4088 }
4089 }
4090
David L. Jonesf561aba2017-03-08 01:02:16 +00004091 // -fcaret-diagnostics is default.
4092 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
Reid Klecknerca77dd52017-05-31 17:37:49 +00004093 options::OPT_fno_caret_diagnostics, CaretDefault))
David L. Jonesf561aba2017-03-08 01:02:16 +00004094 CmdArgs.push_back("-fno-caret-diagnostics");
4095
4096 // -fdiagnostics-fixit-info is default, only pass non-default.
4097 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4098 options::OPT_fno_diagnostics_fixit_info))
4099 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4100
4101 // Enable -fdiagnostics-show-option by default.
4102 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4103 options::OPT_fno_diagnostics_show_option))
4104 CmdArgs.push_back("-fdiagnostics-show-option");
4105
4106 if (const Arg *A =
4107 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4108 CmdArgs.push_back("-fdiagnostics-show-category");
4109 CmdArgs.push_back(A->getValue());
4110 }
4111
4112 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
4113 options::OPT_fno_diagnostics_show_hotness, false))
4114 CmdArgs.push_back("-fdiagnostics-show-hotness");
4115
Brian Gesiak562eab92017-07-01 05:45:26 +00004116 if (const Arg *A =
4117 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4118 std::string Opt = std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4119 CmdArgs.push_back(Args.MakeArgString(Opt));
4120 }
4121
David L. Jonesf561aba2017-03-08 01:02:16 +00004122 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4123 CmdArgs.push_back("-fdiagnostics-format");
4124 CmdArgs.push_back(A->getValue());
4125 }
4126
4127 if (Arg *A = Args.getLastArg(
4128 options::OPT_fdiagnostics_show_note_include_stack,
4129 options::OPT_fno_diagnostics_show_note_include_stack)) {
4130 if (A->getOption().matches(
4131 options::OPT_fdiagnostics_show_note_include_stack))
4132 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4133 else
4134 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4135 }
4136
4137 // Color diagnostics are parsed by the driver directly from argv
4138 // and later re-parsed to construct this job; claim any possible
4139 // color diagnostic here to avoid warn_drv_unused_argument and
4140 // diagnose bad OPT_fdiagnostics_color_EQ values.
4141 for (Arg *A : Args) {
4142 const Option &O = A->getOption();
4143 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4144 !O.matches(options::OPT_fdiagnostics_color) &&
4145 !O.matches(options::OPT_fno_color_diagnostics) &&
4146 !O.matches(options::OPT_fno_diagnostics_color) &&
4147 !O.matches(options::OPT_fdiagnostics_color_EQ))
4148 continue;
4149 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
4150 StringRef Value(A->getValue());
4151 if (Value != "always" && Value != "never" && Value != "auto")
4152 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4153 << ("-fdiagnostics-color=" + Value).str();
4154 }
4155 A->claim();
4156 }
4157 if (D.getDiags().getDiagnosticOptions().ShowColors)
4158 CmdArgs.push_back("-fcolor-diagnostics");
4159
4160 if (Args.hasArg(options::OPT_fansi_escape_codes))
4161 CmdArgs.push_back("-fansi-escape-codes");
4162
4163 if (!Args.hasFlag(options::OPT_fshow_source_location,
4164 options::OPT_fno_show_source_location))
4165 CmdArgs.push_back("-fno-show-source-location");
4166
4167 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4168 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4169
4170 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
Reid Klecknerca77dd52017-05-31 17:37:49 +00004171 ColumnDefault))
David L. Jonesf561aba2017-03-08 01:02:16 +00004172 CmdArgs.push_back("-fno-show-column");
4173
4174 if (!Args.hasFlag(options::OPT_fspell_checking,
4175 options::OPT_fno_spell_checking))
4176 CmdArgs.push_back("-fno-spell-checking");
4177
4178 // -fno-asm-blocks is default.
4179 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4180 false))
4181 CmdArgs.push_back("-fasm-blocks");
4182
4183 // -fgnu-inline-asm is default.
4184 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4185 options::OPT_fno_gnu_inline_asm, true))
4186 CmdArgs.push_back("-fno-gnu-inline-asm");
4187
4188 // Enable vectorization per default according to the optimization level
4189 // selected. For optimization levels that want vectorization we use the alias
4190 // option to simplify the hasFlag logic.
4191 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4192 OptSpecifier VectorizeAliasOption =
4193 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4194 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4195 options::OPT_fno_vectorize, EnableVec))
4196 CmdArgs.push_back("-vectorize-loops");
4197
4198 // -fslp-vectorize is enabled based on the optimization level selected.
4199 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4200 OptSpecifier SLPVectAliasOption =
4201 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4202 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4203 options::OPT_fno_slp_vectorize, EnableSLPVec))
4204 CmdArgs.push_back("-vectorize-slp");
4205
David L. Jonesf561aba2017-03-08 01:02:16 +00004206 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4207 A->render(Args, CmdArgs);
4208
4209 if (Arg *A = Args.getLastArg(
4210 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4211 A->render(Args, CmdArgs);
4212
4213 // -fdollars-in-identifiers default varies depending on platform and
4214 // language; only pass if specified.
4215 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4216 options::OPT_fno_dollars_in_identifiers)) {
4217 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4218 CmdArgs.push_back("-fdollars-in-identifiers");
4219 else
4220 CmdArgs.push_back("-fno-dollars-in-identifiers");
4221 }
4222
4223 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4224 // practical purposes.
4225 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4226 options::OPT_fno_unit_at_a_time)) {
4227 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4228 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4229 }
4230
4231 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4232 options::OPT_fno_apple_pragma_pack, false))
4233 CmdArgs.push_back("-fapple-pragma-pack");
4234
4235 // le32-specific flags:
4236 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4237 // by default.
4238 if (getToolChain().getArch() == llvm::Triple::le32) {
4239 CmdArgs.push_back("-fno-math-builtin");
4240 }
4241
4242 if (Args.hasFlag(options::OPT_fsave_optimization_record,
4243 options::OPT_fno_save_optimization_record, false)) {
4244 CmdArgs.push_back("-opt-record-file");
4245
4246 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4247 if (A) {
4248 CmdArgs.push_back(A->getValue());
4249 } else {
4250 SmallString<128> F;
4251 if (Output.isFilename() && (Args.hasArg(options::OPT_c) ||
4252 Args.hasArg(options::OPT_S))) {
4253 F = Output.getFilename();
4254 } else {
4255 // Use the input filename.
4256 F = llvm::sys::path::stem(Input.getBaseInput());
4257
4258 // If we're compiling for an offload architecture (i.e. a CUDA device),
4259 // we need to make the file name for the device compilation different
4260 // from the host compilation.
4261 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4262 !JA.isDeviceOffloading(Action::OFK_Host)) {
4263 llvm::sys::path::replace_extension(F, "");
4264 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4265 Triple.normalize());
4266 F += "-";
4267 F += JA.getOffloadingArch();
4268 }
4269 }
4270
4271 llvm::sys::path::replace_extension(F, "opt.yaml");
4272 CmdArgs.push_back(Args.MakeArgString(F));
4273 }
4274 }
4275
4276// Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4277//
4278// FIXME: Now that PR4941 has been fixed this can be enabled.
4279#if 0
4280 if (getToolChain().getTriple().isOSDarwin() &&
4281 (getToolChain().getArch() == llvm::Triple::arm ||
4282 getToolChain().getArch() == llvm::Triple::thumb)) {
4283 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4284 CmdArgs.push_back("-fno-builtin-strcat");
4285 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4286 CmdArgs.push_back("-fno-builtin-strcpy");
4287 }
4288#endif
4289
Richard Smith86a3ef52017-06-09 21:24:02 +00004290 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4291 options::OPT_fno_rewrite_imports, false);
4292 if (RewriteImports)
4293 CmdArgs.push_back("-frewrite-imports");
4294
David L. Jonesf561aba2017-03-08 01:02:16 +00004295 // Enable rewrite includes if the user's asked for it or if we're generating
4296 // diagnostics.
4297 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4298 // nice to enable this when doing a crashdump for modules as well.
4299 if (Args.hasFlag(options::OPT_frewrite_includes,
4300 options::OPT_fno_rewrite_includes, false) ||
Richard Smith86a3ef52017-06-09 21:24:02 +00004301 (C.isForDiagnostics() && (RewriteImports || !HaveAnyModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004302 CmdArgs.push_back("-frewrite-includes");
4303
4304 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4305 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4306 options::OPT_traditional_cpp)) {
4307 if (isa<PreprocessJobAction>(JA))
4308 CmdArgs.push_back("-traditional-cpp");
4309 else
4310 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4311 }
4312
4313 Args.AddLastArg(CmdArgs, options::OPT_dM);
4314 Args.AddLastArg(CmdArgs, options::OPT_dD);
4315
4316 // Handle serialized diagnostics.
4317 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4318 CmdArgs.push_back("-serialize-diagnostic-file");
4319 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4320 }
4321
4322 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4323 CmdArgs.push_back("-fretain-comments-from-system-headers");
4324
4325 // Forward -fcomment-block-commands to -cc1.
4326 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4327 // Forward -fparse-all-comments to -cc1.
4328 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4329
4330 // Turn -fplugin=name.so into -load name.so
4331 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4332 CmdArgs.push_back("-load");
4333 CmdArgs.push_back(A->getValue());
4334 A->claim();
4335 }
4336
4337 // Setup statistics file output.
4338 if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
4339 StringRef SaveStats = A->getValue();
4340
4341 SmallString<128> StatsFile;
4342 bool DoSaveStats = false;
4343 if (SaveStats == "obj") {
4344 if (Output.isFilename()) {
4345 StatsFile.assign(Output.getFilename());
4346 llvm::sys::path::remove_filename(StatsFile);
4347 }
4348 DoSaveStats = true;
4349 } else if (SaveStats == "cwd") {
4350 DoSaveStats = true;
4351 } else {
4352 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
4353 }
4354
4355 if (DoSaveStats) {
4356 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
4357 llvm::sys::path::append(StatsFile, BaseName);
4358 llvm::sys::path::replace_extension(StatsFile, "stats");
4359 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
4360 StatsFile));
4361 }
4362 }
4363
4364 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4365 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004366 // -finclude-default-header flag is for preprocessor,
4367 // do not pass it to other cc1 commands when save-temps is enabled
4368 if (C.getDriver().isSaveTempsEnabled() &&
4369 !isa<PreprocessJobAction>(JA)) {
4370 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4371 Arg->claim();
4372 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4373 CmdArgs.push_back(Arg->getValue());
4374 }
4375 }
4376 else {
4377 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4378 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004379 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4380 A->claim();
4381
4382 // We translate this by hand to the -cc1 argument, since nightly test uses
4383 // it and developers have been trained to spell it with -mllvm. Both
4384 // spellings are now deprecated and should be removed.
4385 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4386 CmdArgs.push_back("-disable-llvm-optzns");
4387 } else {
4388 A->render(Args, CmdArgs);
4389 }
4390 }
4391
4392 // With -save-temps, we want to save the unoptimized bitcode output from the
4393 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4394 // by the frontend.
4395 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4396 // has slightly different breakdown between stages.
4397 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4398 // pristine IR generated by the frontend. Ideally, a new compile action should
4399 // be added so both IR can be captured.
4400 if (C.getDriver().isSaveTempsEnabled() &&
4401 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4402 isa<CompileJobAction>(JA))
4403 CmdArgs.push_back("-disable-llvm-passes");
4404
4405 if (Output.getType() == types::TY_Dependencies) {
4406 // Handled with other dependency code.
4407 } else if (Output.isFilename()) {
4408 CmdArgs.push_back("-o");
4409 CmdArgs.push_back(Output.getFilename());
4410 } else {
4411 assert(Output.isNothing() && "Invalid output.");
4412 }
4413
4414 addDashXForInput(Args, Input, CmdArgs);
4415
4416 if (Input.isFilename())
4417 CmdArgs.push_back(Input.getFilename());
4418 else
4419 Input.getInputArg().renderAsInput(Args, CmdArgs);
4420
4421 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4422
4423 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4424
4425 // Optionally embed the -cc1 level arguments into the debug info, for build
4426 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004427 // Also record command line arguments into the debug info if
4428 // -grecord-gcc-switches options is set on.
4429 // By default, -gno-record-gcc-switches is set on and no recording.
4430 if (getToolChain().UseDwarfDebugFlags() ||
4431 Args.hasFlag(options::OPT_grecord_gcc_switches,
4432 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004433 ArgStringList OriginalArgs;
4434 for (const auto &Arg : Args)
4435 Arg->render(Args, OriginalArgs);
4436
4437 SmallString<256> Flags;
4438 Flags += Exec;
4439 for (const char *OriginalArg : OriginalArgs) {
4440 SmallString<128> EscapedArg;
4441 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4442 Flags += " ";
4443 Flags += EscapedArg;
4444 }
4445 CmdArgs.push_back("-dwarf-debug-flags");
4446 CmdArgs.push_back(Args.MakeArgString(Flags));
4447 }
4448
4449 // Add the split debug info name to the command lines here so we
4450 // can propagate it to the backend.
4451 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
4452 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4453 isa<BackendJobAction>(JA));
4454 const char *SplitDwarfOut;
4455 if (SplitDwarf) {
4456 CmdArgs.push_back("-split-dwarf-file");
4457 SplitDwarfOut = SplitDebugName(Args, Input);
4458 CmdArgs.push_back(SplitDwarfOut);
4459 }
4460
4461 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4462 // Include them with -fcuda-include-gpubinary.
4463 if (IsCuda && Inputs.size() > 1)
4464 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
4465 CmdArgs.push_back("-fcuda-include-gpubinary");
4466 CmdArgs.push_back(I->getFilename());
4467 }
4468
4469 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4470 // to specify the result of the compile phase on the host, so the meaningful
4471 // device declarations can be identified. Also, -fopenmp-is-device is passed
4472 // along to tell the frontend that it is generating code for a device, so that
4473 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004474 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004475 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004476 if (Inputs.size() == 2) {
4477 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4478 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4479 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004480 }
4481
4482 // For all the host OpenMP offloading compile jobs we need to pass the targets
4483 // information using -fopenmp-targets= option.
4484 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4485 SmallString<128> TargetInfo("-fopenmp-targets=");
4486
4487 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4488 assert(Tgts && Tgts->getNumValues() &&
4489 "OpenMP offloading has to have targets specified.");
4490 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4491 if (i)
4492 TargetInfo += ',';
4493 // We need to get the string from the triple because it may be not exactly
4494 // the same as the one we get directly from the arguments.
4495 llvm::Triple T(Tgts->getValue(i));
4496 TargetInfo += T.getTriple();
4497 }
4498 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4499 }
4500
4501 bool WholeProgramVTables =
4502 Args.hasFlag(options::OPT_fwhole_program_vtables,
4503 options::OPT_fno_whole_program_vtables, false);
4504 if (WholeProgramVTables) {
4505 if (!D.isUsingLTO())
4506 D.Diag(diag::err_drv_argument_only_allowed_with)
4507 << "-fwhole-program-vtables"
4508 << "-flto";
4509 CmdArgs.push_back("-fwhole-program-vtables");
4510 }
4511
4512 // Finally add the compile command to the compilation.
4513 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4514 Output.getType() == types::TY_Object &&
4515 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4516 auto CLCommand =
4517 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4518 C.addCommand(llvm::make_unique<FallbackCommand>(
4519 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4520 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4521 isa<PrecompileJobAction>(JA)) {
4522 // In /fallback builds, run the main compilation even if the pch generation
4523 // fails, so that the main compilation's fallback to cl.exe runs.
4524 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4525 CmdArgs, Inputs));
4526 } else {
4527 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4528 }
4529
4530 // Handle the debug info splitting at object creation time if we're
4531 // creating an object.
4532 // TODO: Currently only works on linux with newer objcopy.
4533 if (SplitDwarf && Output.getType() == types::TY_Object)
4534 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4535
4536 if (Arg *A = Args.getLastArg(options::OPT_pg))
4537 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4538 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4539 << A->getAsString(Args);
4540
4541 // Claim some arguments which clang supports automatically.
4542
4543 // -fpch-preprocess is used with gcc to add a special marker in the output to
4544 // include the PCH file. Clang's PTH solution is completely transparent, so we
4545 // do not need to deal with it at all.
4546 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4547
4548 // Claim some arguments which clang doesn't support, but we don't
4549 // care to warn the user about.
4550 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4551 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4552
4553 // Disable warnings for clang -E -emit-llvm foo.c
4554 Args.ClaimAllArgs(options::OPT_emit_llvm);
4555}
4556
4557Clang::Clang(const ToolChain &TC)
4558 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4559 // as it is for other tools. Some operations on a Tool actually test
4560 // whether that tool is Clang based on the Tool's Name as a string.
4561 : Tool("clang", "clang frontend", TC, RF_Full) {}
4562
4563Clang::~Clang() {}
4564
4565/// Add options related to the Objective-C runtime/ABI.
4566///
4567/// Returns true if the runtime is non-fragile.
4568ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4569 ArgStringList &cmdArgs,
4570 RewriteKind rewriteKind) const {
4571 // Look for the controlling runtime option.
4572 Arg *runtimeArg =
4573 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4574 options::OPT_fobjc_runtime_EQ);
4575
4576 // Just forward -fobjc-runtime= to the frontend. This supercedes
4577 // options about fragility.
4578 if (runtimeArg &&
4579 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4580 ObjCRuntime runtime;
4581 StringRef value = runtimeArg->getValue();
4582 if (runtime.tryParse(value)) {
4583 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4584 << value;
4585 }
4586
4587 runtimeArg->render(args, cmdArgs);
4588 return runtime;
4589 }
4590
4591 // Otherwise, we'll need the ABI "version". Version numbers are
4592 // slightly confusing for historical reasons:
4593 // 1 - Traditional "fragile" ABI
4594 // 2 - Non-fragile ABI, version 1
4595 // 3 - Non-fragile ABI, version 2
4596 unsigned objcABIVersion = 1;
4597 // If -fobjc-abi-version= is present, use that to set the version.
4598 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4599 StringRef value = abiArg->getValue();
4600 if (value == "1")
4601 objcABIVersion = 1;
4602 else if (value == "2")
4603 objcABIVersion = 2;
4604 else if (value == "3")
4605 objcABIVersion = 3;
4606 else
4607 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4608 } else {
4609 // Otherwise, determine if we are using the non-fragile ABI.
4610 bool nonFragileABIIsDefault =
4611 (rewriteKind == RK_NonFragile ||
4612 (rewriteKind == RK_None &&
4613 getToolChain().IsObjCNonFragileABIDefault()));
4614 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4615 options::OPT_fno_objc_nonfragile_abi,
4616 nonFragileABIIsDefault)) {
4617// Determine the non-fragile ABI version to use.
4618#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4619 unsigned nonFragileABIVersion = 1;
4620#else
4621 unsigned nonFragileABIVersion = 2;
4622#endif
4623
4624 if (Arg *abiArg =
4625 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4626 StringRef value = abiArg->getValue();
4627 if (value == "1")
4628 nonFragileABIVersion = 1;
4629 else if (value == "2")
4630 nonFragileABIVersion = 2;
4631 else
4632 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4633 << value;
4634 }
4635
4636 objcABIVersion = 1 + nonFragileABIVersion;
4637 } else {
4638 objcABIVersion = 1;
4639 }
4640 }
4641
4642 // We don't actually care about the ABI version other than whether
4643 // it's non-fragile.
4644 bool isNonFragile = objcABIVersion != 1;
4645
4646 // If we have no runtime argument, ask the toolchain for its default runtime.
4647 // However, the rewriter only really supports the Mac runtime, so assume that.
4648 ObjCRuntime runtime;
4649 if (!runtimeArg) {
4650 switch (rewriteKind) {
4651 case RK_None:
4652 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4653 break;
4654 case RK_Fragile:
4655 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4656 break;
4657 case RK_NonFragile:
4658 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4659 break;
4660 }
4661
4662 // -fnext-runtime
4663 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4664 // On Darwin, make this use the default behavior for the toolchain.
4665 if (getToolChain().getTriple().isOSDarwin()) {
4666 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4667
4668 // Otherwise, build for a generic macosx port.
4669 } else {
4670 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4671 }
4672
4673 // -fgnu-runtime
4674 } else {
4675 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4676 // Legacy behaviour is to target the gnustep runtime if we are in
4677 // non-fragile mode or the GCC runtime in fragile mode.
4678 if (isNonFragile)
4679 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4680 else
4681 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4682 }
4683
4684 cmdArgs.push_back(
4685 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4686 return runtime;
4687}
4688
4689static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4690 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4691 I += HaveDash;
4692 return !HaveDash;
4693}
4694
4695namespace {
4696struct EHFlags {
4697 bool Synch = false;
4698 bool Asynch = false;
4699 bool NoUnwindC = false;
4700};
4701} // end anonymous namespace
4702
4703/// /EH controls whether to run destructor cleanups when exceptions are
4704/// thrown. There are three modifiers:
4705/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4706/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4707/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4708/// - c: Assume that extern "C" functions are implicitly nounwind.
4709/// The default is /EHs-c-, meaning cleanups are disabled.
4710static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4711 EHFlags EH;
4712
4713 std::vector<std::string> EHArgs =
4714 Args.getAllArgValues(options::OPT__SLASH_EH);
4715 for (auto EHVal : EHArgs) {
4716 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4717 switch (EHVal[I]) {
4718 case 'a':
4719 EH.Asynch = maybeConsumeDash(EHVal, I);
4720 if (EH.Asynch)
4721 EH.Synch = false;
4722 continue;
4723 case 'c':
4724 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
4725 continue;
4726 case 's':
4727 EH.Synch = maybeConsumeDash(EHVal, I);
4728 if (EH.Synch)
4729 EH.Asynch = false;
4730 continue;
4731 default:
4732 break;
4733 }
4734 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4735 break;
4736 }
4737 }
4738 // The /GX, /GX- flags are only processed if there are not /EH flags.
4739 // The default is that /GX is not specified.
4740 if (EHArgs.empty() &&
4741 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
4742 /*default=*/false)) {
4743 EH.Synch = true;
4744 EH.NoUnwindC = true;
4745 }
4746
4747 return EH;
4748}
4749
4750void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
4751 ArgStringList &CmdArgs,
4752 codegenoptions::DebugInfoKind *DebugInfoKind,
4753 bool *EmitCodeView) const {
4754 unsigned RTOptionID = options::OPT__SLASH_MT;
4755
4756 if (Args.hasArg(options::OPT__SLASH_LDd))
4757 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4758 // but defining _DEBUG is sticky.
4759 RTOptionID = options::OPT__SLASH_MTd;
4760
4761 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4762 RTOptionID = A->getOption().getID();
4763
4764 StringRef FlagForCRT;
4765 switch (RTOptionID) {
4766 case options::OPT__SLASH_MD:
4767 if (Args.hasArg(options::OPT__SLASH_LDd))
4768 CmdArgs.push_back("-D_DEBUG");
4769 CmdArgs.push_back("-D_MT");
4770 CmdArgs.push_back("-D_DLL");
4771 FlagForCRT = "--dependent-lib=msvcrt";
4772 break;
4773 case options::OPT__SLASH_MDd:
4774 CmdArgs.push_back("-D_DEBUG");
4775 CmdArgs.push_back("-D_MT");
4776 CmdArgs.push_back("-D_DLL");
4777 FlagForCRT = "--dependent-lib=msvcrtd";
4778 break;
4779 case options::OPT__SLASH_MT:
4780 if (Args.hasArg(options::OPT__SLASH_LDd))
4781 CmdArgs.push_back("-D_DEBUG");
4782 CmdArgs.push_back("-D_MT");
4783 CmdArgs.push_back("-flto-visibility-public-std");
4784 FlagForCRT = "--dependent-lib=libcmt";
4785 break;
4786 case options::OPT__SLASH_MTd:
4787 CmdArgs.push_back("-D_DEBUG");
4788 CmdArgs.push_back("-D_MT");
4789 CmdArgs.push_back("-flto-visibility-public-std");
4790 FlagForCRT = "--dependent-lib=libcmtd";
4791 break;
4792 default:
4793 llvm_unreachable("Unexpected option ID.");
4794 }
4795
4796 if (Args.hasArg(options::OPT__SLASH_Zl)) {
4797 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4798 } else {
4799 CmdArgs.push_back(FlagForCRT.data());
4800
4801 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4802 // users want. The /Za flag to cl.exe turns this off, but it's not
4803 // implemented in clang.
4804 CmdArgs.push_back("--dependent-lib=oldnames");
4805 }
4806
4807 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4808 // would produce interleaved output, so ignore /showIncludes in such cases.
4809 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
4810 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4811 A->render(Args, CmdArgs);
4812
4813 // This controls whether or not we emit RTTI data for polymorphic types.
4814 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4815 /*default=*/false))
4816 CmdArgs.push_back("-fno-rtti-data");
4817
4818 // This controls whether or not we emit stack-protector instrumentation.
4819 // In MSVC, Buffer Security Check (/GS) is on by default.
4820 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
4821 /*default=*/true)) {
4822 CmdArgs.push_back("-stack-protector");
4823 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
4824 }
4825
4826 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
4827 if (Arg *DebugInfoArg =
4828 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
4829 options::OPT_gline_tables_only)) {
4830 *EmitCodeView = true;
4831 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
4832 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
4833 else
4834 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4835 CmdArgs.push_back("-gcodeview");
4836 } else {
4837 *EmitCodeView = false;
4838 }
4839
4840 const Driver &D = getToolChain().getDriver();
4841 EHFlags EH = parseClangCLEHFlags(D, Args);
4842 if (EH.Synch || EH.Asynch) {
4843 if (types::isCXX(InputType))
4844 CmdArgs.push_back("-fcxx-exceptions");
4845 CmdArgs.push_back("-fexceptions");
4846 }
4847 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
4848 CmdArgs.push_back("-fexternc-nounwind");
4849
4850 // /EP should expand to -E -P.
4851 if (Args.hasArg(options::OPT__SLASH_EP)) {
4852 CmdArgs.push_back("-E");
4853 CmdArgs.push_back("-P");
4854 }
4855
4856 unsigned VolatileOptionID;
4857 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
4858 getToolChain().getArch() == llvm::Triple::x86)
4859 VolatileOptionID = options::OPT__SLASH_volatile_ms;
4860 else
4861 VolatileOptionID = options::OPT__SLASH_volatile_iso;
4862
4863 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
4864 VolatileOptionID = A->getOption().getID();
4865
4866 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
4867 CmdArgs.push_back("-fms-volatile");
4868
4869 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
4870 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
4871 if (MostGeneralArg && BestCaseArg)
4872 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4873 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
4874
4875 if (MostGeneralArg) {
4876 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
4877 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
4878 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
4879
4880 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
4881 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
4882 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
4883 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4884 << FirstConflict->getAsString(Args)
4885 << SecondConflict->getAsString(Args);
4886
4887 if (SingleArg)
4888 CmdArgs.push_back("-fms-memptr-rep=single");
4889 else if (MultipleArg)
4890 CmdArgs.push_back("-fms-memptr-rep=multiple");
4891 else
4892 CmdArgs.push_back("-fms-memptr-rep=virtual");
4893 }
4894
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004895 // Parse the default calling convention options.
4896 if (Arg *CCArg =
4897 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
4898 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv)) {
4899 unsigned DCCOptId = CCArg->getOption().getID();
4900 const char *DCCFlag = nullptr;
4901 bool ArchSupported = true;
4902 llvm::Triple::ArchType Arch = getToolChain().getArch();
4903 switch (DCCOptId) {
4904 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00004905 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004906 break;
4907 case options::OPT__SLASH_Gr:
4908 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00004909 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004910 break;
4911 case options::OPT__SLASH_Gz:
4912 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00004913 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004914 break;
4915 case options::OPT__SLASH_Gv:
4916 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00004917 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00004918 break;
4919 }
4920
4921 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
4922 if (ArchSupported && DCCFlag)
4923 CmdArgs.push_back(DCCFlag);
4924 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004925
4926 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
4927 A->render(Args, CmdArgs);
4928
4929 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
4930 CmdArgs.push_back("-fdiagnostics-format");
4931 if (Args.hasArg(options::OPT__SLASH_fallback))
4932 CmdArgs.push_back("msvc-fallback");
4933 else
4934 CmdArgs.push_back("msvc");
4935 }
4936}
4937
4938visualstudio::Compiler *Clang::getCLFallback() const {
4939 if (!CLFallback)
4940 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
4941 return CLFallback.get();
4942}
4943
4944
4945const char *Clang::getBaseInputName(const ArgList &Args,
4946 const InputInfo &Input) {
4947 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
4948}
4949
4950const char *Clang::getBaseInputStem(const ArgList &Args,
4951 const InputInfoList &Inputs) {
4952 const char *Str = getBaseInputName(Args, Inputs[0]);
4953
4954 if (const char *End = strrchr(Str, '.'))
4955 return Args.MakeArgString(std::string(Str, End));
4956
4957 return Str;
4958}
4959
4960const char *Clang::getDependencyFileName(const ArgList &Args,
4961 const InputInfoList &Inputs) {
4962 // FIXME: Think about this more.
4963 std::string Res;
4964
4965 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4966 std::string Str(OutputOpt->getValue());
4967 Res = Str.substr(0, Str.rfind('.'));
4968 } else {
4969 Res = getBaseInputStem(Args, Inputs);
4970 }
4971 return Args.MakeArgString(Res + ".d");
4972}
4973
4974// Begin ClangAs
4975
4976void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
4977 ArgStringList &CmdArgs) const {
4978 StringRef CPUName;
4979 StringRef ABIName;
4980 const llvm::Triple &Triple = getToolChain().getTriple();
4981 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
4982
4983 CmdArgs.push_back("-target-abi");
4984 CmdArgs.push_back(ABIName.data());
4985}
4986
4987void ClangAs::AddX86TargetArgs(const ArgList &Args,
4988 ArgStringList &CmdArgs) const {
4989 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
4990 StringRef Value = A->getValue();
4991 if (Value == "intel" || Value == "att") {
4992 CmdArgs.push_back("-mllvm");
4993 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
4994 } else {
4995 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
4996 << A->getOption().getName() << Value;
4997 }
4998 }
4999}
5000
5001void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5002 const InputInfo &Output, const InputInfoList &Inputs,
5003 const ArgList &Args,
5004 const char *LinkingOutput) const {
5005 ArgStringList CmdArgs;
5006
5007 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5008 const InputInfo &Input = Inputs[0];
5009
5010 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5011 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005012 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005013
5014 // Don't warn about "clang -w -c foo.s"
5015 Args.ClaimAllArgs(options::OPT_w);
5016 // and "clang -emit-llvm -c foo.s"
5017 Args.ClaimAllArgs(options::OPT_emit_llvm);
5018
5019 claimNoWarnArgs(Args);
5020
5021 // Invoke ourselves in -cc1as mode.
5022 //
5023 // FIXME: Implement custom jobs for internal actions.
5024 CmdArgs.push_back("-cc1as");
5025
5026 // Add the "effective" target triple.
5027 CmdArgs.push_back("-triple");
5028 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5029
5030 // Set the output mode, we currently only expect to be used as a real
5031 // assembler.
5032 CmdArgs.push_back("-filetype");
5033 CmdArgs.push_back("obj");
5034
5035 // Set the main file name, so that debug info works even with
5036 // -save-temps or preprocessed assembly.
5037 CmdArgs.push_back("-main-file-name");
5038 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5039
5040 // Add the target cpu
5041 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5042 if (!CPU.empty()) {
5043 CmdArgs.push_back("-target-cpu");
5044 CmdArgs.push_back(Args.MakeArgString(CPU));
5045 }
5046
5047 // Add the target features
5048 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5049
5050 // Ignore explicit -force_cpusubtype_ALL option.
5051 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5052
5053 // Pass along any -I options so we get proper .include search paths.
5054 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5055
5056 // Determine the original source input.
5057 const Action *SourceAction = &JA;
5058 while (SourceAction->getKind() != Action::InputClass) {
5059 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5060 SourceAction = SourceAction->getInputs()[0];
5061 }
5062
5063 // Forward -g and handle debug info related flags, assuming we are dealing
5064 // with an actual assembly file.
5065 bool WantDebug = false;
5066 unsigned DwarfVersion = 0;
5067 Args.ClaimAllArgs(options::OPT_g_Group);
5068 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5069 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5070 !A->getOption().matches(options::OPT_ggdb0);
5071 if (WantDebug)
5072 DwarfVersion = DwarfVersionNum(A->getSpelling());
5073 }
5074 if (DwarfVersion == 0)
5075 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5076
5077 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5078
5079 if (SourceAction->getType() == types::TY_Asm ||
5080 SourceAction->getType() == types::TY_PP_Asm) {
5081 // You might think that it would be ok to set DebugInfoKind outside of
5082 // the guard for source type, however there is a test which asserts
5083 // that some assembler invocation receives no -debug-info-kind,
5084 // and it's not clear whether that test is just overly restrictive.
5085 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5086 : codegenoptions::NoDebugInfo);
5087 // Add the -fdebug-compilation-dir flag if needed.
5088 addDebugCompDirArg(Args, CmdArgs);
5089
5090 // Set the AT_producer to the clang version when using the integrated
5091 // assembler on assembly source files.
5092 CmdArgs.push_back("-dwarf-debug-producer");
5093 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5094
5095 // And pass along -I options
5096 Args.AddAllArgs(CmdArgs, options::OPT_I);
5097 }
5098 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5099 llvm::DebuggerKind::Default);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005100 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5101
David L. Jonesf561aba2017-03-08 01:02:16 +00005102
5103 // Handle -fPIC et al -- the relocation-model affects the assembler
5104 // for some targets.
5105 llvm::Reloc::Model RelocationModel;
5106 unsigned PICLevel;
5107 bool IsPIE;
5108 std::tie(RelocationModel, PICLevel, IsPIE) =
5109 ParsePICArgs(getToolChain(), Args);
5110
5111 const char *RMName = RelocationModelName(RelocationModel);
5112 if (RMName) {
5113 CmdArgs.push_back("-mrelocation-model");
5114 CmdArgs.push_back(RMName);
5115 }
5116
5117 // Optionally embed the -cc1as level arguments into the debug info, for build
5118 // analysis.
5119 if (getToolChain().UseDwarfDebugFlags()) {
5120 ArgStringList OriginalArgs;
5121 for (const auto &Arg : Args)
5122 Arg->render(Args, OriginalArgs);
5123
5124 SmallString<256> Flags;
5125 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5126 Flags += Exec;
5127 for (const char *OriginalArg : OriginalArgs) {
5128 SmallString<128> EscapedArg;
5129 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5130 Flags += " ";
5131 Flags += EscapedArg;
5132 }
5133 CmdArgs.push_back("-dwarf-debug-flags");
5134 CmdArgs.push_back(Args.MakeArgString(Flags));
5135 }
5136
5137 // FIXME: Add -static support, once we have it.
5138
5139 // Add target specific flags.
5140 switch (getToolChain().getArch()) {
5141 default:
5142 break;
5143
5144 case llvm::Triple::mips:
5145 case llvm::Triple::mipsel:
5146 case llvm::Triple::mips64:
5147 case llvm::Triple::mips64el:
5148 AddMIPSTargetArgs(Args, CmdArgs);
5149 break;
5150
5151 case llvm::Triple::x86:
5152 case llvm::Triple::x86_64:
5153 AddX86TargetArgs(Args, CmdArgs);
5154 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005155
5156 case llvm::Triple::arm:
5157 case llvm::Triple::armeb:
5158 case llvm::Triple::thumb:
5159 case llvm::Triple::thumbeb:
5160 // This isn't in AddARMTargetArgs because we want to do this for assembly
5161 // only, not C/C++.
5162 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5163 options::OPT_mno_default_build_attributes, true)) {
5164 CmdArgs.push_back("-mllvm");
5165 CmdArgs.push_back("-arm-add-build-attributes");
5166 }
5167 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005168 }
5169
5170 // Consume all the warning flags. Usually this would be handled more
5171 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5172 // doesn't handle that so rather than warning about unused flags that are
5173 // actually used, we'll lie by omission instead.
5174 // FIXME: Stop lying and consume only the appropriate driver flags
5175 Args.ClaimAllArgs(options::OPT_W_Group);
5176
5177 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5178 getToolChain().getDriver());
5179
5180 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5181
5182 assert(Output.isFilename() && "Unexpected lipo output.");
5183 CmdArgs.push_back("-o");
5184 CmdArgs.push_back(Output.getFilename());
5185
5186 assert(Input.isFilename() && "Invalid input.");
5187 CmdArgs.push_back(Input.getFilename());
5188
5189 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5190 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5191
5192 // Handle the debug info splitting at object creation time if we're
5193 // creating an object.
5194 // TODO: Currently only works on linux with newer objcopy.
5195 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5196 getToolChain().getTriple().isOSLinux())
5197 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5198 SplitDebugName(Args, Input));
5199}
5200
5201// Begin OffloadBundler
5202
5203void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5204 const InputInfo &Output,
5205 const InputInfoList &Inputs,
5206 const llvm::opt::ArgList &TCArgs,
5207 const char *LinkingOutput) const {
5208 // The version with only one output is expected to refer to a bundling job.
5209 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5210
5211 // The bundling command looks like this:
5212 // clang-offload-bundler -type=bc
5213 // -targets=host-triple,openmp-triple1,openmp-triple2
5214 // -outputs=input_file
5215 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5216
5217 ArgStringList CmdArgs;
5218
5219 // Get the type.
5220 CmdArgs.push_back(TCArgs.MakeArgString(
5221 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5222
5223 assert(JA.getInputs().size() == Inputs.size() &&
5224 "Not have inputs for all dependence actions??");
5225
5226 // Get the targets.
5227 SmallString<128> Triples;
5228 Triples += "-targets=";
5229 for (unsigned I = 0; I < Inputs.size(); ++I) {
5230 if (I)
5231 Triples += ',';
5232
5233 Action::OffloadKind CurKind = Action::OFK_Host;
5234 const ToolChain *CurTC = &getToolChain();
5235 const Action *CurDep = JA.getInputs()[I];
5236
5237 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
5238 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
5239 CurKind = A->getOffloadingDeviceKind();
5240 CurTC = TC;
5241 });
5242 }
5243 Triples += Action::GetOffloadKindName(CurKind);
5244 Triples += '-';
5245 Triples += CurTC->getTriple().normalize();
5246 }
5247 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5248
5249 // Get bundled file command.
5250 CmdArgs.push_back(
5251 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5252
5253 // Get unbundled files command.
5254 SmallString<128> UB;
5255 UB += "-inputs=";
5256 for (unsigned I = 0; I < Inputs.size(); ++I) {
5257 if (I)
5258 UB += ',';
5259 UB += Inputs[I].getFilename();
5260 }
5261 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5262
5263 // All the inputs are encoded as commands.
5264 C.addCommand(llvm::make_unique<Command>(
5265 JA, *this,
5266 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5267 CmdArgs, None));
5268}
5269
5270void OffloadBundler::ConstructJobMultipleOutputs(
5271 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5272 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5273 const char *LinkingOutput) const {
5274 // The version with multiple outputs is expected to refer to a unbundling job.
5275 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5276
5277 // The unbundling command looks like this:
5278 // clang-offload-bundler -type=bc
5279 // -targets=host-triple,openmp-triple1,openmp-triple2
5280 // -inputs=input_file
5281 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5282 // -unbundle
5283
5284 ArgStringList CmdArgs;
5285
5286 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5287 InputInfo Input = Inputs.front();
5288
5289 // Get the type.
5290 CmdArgs.push_back(TCArgs.MakeArgString(
5291 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5292
5293 // Get the targets.
5294 SmallString<128> Triples;
5295 Triples += "-targets=";
5296 auto DepInfo = UA.getDependentActionsInfo();
5297 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5298 if (I)
5299 Triples += ',';
5300
5301 auto &Dep = DepInfo[I];
5302 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5303 Triples += '-';
5304 Triples += Dep.DependentToolChain->getTriple().normalize();
5305 }
5306
5307 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5308
5309 // Get bundled file command.
5310 CmdArgs.push_back(
5311 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5312
5313 // Get unbundled files command.
5314 SmallString<128> UB;
5315 UB += "-outputs=";
5316 for (unsigned I = 0; I < Outputs.size(); ++I) {
5317 if (I)
5318 UB += ',';
5319 UB += Outputs[I].getFilename();
5320 }
5321 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5322 CmdArgs.push_back("-unbundle");
5323
5324 // All the inputs are encoded as commands.
5325 C.addCommand(llvm::make_unique<Command>(
5326 JA, *this,
5327 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5328 CmdArgs, None));
5329}