Bug Summary

File:tools/clang/lib/Driver/ToolChains/Clang.cpp
Warning:line 3032, column 5
Value stored to 'IsWindowsGNU' is never read

Annotated Source Code

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