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