Coverage Report

Created: 2021-03-06 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "Clang.h"
10
#include "AMDGPU.h"
11
#include "Arch/AArch64.h"
12
#include "Arch/ARM.h"
13
#include "Arch/Mips.h"
14
#include "Arch/PPC.h"
15
#include "Arch/RISCV.h"
16
#include "Arch/Sparc.h"
17
#include "Arch/SystemZ.h"
18
#include "Arch/VE.h"
19
#include "Arch/X86.h"
20
#include "CommonArgs.h"
21
#include "Hexagon.h"
22
#include "InputInfo.h"
23
#include "MSP430.h"
24
#include "PS4CPU.h"
25
#include "clang/Basic/CharInfo.h"
26
#include "clang/Basic/CodeGenOptions.h"
27
#include "clang/Basic/LangOptions.h"
28
#include "clang/Basic/ObjCRuntime.h"
29
#include "clang/Basic/Version.h"
30
#include "clang/Driver/Distro.h"
31
#include "clang/Driver/DriverDiagnostic.h"
32
#include "clang/Driver/Options.h"
33
#include "clang/Driver/SanitizerArgs.h"
34
#include "clang/Driver/XRayArgs.h"
35
#include "llvm/ADT/StringExtras.h"
36
#include "llvm/Config/llvm-config.h"
37
#include "llvm/Option/ArgList.h"
38
#include "llvm/Support/CodeGen.h"
39
#include "llvm/Support/Compiler.h"
40
#include "llvm/Support/Compression.h"
41
#include "llvm/Support/FileSystem.h"
42
#include "llvm/Support/Host.h"
43
#include "llvm/Support/Path.h"
44
#include "llvm/Support/Process.h"
45
#include "llvm/Support/TargetParser.h"
46
#include "llvm/Support/YAMLParser.h"
47
48
using namespace clang::driver;
49
using namespace clang::driver::tools;
50
using namespace clang;
51
using namespace llvm::opt;
52
53
41.7k
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
54
41.7k
  if (Arg *A =
55
5
          Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
56
5
    if (!Args.hasArg(options::OPT_E) && 
!Args.hasArg(options::OPT__SLASH_P)2
&&
57
1
        !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
58
1
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
59
1
          << A->getBaseArg().getAsString(Args)
60
1
          << (D.IsCLMode() ? "/E, /P or /EP" : 
"-E"0
);
61
1
    }
62
5
  }
63
41.7k
}
64
65
42.1k
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
66
  // In gcc, only ARM checks this, but it seems reasonable to check universally.
67
42.1k
  if (Args.hasArg(options::OPT_static))
68
110
    if (const Arg *A =
69
110
            Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
70
1
      D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
71
1
                                                      << "-static";
72
42.1k
}
73
74
// Add backslashes to escape spaces and other backslashes.
75
// This is used for the space-separated argument list specified with
76
// the -dwarf-debug-flags option.
77
static void EscapeSpacesAndBackslashes(const char *Arg,
78
1.29k
                                       SmallVectorImpl<char> &Res) {
79
34.8k
  for (; *Arg; 
++Arg33.5k
) {
80
33.5k
    switch (*Arg) {
81
33.4k
    default:
82
33.4k
      break;
83
17
    case ' ':
84
18
    case '\\':
85
18
      Res.push_back('\\');
86
18
      break;
87
33.5k
    }
88
33.5k
    Res.push_back(*Arg);
89
33.5k
  }
90
1.29k
}
91
92
// Quote target names for inclusion in GNU Make dependency files.
93
// Only the characters '$', '#', ' ', '\t' are quoted.
94
42
static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
95
1.27k
  for (unsigned i = 0, e = Target.size(); i != e; 
++i1.22k
) {
96
1.22k
    switch (Target[i]) {
97
5
    case ' ':
98
5
    case '\t':
99
      // Escape the preceding backslashes
100
8
      for (int j = i - 1; j >= 0 && 
Target[j] == '\\'7
;
--j3
)
101
3
        Res.push_back('\\');
102
103
      // Escape the space/tab
104
5
      Res.push_back('\\');
105
5
      break;
106
2
    case '$':
107
2
      Res.push_back('$');
108
2
      break;
109
1
    case '#':
110
1
      Res.push_back('\\');
111
1
      break;
112
1.22k
    default:
113
1.22k
      break;
114
1.22k
    }
115
116
1.22k
    Res.push_back(Target[i]);
117
1.22k
  }
118
42
}
119
120
/// Apply \a Work on the current tool chain \a RegularToolChain and any other
121
/// offloading tool chain that is associated with the current action \a JA.
122
static void
123
forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
124
                           const ToolChain &RegularToolChain,
125
69.8k
                           llvm::function_ref<void(const ToolChain &)> Work) {
126
  // Apply Work on the current/regular tool chain.
127
69.8k
  Work(RegularToolChain);
128
129
  // Apply Work on all the offloading tool chains associated with the current
130
  // action.
131
69.8k
  if (JA.isHostOffloading(Action::OFK_Cuda))
132
434
    Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
133
69.4k
  else if (JA.isDeviceOffloading(Action::OFK_Cuda))
134
532
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
135
68.8k
  else if (JA.isHostOffloading(Action::OFK_HIP))
136
288
    Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
137
68.5k
  else if (JA.isDeviceOffloading(Action::OFK_HIP))
138
456
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
139
140
69.8k
  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
141
116
    auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
142
240
    for (auto II = TCs.first, IE = TCs.second; II != IE; 
++II124
)
143
124
      Work(*II->second);
144
69.7k
  } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
145
71
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
146
147
  //
148
  // TODO: Add support for other offloading programming models here.
149
  //
150
69.8k
}
151
152
/// This is a helper function for validating the optional refinement step
153
/// parameter in reciprocal argument strings. Return false if there is an error
154
/// parsing the refinement step. Otherwise, return true and set the Position
155
/// of the refinement step in the input string.
156
static bool getRefinementStep(StringRef In, const Driver &D,
157
32
                              const Arg &A, size_t &Position) {
158
32
  const char RefinementStepToken = ':';
159
32
  Position = In.find(RefinementStepToken);
160
32
  if (Position != StringRef::npos) {
161
12
    StringRef Option = A.getOption().getName();
162
12
    StringRef RefStep = In.substr(Position + 1);
163
    // Allow exactly one numeric character for the additional refinement
164
    // step parameter. This is reasonable for all currently-supported
165
    // operations and architectures because we would expect that a larger value
166
    // of refinement steps would cause the estimate "optimization" to
167
    // under-perform the native operation. Also, if the estimate does not
168
    // converge quickly, it probably will not ever converge, so further
169
    // refinement steps will not produce a better answer.
170
12
    if (RefStep.size() != 1) {
171
2
      D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
172
2
      return false;
173
2
    }
174
10
    char RefStepChar = RefStep[0];
175
10
    if (RefStepChar < '0' || RefStepChar > '9') {
176
0
      D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
177
0
      return false;
178
0
    }
179
10
  }
180
30
  return true;
181
32
}
182
183
/// The -mrecip flag requires processing of many optional parameters.
184
static void ParseMRecip(const Driver &D, const ArgList &Args,
185
42.1k
                        ArgStringList &OutStrings) {
186
42.1k
  StringRef DisabledPrefixIn = "!";
187
42.1k
  StringRef DisabledPrefixOut = "!";
188
42.1k
  StringRef EnabledPrefixOut = "";
189
42.1k
  StringRef Out = "-mrecip=";
190
191
42.1k
  Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
192
42.1k
  if (!A)
193
42.1k
    return;
194
195
18
  unsigned NumOptions = A->getNumValues();
196
18
  if (NumOptions == 0) {
197
    // No option is the same as "all".
198
1
    OutStrings.push_back(Args.MakeArgString(Out + "all"));
199
1
    return;
200
1
  }
201
202
  // Pass through "all", "none", or "default" with an optional refinement step.
203
17
  if (NumOptions == 1) {
204
12
    StringRef Val = A->getValue(0);
205
12
    size_t RefStepLoc;
206
12
    if (!getRefinementStep(Val, D, *A, RefStepLoc))
207
2
      return;
208
10
    StringRef ValBase = Val.slice(0, RefStepLoc);
209
10
    if (ValBase == "all" || 
ValBase == "none"8
||
ValBase == "default"7
) {
210
4
      OutStrings.push_back(Args.MakeArgString(Out + Val));
211
4
      return;
212
4
    }
213
10
  }
214
215
  // Each reciprocal type may be enabled or disabled individually.
216
  // Check each input value for validity, concatenate them all back together,
217
  // and pass through.
218
219
11
  llvm::StringMap<bool> OptionStrings;
220
11
  OptionStrings.insert(std::make_pair("divd", false));
221
11
  OptionStrings.insert(std::make_pair("divf", false));
222
11
  OptionStrings.insert(std::make_pair("vec-divd", false));
223
11
  OptionStrings.insert(std::make_pair("vec-divf", false));
224
11
  OptionStrings.insert(std::make_pair("sqrtd", false));
225
11
  OptionStrings.insert(std::make_pair("sqrtf", false));
226
11
  OptionStrings.insert(std::make_pair("vec-sqrtd", false));
227
11
  OptionStrings.insert(std::make_pair("vec-sqrtf", false));
228
229
28
  for (unsigned i = 0; i != NumOptions; 
++i17
) {
230
20
    StringRef Val = A->getValue(i);
231
232
20
    bool IsDisabled = Val.startswith(DisabledPrefixIn);
233
    // Ignore the disablement token for string matching.
234
20
    if (IsDisabled)
235
3
      Val = Val.substr(1);
236
237
20
    size_t RefStep;
238
20
    if (!getRefinementStep(Val, D, *A, RefStep))
239
0
      return;
240
241
20
    StringRef ValBase = Val.slice(0, RefStep);
242
20
    llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
243
20
    if (OptionIter == OptionStrings.end()) {
244
      // Try again specifying float suffix.
245
6
      OptionIter = OptionStrings.find(ValBase.str() + 'f');
246
6
      if (OptionIter == OptionStrings.end()) {
247
        // The input name did not match any known option string.
248
1
        D.Diag(diag::err_drv_unknown_argument) << Val;
249
1
        return;
250
1
      }
251
      // The option was specified without a float or double suffix.
252
      // Make sure that the double entry was not already specified.
253
      // The float entry will be checked below.
254
5
      if (OptionStrings[ValBase.str() + 'd']) {
255
0
        D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
256
0
        return;
257
0
      }
258
5
    }
259
260
19
    if (OptionIter->second == true) {
261
      // Duplicate option specified.
262
2
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
263
2
      return;
264
2
    }
265
266
    // Mark the matched option as found. Do not allow duplicate specifiers.
267
17
    OptionIter->second = true;
268
269
    // If the precision was not specified, also mark the double entry as found.
270
17
    if (ValBase.back() != 'f' && 
ValBase.back() != 'd'11
)
271
5
      OptionStrings[ValBase.str() + 'd'] = true;
272
273
    // Build the output string.
274
17
    StringRef Prefix = IsDisabled ? 
DisabledPrefixOut3
:
EnabledPrefixOut14
;
275
17
    Out = Args.MakeArgString(Out + Prefix + Val);
276
17
    if (i != NumOptions - 1)
277
9
      Out = Args.MakeArgString(Out + ",");
278
17
  }
279
280
8
  OutStrings.push_back(Args.MakeArgString(Out));
281
8
}
282
283
/// The -mprefer-vector-width option accepts either a positive integer
284
/// or the string "none".
285
static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
286
42.1k
                                    ArgStringList &CmdArgs) {
287
42.1k
  Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
288
42.1k
  if (!A)
289
42.1k
    return;
290
291
5
  StringRef Value = A->getValue();
292
5
  if (Value == "none") {
293
1
    CmdArgs.push_back("-mprefer-vector-width=none");
294
4
  } else {
295
4
    unsigned Width;
296
4
    if (Value.getAsInteger(10, Width)) {
297
3
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
298
3
      return;
299
3
    }
300
1
    CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
301
1
  }
302
5
}
303
304
static void getWebAssemblyTargetFeatures(const ArgList &Args,
305
74
                                         std::vector<StringRef> &Features) {
306
74
  handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
307
74
}
308
309
static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
310
                              const ArgList &Args, ArgStringList &CmdArgs,
311
43.1k
                              bool ForAS, bool IsAux = false) {
312
43.1k
  std::vector<StringRef> Features;
313
43.1k
  switch (Triple.getArch()) {
314
526
  default:
315
526
    break;
316
341
  case llvm::Triple::mips:
317
453
  case llvm::Triple::mipsel:
318
583
  case llvm::Triple::mips64:
319
672
  case llvm::Triple::mips64el:
320
672
    mips::getMIPSTargetFeatures(D, Triple, Args, Features);
321
672
    break;
322
323
1.06k
  case llvm::Triple::arm:
324
1.22k
  case llvm::Triple::armeb:
325
1.78k
  case llvm::Triple::thumb:
326
1.88k
  case llvm::Triple::thumbeb:
327
1.88k
    arm::getARMTargetFeatures(D, Triple, Args, CmdArgs, Features, ForAS);
328
1.88k
    break;
329
330
103
  case llvm::Triple::ppc:
331
110
  case llvm::Triple::ppcle:
332
278
  case llvm::Triple::ppc64:
333
488
  case llvm::Triple::ppc64le:
334
488
    ppc::getPPCTargetFeatures(D, Triple, Args, Features);
335
488
    break;
336
233
  case llvm::Triple::riscv32:
337
401
  case llvm::Triple::riscv64:
338
401
    riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
339
401
    break;
340
65
  case llvm::Triple::systemz:
341
65
    systemz::getSystemZTargetFeatures(D, Args, Features);
342
65
    break;
343
1.05k
  case llvm::Triple::aarch64:
344
1.05k
  case llvm::Triple::aarch64_32:
345
1.23k
  case llvm::Triple::aarch64_be:
346
1.23k
    aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
347
1.23k
    break;
348
10.3k
  case llvm::Triple::x86:
349
36.9k
  case llvm::Triple::x86_64:
350
36.9k
    x86::getX86TargetFeatures(D, Triple, Args, Features);
351
36.9k
    break;
352
96
  case llvm::Triple::hexagon:
353
96
    hexagon::getHexagonTargetFeatures(D, Args, Features);
354
96
    break;
355
55
  case llvm::Triple::wasm32:
356
74
  case llvm::Triple::wasm64:
357
74
    getWebAssemblyTargetFeatures(Args, Features);
358
74
    break;
359
94
  case llvm::Triple::sparc:
360
115
  case llvm::Triple::sparcel:
361
166
  case llvm::Triple::sparcv9:
362
166
    sparc::getSparcTargetFeatures(D, Args, Features);
363
166
    break;
364
54
  case llvm::Triple::r600:
365
544
  case llvm::Triple::amdgcn:
366
544
    amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
367
544
    break;
368
51
  case llvm::Triple::msp430:
369
51
    msp430::getMSP430TargetFeatures(D, Args, Features);
370
51
    break;
371
0
  case llvm::Triple::ve:
372
0
    ve::getVETargetFeatures(D, Args, Features);
373
0
    break;
374
43.1k
  }
375
376
46.8k
  
for (auto Feature : unifyTargetFeatures(Features))43.1k
{
377
46.8k
    CmdArgs.push_back(IsAux ? 
"-aux-target-feature"2
:
"-target-feature"46.8k
);
378
46.8k
    CmdArgs.push_back(Feature.data());
379
46.8k
  }
380
43.1k
}
381
382
static bool
383
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
384
3.21k
                                          const llvm::Triple &Triple) {
385
  // We use the zero-cost exception tables for Objective-C if the non-fragile
386
  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
387
  // later.
388
3.21k
  if (runtime.isNonFragile())
389
3.15k
    return true;
390
391
58
  if (!Triple.isMacOSX())
392
42
    return false;
393
394
16
  return (!Triple.isMacOSXVersionLT(10, 5) &&
395
13
          (Triple.getArch() == llvm::Triple::x86_64 ||
396
9
           Triple.getArch() == llvm::Triple::arm));
397
58
}
398
399
/// Adds exception related arguments to the driver command arguments. There's a
400
/// master flag, -fexceptions and also language specific flags to enable/disable
401
/// C++ and Objective-C exceptions. This makes it possible to for example
402
/// disable C++ exceptions but enable Objective-C exceptions.
403
static void addExceptionArgs(const ArgList &Args, types::ID InputType,
404
                             const ToolChain &TC, bool KernelOrKext,
405
                             const ObjCRuntime &objcRuntime,
406
41.6k
                             ArgStringList &CmdArgs) {
407
41.6k
  const llvm::Triple &Triple = TC.getTriple();
408
409
41.6k
  if (KernelOrKext) {
410
    // -mkernel and -fapple-kext imply no exceptions, so claim exception related
411
    // arguments now to avoid warnings about unused arguments.
412
27
    Args.ClaimAllArgs(options::OPT_fexceptions);
413
27
    Args.ClaimAllArgs(options::OPT_fno_exceptions);
414
27
    Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
415
27
    Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
416
27
    Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
417
27
    Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
418
27
    return;
419
27
  }
420
421
  // See if the user explicitly enabled exceptions.
422
41.5k
  bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
423
41.5k
                         false);
424
425
  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
426
  // is not necessarily sensible, but follows GCC.
427
41.5k
  if (types::isObjC(InputType) &&
428
3.21k
      Args.hasFlag(options::OPT_fobjc_exceptions,
429
3.21k
                   options::OPT_fno_objc_exceptions, true)) {
430
3.21k
    CmdArgs.push_back("-fobjc-exceptions");
431
432
3.21k
    EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
433
3.21k
  }
434
435
41.5k
  if (types::isCXX(InputType)) {
436
    // Disable C++ EH by default on XCore and PS4.
437
28.0k
    bool CXXExceptionsEnabled =
438
28.0k
        Triple.getArch() != llvm::Triple::xcore && 
!Triple.isPS4CPU()28.0k
;
439
28.0k
    Arg *ExceptionArg = Args.getLastArg(
440
28.0k
        options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
441
28.0k
        options::OPT_fexceptions, options::OPT_fno_exceptions);
442
28.0k
    if (ExceptionArg)
443
12.4k
      CXXExceptionsEnabled =
444
12.4k
          ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
445
12.4k
          ExceptionArg->getOption().matches(options::OPT_fexceptions);
446
447
28.0k
    if (CXXExceptionsEnabled) {
448
28.0k
      CmdArgs.push_back("-fcxx-exceptions");
449
450
28.0k
      EH = true;
451
28.0k
    }
452
28.0k
  }
453
454
  // OPT_fignore_exceptions means exception could still be thrown,
455
  // but no clean up or catch would happen in current module.
456
  // So we do not set EH to false.
457
41.5k
  Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
458
459
41.5k
  if (EH)
460
31.0k
    CmdArgs.push_back("-fexceptions");
461
41.5k
}
462
463
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
464
42.1k
                                 const JobAction &JA) {
465
42.1k
  bool Default = true;
466
42.1k
  if (TC.getTriple().isOSDarwin()) {
467
    // The native darwin assembler doesn't support the linker_option directives,
468
    // so we disable them if we think the .s file will be passed to it.
469
15.7k
    Default = TC.useIntegratedAs();
470
15.7k
  }
471
  // The linker_option directives are intended for host compilation.
472
42.1k
  if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
473
41.8k
      JA.isDeviceOffloading(Action::OFK_HIP))
474
528
    Default = false;
475
42.1k
  return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
476
42.1k
                      Default);
477
42.1k
}
478
479
static bool ShouldDisableDwarfDirectory(const ArgList &Args,
480
42.1k
                                        const ToolChain &TC) {
481
42.1k
  bool UseDwarfDirectory =
482
42.1k
      Args.hasFlag(options::OPT_fdwarf_directory_asm,
483
42.1k
                   options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
484
42.1k
  return !UseDwarfDirectory;
485
42.1k
}
486
487
// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
488
// to the corresponding DebugInfoKind.
489
913
static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
490
913
  assert(A.getOption().matches(options::OPT_gN_Group) &&
491
913
         "Not a -g option that specifies a debug-info level");
492
913
  if (A.getOption().matches(options::OPT_g0) ||
493
884
      A.getOption().matches(options::OPT_ggdb0))
494
37
    return codegenoptions::NoDebugInfo;
495
876
  if (A.getOption().matches(options::OPT_gline_tables_only) ||
496
855
      A.getOption().matches(options::OPT_ggdb1))
497
30
    return codegenoptions::DebugLineTablesOnly;
498
846
  if (A.getOption().matches(options::OPT_gline_directives_only))
499
11
    return codegenoptions::DebugDirectivesOnly;
500
835
  return codegenoptions::LimitedDebugInfo;
501
846
}
502
503
42.1k
static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
504
42.1k
  switch (Triple.getArch()){
505
40.4k
  default:
506
40.4k
    return false;
507
1.59k
  case llvm::Triple::arm:
508
1.63k
  case llvm::Triple::thumb:
509
    // ARM Darwin targets require a frame pointer to be always present to aid
510
    // offline debugging via backtraces.
511
1.63k
    return Triple.isOSDarwin();
512
42.1k
  }
513
42.1k
}
514
515
static bool useFramePointerForTargetByDefault(const ArgList &Args,
516
41.9k
                                              const llvm::Triple &Triple) {
517
41.9k
  if (Args.hasArg(options::OPT_pg) && 
!Args.hasArg(options::OPT_mfentry)48
)
518
44
    return true;
519
520
41.9k
  switch (Triple.getArch()) {
521
5
  case llvm::Triple::xcore:
522
60
  case llvm::Triple::wasm32:
523
79
  case llvm::Triple::wasm64:
524
130
  case llvm::Triple::msp430:
525
    // XCore never wants frame pointers, regardless of OS.
526
    // WebAssembly never wants frame pointers.
527
130
    return false;
528
103
  case llvm::Triple::ppc:
529
110
  case llvm::Triple::ppcle:
530
276
  case llvm::Triple::ppc64:
531
451
  case llvm::Triple::ppc64le:
532
681
  case llvm::Triple::riscv32:
533
846
  case llvm::Triple::riscv64:
534
1.31k
  case llvm::Triple::amdgcn:
535
1.36k
  case llvm::Triple::r600:
536
1.36k
    return !areOptimizationsEnabled(Args);
537
40.4k
  default:
538
40.4k
    break;
539
41.9k
  }
540
541
40.4k
  if (Triple.isOSNetBSD()) {
542
179
    return !areOptimizationsEnabled(Args);
543
179
  }
544
545
40.2k
  if (Triple.isOSLinux() || 
Triple.getOS() == llvm::Triple::CloudABI36.0k
||
546
36.0k
      Triple.isOSHurd()) {
547
4.23k
    switch (Triple.getArch()) {
548
    // Don't use a frame pointer on linux if optimizing for certain targets.
549
530
    case llvm::Triple::arm:
550
573
    case llvm::Triple::armeb:
551
586
    case llvm::Triple::thumb:
552
597
    case llvm::Triple::thumbeb:
553
597
      if (Triple.isAndroid())
554
97
        return true;
555
500
      LLVM_FALLTHROUGH;
556
596
    case llvm::Triple::mips64:
557
672
    case llvm::Triple::mips64el:
558
906
    case llvm::Triple::mips:
559
1.00k
    case llvm::Triple::mipsel:
560
1.04k
    case llvm::Triple::systemz:
561
1.51k
    case llvm::Triple::x86:
562
3.79k
    case llvm::Triple::x86_64:
563
3.79k
      return !areOptimizationsEnabled(Args);
564
343
    default:
565
343
      return true;
566
4.23k
    }
567
4.23k
  }
568
569
36.0k
  if (Triple.isOSWindows()) {
570
7.88k
    switch (Triple.getArch()) {
571
160
    case llvm::Triple::x86:
572
160
      return !areOptimizationsEnabled(Args);
573
7.67k
    case llvm::Triple::x86_64:
574
7.67k
      return Triple.isOSBinFormatMachO();
575
37
    case llvm::Triple::arm:
576
41
    case llvm::Triple::thumb:
577
      // Windows on ARM builds with FPO disabled to aid fast stack walking
578
41
      return true;
579
11
    default:
580
      // All other supported Windows ISAs use xdata unwind information, so frame
581
      // pointers are not generally useful.
582
11
      return false;
583
7.88k
    }
584
7.88k
  }
585
586
28.1k
  return true;
587
36.0k
}
588
589
static CodeGenOptions::FramePointerKind
590
42.1k
getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
591
  // We have 4 states:
592
  //
593
  //  00) leaf retained, non-leaf retained
594
  //  01) leaf retained, non-leaf omitted (this is invalid)
595
  //  10) leaf omitted, non-leaf retained
596
  //      (what -momit-leaf-frame-pointer was designed for)
597
  //  11) leaf omitted, non-leaf omitted
598
  //
599
  //  "omit" options taking precedence over "no-omit" options is the only way
600
  //  to make 3 valid states representable
601
42.1k
  Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
602
42.1k
                           options::OPT_fno_omit_frame_pointer);
603
42.1k
  bool OmitFP = A && 
A->getOption().matches(options::OPT_fomit_frame_pointer)62
;
604
42.1k
  bool NoOmitFP =
605
42.1k
      A && 
A->getOption().matches(options::OPT_fno_omit_frame_pointer)62
;
606
42.1k
  bool OmitLeafFP = Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
607
42.1k
                                 options::OPT_mno_omit_leaf_frame_pointer,
608
42.1k
                                 Triple.isAArch64() || 
Triple.isPS4CPU()40.9k
);
609
42.1k
  if (NoOmitFP || 
mustUseNonLeafFramePointerForTarget(Triple)42.1k
||
610
42.0k
      (!OmitFP && 
useFramePointerForTargetByDefault(Args, Triple)41.9k
)) {
611
34.0k
    if (OmitLeafFP)
612
1.35k
      return CodeGenOptions::FramePointerKind::NonLeaf;
613
32.7k
    return CodeGenOptions::FramePointerKind::All;
614
34.0k
  }
615
8.06k
  return CodeGenOptions::FramePointerKind::None;
616
42.1k
}
617
618
/// Add a CC1 option to specify the debug compilation directory.
619
static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
620
42.4k
                               const llvm::vfs::FileSystem &VFS) {
621
42.4k
  if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
622
7
                               options::OPT_fdebug_compilation_dir_EQ)) {
623
7
    if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
624
3
      CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
625
3
                                           A->getValue()));
626
4
    else
627
4
      A->render(Args, CmdArgs);
628
42.4k
  } else if (llvm::ErrorOr<std::string> CWD =
629
42.4k
                 VFS.getCurrentWorkingDirectory()) {
630
42.4k
    CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
631
42.4k
  }
632
42.4k
}
633
634
/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
635
42.4k
static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
636
42.4k
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
637
22
                                    options::OPT_fdebug_prefix_map_EQ)) {
638
22
    StringRef Map = A->getValue();
639
22
    if (Map.find('=') == StringRef::npos)
640
2
      D.Diag(diag::err_drv_invalid_argument_to_option)
641
2
          << Map << A->getOption().getName();
642
20
    else
643
20
      CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
644
22
    A->claim();
645
22
  }
646
42.4k
}
647
648
/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
649
static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
650
41.7k
                                 ArgStringList &CmdArgs) {
651
41.7k
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
652
20
                                    options::OPT_fmacro_prefix_map_EQ)) {
653
20
    StringRef Map = A->getValue();
654
20
    if (Map.find('=') == StringRef::npos)
655
2
      D.Diag(diag::err_drv_invalid_argument_to_option)
656
2
          << Map << A->getOption().getName();
657
18
    else
658
18
      CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
659
20
    A->claim();
660
20
  }
661
41.7k
}
662
663
/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
664
static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
665
41.7k
                                   ArgStringList &CmdArgs) {
666
41.7k
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
667
17
                                    options::OPT_fcoverage_prefix_map_EQ)) {
668
17
    StringRef Map = A->getValue();
669
17
    if (Map.find('=') == StringRef::npos)
670
2
      D.Diag(diag::err_drv_invalid_argument_to_option)
671
2
          << Map << A->getOption().getName();
672
15
    else
673
15
      CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
674
17
    A->claim();
675
17
  }
676
41.7k
}
677
678
/// Vectorize at all optimization levels greater than 1 except for -Oz.
679
/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
680
/// enabled.
681
84.2k
static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
682
84.2k
  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
683
7.56k
    if (A->getOption().matches(options::OPT_O4) ||
684
7.55k
        A->getOption().matches(options::OPT_Ofast))
685
64
      return true;
686
687
7.50k
    if (A->getOption().matches(options::OPT_O0))
688
6.25k
      return false;
689
690
1.24k
    assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
691
692
    // Vectorize -Os.
693
0
    StringRef S(A->getValue());
694
1.24k
    if (S == "s")
695
66
      return true;
696
697
    // Don't vectorize -Oz, unless it's the slp vectorizer.
698
1.17k
    if (S == "z")
699
20
      return isSlpVec;
700
701
1.15k
    unsigned OptLevel = 0;
702
1.15k
    if (S.getAsInteger(10, OptLevel))
703
12
      return false;
704
705
1.14k
    return OptLevel > 1;
706
1.15k
  }
707
708
76.7k
  return false;
709
84.2k
}
710
711
/// Add -x lang to \p CmdArgs for \p Input.
712
static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
713
42.1k
                             ArgStringList &CmdArgs) {
714
  // When using -verify-pch, we don't want to provide the type
715
  // 'precompiled-header' if it was inferred from the file extension
716
42.1k
  if (Args.hasArg(options::OPT_verify_pch) && 
Input.getType() == types::TY_PCH2
)
717
1
    return;
718
719
42.1k
  CmdArgs.push_back("-x");
720
42.1k
  if (Args.hasArg(options::OPT_rewrite_objc))
721
10
    CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
722
42.1k
  else {
723
    // Map the driver type to the frontend type. This is mostly an identity
724
    // mapping, except that the distinction between module interface units
725
    // and other source files does not exist at the frontend layer.
726
42.1k
    const char *ClangType;
727
42.1k
    switch (Input.getType()) {
728
6
    case types::TY_CXXModule:
729
6
      ClangType = "c++";
730
6
      break;
731
0
    case types::TY_PP_CXXModule:
732
0
      ClangType = "c++-cpp-output";
733
0
      break;
734
42.1k
    default:
735
42.1k
      ClangType = types::getTypeName(Input.getType());
736
42.1k
      break;
737
42.1k
    }
738
42.1k
    CmdArgs.push_back(ClangType);
739
42.1k
  }
740
42.1k
}
741
742
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
743
                                   const Driver &D, const InputInfo &Output,
744
                                   const ArgList &Args,
745
41.3k
                                   ArgStringList &CmdArgs) {
746
747
41.3k
  auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
748
41.3k
                                         options::OPT_fprofile_generate_EQ,
749
41.3k
                                         options::OPT_fno_profile_generate);
750
41.3k
  if (PGOGenerateArg &&
751
26
      PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
752
4
    PGOGenerateArg = nullptr;
753
754
41.3k
  auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
755
41.3k
                                           options::OPT_fcs_profile_generate_EQ,
756
41.3k
                                           options::OPT_fno_profile_generate);
757
41.3k
  if (CSPGOGenerateArg &&
758
9
      CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
759
4
    CSPGOGenerateArg = nullptr;
760
761
41.3k
  auto *ProfileGenerateArg = Args.getLastArg(
762
41.3k
      options::OPT_fprofile_instr_generate,
763
41.3k
      options::OPT_fprofile_instr_generate_EQ,
764
41.3k
      options::OPT_fno_profile_instr_generate);
765
41.3k
  if (ProfileGenerateArg &&
766
45
      ProfileGenerateArg->getOption().matches(
767
45
          options::OPT_fno_profile_instr_generate))
768
4
    ProfileGenerateArg = nullptr;
769
770
41.3k
  if (PGOGenerateArg && 
ProfileGenerateArg22
)
771
2
    D.Diag(diag::err_drv_argument_not_allowed_with)
772
2
        << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
773
774
41.3k
  auto *ProfileUseArg = getLastProfileUseArg(Args);
775
776
41.3k
  if (PGOGenerateArg && 
ProfileUseArg22
)
777
8
    D.Diag(diag::err_drv_argument_not_allowed_with)
778
8
        << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
779
780
41.3k
  if (ProfileGenerateArg && 
ProfileUseArg41
)
781
10
    D.Diag(diag::err_drv_argument_not_allowed_with)
782
10
        << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
783
784
41.3k
  if (CSPGOGenerateArg && 
PGOGenerateArg5
) {
785
1
    D.Diag(diag::err_drv_argument_not_allowed_with)
786
1
        << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
787
1
    PGOGenerateArg = nullptr;
788
1
  }
789
790
41.3k
  if (ProfileGenerateArg) {
791
41
    if (ProfileGenerateArg->getOption().matches(
792
41
            options::OPT_fprofile_instr_generate_EQ))
793
7
      CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
794
7
                                           ProfileGenerateArg->getValue()));
795
    // The default is to use Clang Instrumentation.
796
41
    CmdArgs.push_back("-fprofile-instrument=clang");
797
41
    if (TC.getTriple().isWindowsMSVCEnvironment()) {
798
      // Add dependent lib for clang_rt.profile
799
7
      CmdArgs.push_back(Args.MakeArgString(
800
7
          "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
801
7
    }
802
41
  }
803
804
41.3k
  Arg *PGOGenArg = nullptr;
805
41.3k
  if (PGOGenerateArg) {
806
21
    assert(!CSPGOGenerateArg);
807
0
    PGOGenArg = PGOGenerateArg;
808
21
    CmdArgs.push_back("-fprofile-instrument=llvm");
809
21
  }
810
41.3k
  if (CSPGOGenerateArg) {
811
5
    assert(!PGOGenerateArg);
812
0
    PGOGenArg = CSPGOGenerateArg;
813
5
    CmdArgs.push_back("-fprofile-instrument=csllvm");
814
5
  }
815
41.3k
  if (PGOGenArg) {
816
26
    if (TC.getTriple().isWindowsMSVCEnvironment()) {
817
      // Add dependent lib for clang_rt.profile
818
1
      CmdArgs.push_back(Args.MakeArgString(
819
1
          "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
820
1
    }
821
26
    if (PGOGenArg->getOption().matches(
822
26
            PGOGenerateArg ? 
options::OPT_fprofile_generate_EQ21
823
9
                           : 
options::OPT_fcs_profile_generate_EQ5
)) {
824
9
      SmallString<128> Path(PGOGenArg->getValue());
825
9
      llvm::sys::path::append(Path, "default_%m.profraw");
826
9
      CmdArgs.push_back(
827
9
          Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
828
9
    }
829
26
  }
830
831
41.3k
  if (ProfileUseArg) {
832
41
    if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
833
9
      CmdArgs.push_back(Args.MakeArgString(
834
9
          Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
835
32
    else if ((ProfileUseArg->getOption().matches(
836
32
                  options::OPT_fprofile_use_EQ) ||
837
12
              ProfileUseArg->getOption().matches(
838
32
                  options::OPT_fprofile_instr_use))) {
839
32
      SmallString<128> Path(
840
32
          ProfileUseArg->getNumValues() == 0 ? 
""12
:
ProfileUseArg->getValue()20
);
841
32
      if (Path.empty() || 
llvm::sys::fs::is_directory(Path)20
)
842
17
        llvm::sys::path::append(Path, "default.profdata");
843
32
      CmdArgs.push_back(
844
32
          Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
845
32
    }
846
41
  }
847
848
41.3k
  bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
849
41.3k
                                   options::OPT_fno_test_coverage, false) ||
850
41.3k
                      Args.hasArg(options::OPT_coverage);
851
41.3k
  bool EmitCovData = TC.needsGCovInstrumentation(Args);
852
41.3k
  if (EmitCovNotes)
853
20
    CmdArgs.push_back("-ftest-coverage");
854
41.3k
  if (EmitCovData)
855
25
    CmdArgs.push_back("-fprofile-arcs");
856
857
41.3k
  if (Args.hasFlag(options::OPT_fcoverage_mapping,
858
3
                   options::OPT_fno_coverage_mapping, false)) {
859
3
    if (!ProfileGenerateArg)
860
1
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
861
1
          << "-fcoverage-mapping"
862
1
          << "-fprofile-instr-generate";
863
864
3
    CmdArgs.push_back("-fcoverage-mapping");
865
3
  }
866
867
41.3k
  if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
868
3
                               options::OPT_fcoverage_compilation_dir_EQ)) {
869
3
    if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
870
2
      CmdArgs.push_back(Args.MakeArgString(
871
2
          Twine("-fcoverage-compilation-dir=") + A->getValue()));
872
1
    else
873
1
      A->render(Args, CmdArgs);
874
41.3k
  } else if (llvm::ErrorOr<std::string> CWD =
875
41.3k
                 D.getVFS().getCurrentWorkingDirectory()) {
876
41.3k
    CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
877
41.3k
  }
878
879
41.3k
  if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
880
5
    auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
881
5
    if (!Args.hasArg(options::OPT_coverage))
882
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
883
0
          << "-fprofile-exclude-files="
884
0
          << "--coverage";
885
886
5
    StringRef v = Arg->getValue();
887
5
    CmdArgs.push_back(
888
5
        Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
889
5
  }
890
891
41.3k
  if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
892
4
    auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
893
4
    if (!Args.hasArg(options::OPT_coverage))
894
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
895
0
          << "-fprofile-filter-files="
896
0
          << "--coverage";
897
898
4
    StringRef v = Arg->getValue();
899
4
    CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
900
4
  }
901
902
41.3k
  if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
903
4
    StringRef Val = A->getValue();
904
4
    if (Val == "atomic" || 
Val == "prefer-atomic"3
)
905
2
      CmdArgs.push_back("-fprofile-update=atomic");
906
2
    else if (Val != "single")
907
1
      D.Diag(diag::err_drv_unsupported_option_argument)
908
1
          << A->getOption().getName() << Val;
909
41.3k
  } else if (TC.getSanitizerArgs().needsTsanRt()) {
910
70
    CmdArgs.push_back("-fprofile-update=atomic");
911
70
  }
912
913
  // Leave -fprofile-dir= an unused argument unless .gcda emission is
914
  // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
915
  // the flag used. There is no -fno-profile-dir, so the user has no
916
  // targeted way to suppress the warning.
917
41.3k
  Arg *FProfileDir = nullptr;
918
41.3k
  if (Args.hasArg(options::OPT_fprofile_arcs) ||
919
41.3k
      Args.hasArg(options::OPT_coverage))
920
27
    FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
921
922
  // Put the .gcno and .gcda files (if needed) next to the object file or
923
  // bitcode file in the case of LTO.
924
  // FIXME: There should be a simpler way to find the object file for this
925
  // input, and this code probably does the wrong thing for commands that
926
  // compile and link all at once.
927
41.3k
  if ((Args.hasArg(options::OPT_c) || 
Args.hasArg(options::OPT_S)34.4k
) &&
928
8.16k
      (EmitCovNotes || 
EmitCovData8.14k
) &&
Output.isFilename()17
) {
929
17
    SmallString<128> OutputFilename;
930
17
    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT__SLASH_Fo))
931
1
      OutputFilename = FinalOutput->getValue();
932
16
    else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
933
10
      OutputFilename = FinalOutput->getValue();
934
6
    else
935
6
      OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
936
17
    SmallString<128> CoverageFilename = OutputFilename;
937
17
    if (llvm::sys::path::is_relative(CoverageFilename))
938
7
      (void)D.getVFS().makeAbsolute(CoverageFilename);
939
17
    llvm::sys::path::replace_extension(CoverageFilename, "gcno");
940
941
17
    CmdArgs.push_back("-coverage-notes-file");
942
17
    CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
943
944
17
    if (EmitCovData) {
945
15
      if (FProfileDir) {
946
2
        CoverageFilename = FProfileDir->getValue();
947
2
        llvm::sys::path::append(CoverageFilename, OutputFilename);
948
2
      }
949
15
      llvm::sys::path::replace_extension(CoverageFilename, "gcda");
950
15
      CmdArgs.push_back("-coverage-data-file");
951
15
      CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
952
15
    }
953
17
  }
954
41.3k
}
955
956
/// Check whether the given input tree contains any compilation actions.
957
28.6k
static bool ContainsCompileAction(const Action *A) {
958
28.6k
  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
959
9.80k
    return true;
960
961
18.8k
  for (const auto &AI : A->inputs())
962
18.4k
    if (ContainsCompileAction(AI))
963
17.8k
      return true;
964
965
919
  return false;
966
18.8k
}
967
968
/// Check if -relax-all should be passed to the internal assembler.
969
/// This is done by default when compiling non-assembler source with -O0.
970
10.3k
static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
971
10.3k
  bool RelaxDefault = true;
972
973
10.3k
  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
974
3.31k
    RelaxDefault = A->getOption().matches(options::OPT_O0);
975
976
10.3k
  if (RelaxDefault) {
977
10.1k
    RelaxDefault = false;
978
10.1k
    for (const auto &Act : C.getActions()) {
979
10.1k
      if (ContainsCompileAction(Act)) {
980
9.80k
        RelaxDefault = true;
981
9.80k
        break;
982
9.80k
      }
983
10.1k
    }
984
10.1k
  }
985
986
10.3k
  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
987
10.3k
                      RelaxDefault);
988
10.3k
}
989
990
// Extract the integer N from a string spelled "-dwarf-N", returning 0
991
// on mismatch. The StringRef input (rather than an Arg) allows
992
// for use by the "-Xassembler" option parser.
993
65
static unsigned DwarfVersionNum(StringRef ArgValue) {
994
65
  return llvm::StringSwitch<unsigned>(ArgValue)
995
65
      .Case("-gdwarf-2", 2)
996
65
      .Case("-gdwarf-3", 3)
997
65
      .Case("-gdwarf-4", 4)
998
65
      .Case("-gdwarf-5", 5)
999
65
      .Default(0);
1000
65
}
1001
1002
// Find a DWARF format version option.
1003
// This function is a complementary for DwarfVersionNum().
1004
42.5k
static const Arg *getDwarfNArg(const ArgList &Args) {
1005
42.5k
  return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
1006
42.5k
                         options::OPT_gdwarf_4, options::OPT_gdwarf_5,
1007
42.5k
                         options::OPT_gdwarf);
1008
42.5k
}
1009
1010
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
1011
                                    codegenoptions::DebugInfoKind DebugInfoKind,
1012
                                    unsigned DwarfVersion,
1013
42.5k
                                    llvm::DebuggerKind DebuggerTuning) {
1014
42.5k
  switch (DebugInfoKind) {
1015
19
  case codegenoptions::DebugDirectivesOnly:
1016
19
    CmdArgs.push_back("-debug-info-kind=line-directives-only");
1017
19
    break;
1018
65
  case codegenoptions::DebugLineTablesOnly:
1019
65
    CmdArgs.push_back("-debug-info-kind=line-tables-only");
1020
65
    break;
1021
0
  case codegenoptions::DebugInfoConstructor:
1022
0
    CmdArgs.push_back("-debug-info-kind=constructor");
1023
0
    break;
1024
267
  case codegenoptions::LimitedDebugInfo:
1025
267
    CmdArgs.push_back("-debug-info-kind=limited");
1026
267
    break;
1027
3.39k
  case codegenoptions::FullDebugInfo:
1028
3.39k
    CmdArgs.push_back("-debug-info-kind=standalone");
1029
3.39k
    break;
1030
1
  case codegenoptions::UnusedTypeInfo:
1031
1
    CmdArgs.push_back("-debug-info-kind=unused-types");
1032
1
    break;
1033
38.8k
  default:
1034
38.8k
    break;
1035
42.5k
  }
1036
42.5k
  if (DwarfVersion > 0)
1037
4.10k
    CmdArgs.push_back(
1038
4.10k
        Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
1039
42.5k
  switch (DebuggerTuning) {
1040
18.5k
  case llvm::DebuggerKind::GDB:
1041
18.5k
    CmdArgs.push_back("-debugger-tuning=gdb");
1042
18.5k
    break;
1043
15.6k
  case llvm::DebuggerKind::LLDB:
1044
15.6k
    CmdArgs.push_back("-debugger-tuning=lldb");
1045
15.6k
    break;
1046
137
  case llvm::DebuggerKind::SCE:
1047
137
    CmdArgs.push_back("-debugger-tuning=sce");
1048
137
    break;
1049
8.18k
  default:
1050
8.18k
    break;
1051
42.5k
  }
1052
42.5k
}
1053
1054
static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1055
7.92k
                                 const Driver &D, const ToolChain &TC) {
1056
7.92k
  assert(A && "Expected non-nullptr argument.");
1057
7.92k
  if (TC.supportsDebugInfoOption(A))
1058
7.91k
    return true;
1059
3
  D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1060
3
      << A->getAsString(Args) << TC.getTripleString();
1061
3
  return false;
1062
7.92k
}
1063
1064
static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1065
                                           ArgStringList &CmdArgs,
1066
                                           const Driver &D,
1067
42.5k
                                           const ToolChain &TC) {
1068
42.5k
  const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
1069
42.5k
  if (!A)
1070
42.5k
    return;
1071
29
  if (checkDebugInfoOption(A, Args, D, TC)) {
1072
27
    StringRef Value = A->getValue();
1073
27
    if (Value == "none") {
1074
5
      CmdArgs.push_back("--compress-debug-sections=none");
1075
22
    } else if (Value == "zlib" || 
Value == "zlib-gnu"8
) {
1076
19
      if (llvm::zlib::isAvailable()) {
1077
19
        CmdArgs.push_back(
1078
19
            Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1079
0
      } else {
1080
0
        D.Diag(diag::warn_debug_compression_unavailable);
1081
0
      }
1082
3
    } else {
1083
3
      D.Diag(diag::err_drv_unsupported_option_argument)
1084
3
          << A->getOption().getName() << Value;
1085
3
    }
1086
27
  }
1087
29
}
1088
1089
42.5k
static const char *RelocationModelName(llvm::Reloc::Model Model) {
1090
42.5k
  switch (Model) {
1091
17.5k
  case llvm::Reloc::Static:
1092
17.5k
    return "static";
1093
25.0k
  case llvm::Reloc::PIC_:
1094
25.0k
    return "pic";
1095
8
  case llvm::Reloc::DynamicNoPIC:
1096
8
    return "dynamic-no-pic";
1097
11
  case llvm::Reloc::ROPI:
1098
11
    return "ropi";
1099
6
  case llvm::Reloc::RWPI:
1100
6
    return "rwpi";
1101
6
  case llvm::Reloc::ROPI_RWPI:
1102
6
    return "ropi-rwpi";
1103
42.5k
  }
1104
42.5k
  
llvm_unreachable0
("Unknown Reloc::Model kind");
1105
42.5k
}
1106
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
1107
                                                 const ArgList &Args,
1108
544
                                                 ArgStringList &CmdArgs) {
1109
544
  unsigned CodeObjVer = getOrCheckAMDGPUCodeObjectVersion(D, Args);
1110
544
  CmdArgs.insert(CmdArgs.begin() + 1,
1111
544
                 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
1112
544
                                    Twine(CodeObjVer)));
1113
544
  CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
1114
544
}
1115
1116
void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1117
                                    const Driver &D, const ArgList &Args,
1118
                                    ArgStringList &CmdArgs,
1119
                                    const InputInfo &Output,
1120
41.7k
                                    const InputInfoList &Inputs) const {
1121
41.7k
  const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1122
1123
41.7k
  CheckPreprocessingOptions(D, Args);
1124
1125
41.7k
  Args.AddLastArg(CmdArgs, options::OPT_C);
1126
41.7k
  Args.AddLastArg(CmdArgs, options::OPT_CC);
1127
1128
  // Handle dependency file generation.
1129
41.7k
  Arg *ArgM = Args.getLastArg(options::OPT_MM);
1130
41.7k
  if (!ArgM)
1131
41.7k
    ArgM = Args.getLastArg(options::OPT_M);
1132
41.7k
  Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1133
41.7k
  if (!ArgMD)
1134
41.7k
    ArgMD = Args.getLastArg(options::OPT_MD);
1135
1136
  // -M and -MM imply -w.
1137
41.7k
  if (ArgM)
1138
85
    CmdArgs.push_back("-w");
1139
41.6k
  else
1140
41.6k
    ArgM = ArgMD;
1141
1142
41.7k
  if (ArgM) {
1143
    // Determine the output location.
1144
3.15k
    const char *DepFile;
1145
3.15k
    if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1146
3.08k
      DepFile = MF->getValue();
1147
3.08k
      C.addFailureResultFile(DepFile, &JA);
1148
77
    } else if (Output.getType() == types::TY_Dependencies) {
1149
72
      DepFile = Output.getFilename();
1150
5
    } else if (!ArgMD) {
1151
0
      DepFile = "-";
1152
5
    } else {
1153
5
      DepFile = getDependencyFileName(Args, Inputs);
1154
5
      C.addFailureResultFile(DepFile, &JA);
1155
5
    }
1156
3.15k
    CmdArgs.push_back("-dependency-file");
1157
3.15k
    CmdArgs.push_back(DepFile);
1158
1159
3.15k
    bool HasTarget = false;
1160
3.12k
    for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1161
3.12k
      HasTarget = true;
1162
3.12k
      A->claim();
1163
3.12k
      if (A->getOption().matches(options::OPT_MT)) {
1164
3.12k
        A->render(Args, CmdArgs);
1165
5
      } else {
1166
5
        CmdArgs.push_back("-MT");
1167
5
        SmallString<128> Quoted;
1168
5
        QuoteTarget(A->getValue(), Quoted);
1169
5
        CmdArgs.push_back(Args.MakeArgString(Quoted));
1170
5
      }
1171
3.12k
    }
1172
1173
    // Add a default target if one wasn't specified.
1174
3.15k
    if (!HasTarget) {
1175
37
      const char *DepTarget;
1176
1177
      // If user provided -o, that is the dependency target, except
1178
      // when we are only generating a dependency file.
1179
37
      Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1180
37
      if (OutputOpt && 
Output.getType() != types::TY_Dependencies8
) {
1181
6
        DepTarget = OutputOpt->getValue();
1182
31
      } else {
1183
        // Otherwise derive from the base input.
1184
        //
1185
        // FIXME: This should use the computed output file location.
1186
31
        SmallString<128> P(Inputs[0].getBaseInput());
1187
31
        llvm::sys::path::replace_extension(P, "o");
1188
31
        DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1189
31
      }
1190
1191
37
      CmdArgs.push_back("-MT");
1192
37
      SmallString<128> Quoted;
1193
37
      QuoteTarget(DepTarget, Quoted);
1194
37
      CmdArgs.push_back(Args.MakeArgString(Quoted));
1195
37
    }
1196
1197
3.15k
    if (ArgM->getOption().matches(options::OPT_M) ||
1198
3.07k
        ArgM->getOption().matches(options::OPT_MD))
1199
3.14k
      CmdArgs.push_back("-sys-header-deps");
1200
3.15k
    if ((isa<PrecompileJobAction>(JA) &&
1201
2
         !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1202
3.15k
        Args.hasArg(options::OPT_fmodule_file_deps))
1203
2
      CmdArgs.push_back("-module-file-deps");
1204
3.15k
  }
1205
1206
41.7k
  if (Args.hasArg(options::OPT_MG)) {
1207
4
    if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1208
4
        ArgM->getOption().matches(options::OPT_MMD))
1209
0
      D.Diag(diag::err_drv_mg_requires_m_or_mm);
1210
4
    CmdArgs.push_back("-MG");
1211
4
  }
1212
1213
41.7k
  Args.AddLastArg(CmdArgs, options::OPT_MP);
1214
41.7k
  Args.AddLastArg(CmdArgs, options::OPT_MV);
1215
1216
  // Add offload include arguments specific for CUDA/HIP.  This must happen
1217
  // before we -I or -include anything else, because we must pick up the
1218
  // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1219
  // from e.g. /usr/local/include.
1220
41.7k
  if (JA.isOffloading(Action::OFK_Cuda))
1221
483
    getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1222
41.7k
  if (JA.isOffloading(Action::OFK_HIP))
1223
372
    getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1224
1225
  // If we are offloading to a target via OpenMP we need to include the
1226
  // openmp_wrappers folder which contains alternative system headers.
1227
41.7k
  if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1228
71
      getToolChain().getTriple().isNVPTX()){
1229
42
    if (!Args.hasArg(options::OPT_nobuiltininc)) {
1230
      // Add openmp_wrappers/* to our system include path.  This lets us wrap
1231
      // standard library headers.
1232
42
      SmallString<128> P(D.ResourceDir);
1233
42
      llvm::sys::path::append(P, "include");
1234
42
      llvm::sys::path::append(P, "openmp_wrappers");
1235
42
      CmdArgs.push_back("-internal-isystem");
1236
42
      CmdArgs.push_back(Args.MakeArgString(P));
1237
42
    }
1238
1239
42
    CmdArgs.push_back("-include");
1240
42
    CmdArgs.push_back("__clang_openmp_device_functions.h");
1241
42
  }
1242
1243
  // Add -i* options, and automatically translate to
1244
  // -include-pch/-include-pth for transparent PCH support. It's
1245
  // wonky, but we include looking for .gch so we can support seamless
1246
  // replacement into a build system already set up to be generating
1247
  // .gch files.
1248
1249
41.7k
  if (getToolChain().getDriver().IsCLMode()) {
1250
532
    const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1251
532
    const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1252
532
    if (YcArg && 
JA.getKind() >= Action::PrecompileJobClass36
&&
1253
36
        JA.getKind() <= Action::AssembleJobClass) {
1254
36
      CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1255
      // -fpch-instantiate-templates is the default when creating
1256
      // precomp using /Yc
1257
36
      if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1258
36
                       options::OPT_fno_pch_instantiate_templates, true))
1259
34
        CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1260
36
    }
1261
532
    if (YcArg || 
YuArg496
) {
1262
49
      StringRef ThroughHeader = YcArg ? 
YcArg->getValue()36
:
YuArg->getValue()13
;
1263
49
      if (!isa<PrecompileJobAction>(JA)) {
1264
31
        CmdArgs.push_back("-include-pch");
1265
31
        CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1266
31
            C, !ThroughHeader.empty()
1267
26
                   ? ThroughHeader
1268
5
                   : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1269
31
      }
1270
1271
49
      if (ThroughHeader.empty()) {
1272
9
        CmdArgs.push_back(Args.MakeArgString(
1273
9
            Twine("-pch-through-hdrstop-") + (YcArg ? 
"create"8
:
"use"1
)));
1274
40
      } else {
1275
40
        CmdArgs.push_back(
1276
40
            Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1277
40
      }
1278
49
    }
1279
532
  }
1280
1281
41.7k
  bool RenderedImplicitInclude = false;
1282
9.86k
  for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1283
9.86k
    if (A->getOption().matches(options::OPT_include)) {
1284
      // Handling of gcc-style gch precompiled headers.
1285
3.18k
      bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1286
3.18k
      RenderedImplicitInclude = true;
1287
1288
3.18k
      bool FoundPCH = false;
1289
3.18k
      SmallString<128> P(A->getValue());
1290
      // We want the files to have a name like foo.h.pch. Add a dummy extension
1291
      // so that replace_extension does the right thing.
1292
3.18k
      P += ".dummy";
1293
3.18k
      llvm::sys::path::replace_extension(P, "pch");
1294
3.18k
      if (llvm::sys::fs::exists(P))
1295
69
        FoundPCH = true;
1296
1297
3.18k
      if (!FoundPCH) {
1298
3.11k
        llvm::sys::path::replace_extension(P, "gch");
1299
3.11k
        if (llvm::sys::fs::exists(P)) {
1300
8
          FoundPCH = true;
1301
8
        }
1302
3.11k
      }
1303
1304
3.18k
      if (FoundPCH) {
1305
77
        if (IsFirstImplicitInclude) {
1306
77
          A->claim();
1307
77
          CmdArgs.push_back("-include-pch");
1308
77
          CmdArgs.push_back(Args.MakeArgString(P));
1309
77
          continue;
1310
0
        } else {
1311
          // Ignore the PCH if not first on command line and emit warning.
1312
0
          D.Diag(diag::warn_drv_pch_not_first_include) << P
1313
0
                                                       << A->getAsString(Args);
1314
0
        }
1315
77
      }
1316
6.67k
    } else if (A->getOption().matches(options::OPT_isystem_after)) {
1317
      // Handling of paths which must come late.  These entries are handled by
1318
      // the toolchain itself after the resource dir is inserted in the right
1319
      // search order.
1320
      // Do not claim the argument so that the use of the argument does not
1321
      // silently go unnoticed on toolchains which do not honour the option.
1322
4
      continue;
1323
6.67k
    } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1324
      // Translated to -internal-isystem by the driver, no need to pass to cc1.
1325
14
      continue;
1326
14
    }
1327
1328
    // Not translated, render as usual.
1329
9.77k
    A->claim();
1330
9.77k
    A->render(Args, CmdArgs);
1331
9.77k
  }
1332
1333
41.7k
  Args.AddAllArgs(CmdArgs,
1334
41.7k
                  {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1335
41.7k
                   options::OPT_F, options::OPT_index_header_map});
1336
1337
  // Add -Wp, and -Xpreprocessor if using the preprocessor.
1338
1339
  // FIXME: There is a very unfortunate problem here, some troubled
1340
  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1341
  // really support that we would have to parse and then translate
1342
  // those options. :(
1343
41.7k
  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1344
41.7k
                       options::OPT_Xpreprocessor);
1345
1346
  // -I- is a deprecated GCC feature, reject it.
1347
41.7k
  if (Arg *A = Args.getLastArg(options::OPT_I_))
1348
0
    D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1349
1350
  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1351
  // -isysroot to the CC1 invocation.
1352
41.7k
  StringRef sysroot = C.getSysRoot();
1353
41.7k
  if (sysroot != "") {
1354
775
    if (!Args.hasArg(options::OPT_isysroot)) {
1355
770
      CmdArgs.push_back("-isysroot");
1356
770
      CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1357
770
    }
1358
775
  }
1359
1360
  // Parse additional include paths from environment variables.
1361
  // FIXME: We should probably sink the logic for handling these from the
1362
  // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1363
  // CPATH - included following the user specified includes (but prior to
1364
  // builtin and standard includes).
1365
41.7k
  addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1366
  // C_INCLUDE_PATH - system includes enabled when compiling C.
1367
41.7k
  addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1368
  // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1369
41.7k
  addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1370
  // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1371
41.7k
  addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1372
  // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1373
41.7k
  addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1374
1375
  // While adding the include arguments, we also attempt to retrieve the
1376
  // arguments of related offloading toolchains or arguments that are specific
1377
  // of an offloading programming model.
1378
1379
  // Add C++ include arguments, if needed.
1380
41.7k
  if (types::isCXX(Inputs[0].getType())) {
1381
28.1k
    bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1382
28.1k
    forAllAssociatedToolChains(
1383
28.1k
        C, JA, getToolChain(),
1384
28.9k
        [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1385
28.9k
          HasStdlibxxIsystem ? 
TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)8
1386
28.9k
                             : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1387
28.9k
        });
1388
28.1k
  }
1389
1390
  // Add system include arguments for all targets but IAMCU.
1391
41.7k
  if (!IsIAMCU)
1392
41.7k
    forAllAssociatedToolChains(C, JA, getToolChain(),
1393
42.7k
                               [&Args, &CmdArgs](const ToolChain &TC) {
1394
42.7k
                                 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1395
42.7k
                               });
1396
5
  else {
1397
    // For IAMCU add special include arguments.
1398
5
    getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1399
5
  }
1400
1401
41.7k
  addMacroPrefixMapArg(D, Args, CmdArgs);
1402
41.7k
  addCoveragePrefixMapArg(D, Args, CmdArgs);
1403
41.7k
}
1404
1405
// FIXME: Move to target hook.
1406
42.1k
static bool isSignedCharDefault(const llvm::Triple &Triple) {
1407
42.1k
  switch (Triple.getArch()) {
1408
38.0k
  default:
1409
38.0k
    return true;
1410
1411
1.03k
  case llvm::Triple::aarch64:
1412
1.04k
  case llvm::Triple::aarch64_32:
1413
1.22k
  case llvm::Triple::aarch64_be:
1414
2.82k
  case llvm::Triple::arm:
1415
2.95k
  case llvm::Triple::armeb:
1416
2.99k
  case llvm::Triple::thumb:
1417
3.00k
  case llvm::Triple::thumbeb:
1418
3.00k
    if (Triple.isOSDarwin() || 
Triple.isOSWindows()2.80k
)
1419
272
      return true;
1420
2.73k
    return false;
1421
1422
103
  case llvm::Triple::ppc:
1423
271
  case llvm::Triple::ppc64:
1424
271
    if (Triple.isOSDarwin())
1425
0
      return true;
1426
271
    return false;
1427
1428
96
  case llvm::Triple::hexagon:
1429
103
  case llvm::Triple::ppcle:
1430
296
  case llvm::Triple::ppc64le:
1431
526
  case llvm::Triple::riscv32:
1432
691
  case llvm::Triple::riscv64:
1433
754
  case llvm::Triple::systemz:
1434
759
  case llvm::Triple::xcore:
1435
759
    return false;
1436
42.1k
  }
1437
42.1k
}
1438
1439
static bool hasMultipleInvocations(const llvm::Triple &Triple,
1440
38
                                   const ArgList &Args) {
1441
  // Supported only on Darwin where we invoke the compiler multiple times
1442
  // followed by an invocation to lipo.
1443
38
  if (!Triple.isOSDarwin())
1444
7
    return false;
1445
  // If more than one "-arch <arch>" is specified, we're targeting multiple
1446
  // architectures resulting in a fat binary.
1447
31
  return Args.getAllArgValues(options::OPT_arch).size() > 1;
1448
38
}
1449
1450
static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1451
38
                                const llvm::Triple &Triple) {
1452
  // When enabling remarks, we need to error if:
1453
  // * The remark file is specified but we're targeting multiple architectures,
1454
  // which means more than one remark file is being generated.
1455
38
  bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1456
38
  bool hasExplicitOutputFile =
1457
38
      Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1458
38
  if (hasMultipleInvocations && 
hasExplicitOutputFile4
) {
1459
2
    D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1460
2
        << "-foptimization-record-file";
1461
2
    return false;
1462
2
  }
1463
36
  return true;
1464
38
}
1465
1466
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1467
                                 const llvm::Triple &Triple,
1468
                                 const InputInfo &Input,
1469
36
                                 const InputInfo &Output, const JobAction &JA) {
1470
36
  StringRef Format = "yaml";
1471
36
  if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1472
4
    Format = A->getValue();
1473
1474
36
  CmdArgs.push_back("-opt-record-file");
1475
1476
36
  const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1477
36
  if (A) {
1478
3
    CmdArgs.push_back(A->getValue());
1479
33
  } else {
1480
33
    bool hasMultipleArchs =
1481
33
        Triple.isOSDarwin() && // Only supported on Darwin platforms.
1482
27
        Args.getAllArgValues(options::OPT_arch).size() > 1;
1483
1484
33
    SmallString<128> F;
1485
1486
33
    if (Args.hasArg(options::OPT_c) || 
Args.hasArg(options::OPT_S)19
) {
1487
24
      if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1488
16
        F = FinalOutput->getValue();
1489
9
    } else {
1490
9
      if (Format != "yaml" && // For YAML, keep the original behavior.
1491
1
          Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1492
1
          Output.isFilename())
1493
1
        F = Output.getFilename();
1494
9
    }
1495
1496
33
    if (F.empty()) {
1497
      // Use the input filename.
1498
16
      F = llvm::sys::path::stem(Input.getBaseInput());
1499
1500
      // If we're compiling for an offload architecture (i.e. a CUDA device),
1501
      // we need to make the file name for the device compilation different
1502
      // from the host compilation.
1503
16
      if (!JA.isDeviceOffloading(Action::OFK_None) &&
1504
2
          !JA.isDeviceOffloading(Action::OFK_Host)) {
1505
2
        llvm::sys::path::replace_extension(F, "");
1506
2
        F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1507
2
                                                 Triple.normalize());
1508
2
        F += "-";
1509
2
        F += JA.getOffloadingArch();
1510
2
      }
1511
16
    }
1512
1513
    // If we're having more than one "-arch", we should name the files
1514
    // differently so that every cc1 invocation writes to a different file.
1515
    // We're doing that by appending "-<arch>" with "<arch>" being the arch
1516
    // name from the triple.
1517
33
    if (hasMultipleArchs) {
1518
      // First, remember the extension.
1519
2
      SmallString<64> OldExtension = llvm::sys::path::extension(F);
1520
      // then, remove it.
1521
2
      llvm::sys::path::replace_extension(F, "");
1522
      // attach -<arch> to it.
1523
2
      F += "-";
1524
2
      F += Triple.getArchName();
1525
      // put back the extension.
1526
2
      llvm::sys::path::replace_extension(F, OldExtension);
1527
2
    }
1528
1529
33
    SmallString<32> Extension;
1530
33
    Extension += "opt.";
1531
33
    Extension += Format;
1532
1533
33
    llvm::sys::path::replace_extension(F, Extension);
1534
33
    CmdArgs.push_back(Args.MakeArgString(F));
1535
33
  }
1536
1537
36
  if (const Arg *A =
1538
4
          Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1539
4
    CmdArgs.push_back("-opt-record-passes");
1540
4
    CmdArgs.push_back(A->getValue());
1541
4
  }
1542
1543
36
  if (!Format.empty()) {
1544
36
    CmdArgs.push_back("-opt-record-format");
1545
36
    CmdArgs.push_back(Format.data());
1546
36
  }
1547
36
}
1548
1549
3.00k
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1550
3.00k
  if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1551
3.00k
                    options::OPT_fno_aapcs_bitfield_width, true))
1552
2
    CmdArgs.push_back("-fno-aapcs-bitfield-width");
1553
1554
3.00k
  if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1555
2
    CmdArgs.push_back("-faapcs-bitfield-load");
1556
3.00k
}
1557
1558
namespace {
1559
void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1560
1.79k
                  ArgStringList &CmdArgs) {
1561
  // Select the ABI to use.
1562
  // FIXME: Support -meabi.
1563
  // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1564
1.79k
  const char *ABIName = nullptr;
1565
1.79k
  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1566
3
    ABIName = A->getValue();
1567
1.78k
  } else {
1568
1.78k
    std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1569
1.78k
    ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1570
1.78k
  }
1571
1572
1.79k
  CmdArgs.push_back("-target-abi");
1573
1.79k
  CmdArgs.push_back(ABIName);
1574
1.79k
}
1575
}
1576
1577
void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1578
1.78k
                             ArgStringList &CmdArgs, bool KernelOrKext) const {
1579
1.78k
  RenderARMABI(Triple, Args, CmdArgs);
1580
1581
  // Determine floating point ABI from the options & target defaults.
1582
1.78k
  arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1583
1.78k
  if (ABI == arm::FloatABI::Soft) {
1584
    // Floating point operations and argument passing are soft.
1585
    // FIXME: This changes CPP defines, we need -target-soft-float.
1586
763
    CmdArgs.push_back("-msoft-float");
1587
763
    CmdArgs.push_back("-mfloat-abi");
1588
763
    CmdArgs.push_back("soft");
1589
1.02k
  } else if (ABI == arm::FloatABI::SoftFP) {
1590
    // Floating point operations are hard, but argument passing is soft.
1591
827
    CmdArgs.push_back("-mfloat-abi");
1592
827
    CmdArgs.push_back("soft");
1593
197
  } else {
1594
    // Floating point operations and argument passing are hard.
1595
197
    assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1596
0
    CmdArgs.push_back("-mfloat-abi");
1597
197
    CmdArgs.push_back("hard");
1598
197
  }
1599
1600
  // Forward the -mglobal-merge option for explicit control over the pass.
1601
1.78k
  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1602
2
                               options::OPT_mno_global_merge)) {
1603
2
    CmdArgs.push_back("-mllvm");
1604
2
    if (A->getOption().matches(options::OPT_mno_global_merge))
1605
1
      CmdArgs.push_back("-arm-global-merge=false");
1606
1
    else
1607
1
      CmdArgs.push_back("-arm-global-merge=true");
1608
2
  }
1609
1610
1.78k
  if (!Args.hasFlag(options::OPT_mimplicit_float,
1611
1.78k
                    options::OPT_mno_implicit_float, true))
1612
1
    CmdArgs.push_back("-no-implicit-float");
1613
1614
1.78k
  if (Args.getLastArg(options::OPT_mcmse))
1615
15
    CmdArgs.push_back("-mcmse");
1616
1617
1.78k
  AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1618
1.78k
}
1619
1620
void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1621
                                const ArgList &Args, bool KernelOrKext,
1622
42.1k
                                ArgStringList &CmdArgs) const {
1623
42.1k
  const ToolChain &TC = getToolChain();
1624
1625
  // Add the target features
1626
42.1k
  getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1627
1628
  // Add target specific flags.
1629
42.1k
  switch (TC.getArch()) {
1630
1.07k
  default:
1631
1.07k
    break;
1632
1633
1.60k
  case llvm::Triple::arm:
1634
1.73k
  case llvm::Triple::armeb:
1635
1.77k
  case llvm::Triple::thumb:
1636
1.78k
  case llvm::Triple::thumbeb:
1637
    // Use the effective triple, which takes into account the deployment target.
1638
1.78k
    AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1639
1.78k
    CmdArgs.push_back("-fallow-half-arguments-and-returns");
1640
1.78k
    break;
1641
1642
1.03k
  case llvm::Triple::aarch64:
1643
1.04k
  case llvm::Triple::aarch64_32:
1644
1.22k
  case llvm::Triple::aarch64_be:
1645
1.22k
    AddAArch64TargetArgs(Args, CmdArgs);
1646
1.22k
    CmdArgs.push_back("-fallow-half-arguments-and-returns");
1647
1.22k
    break;
1648
1649
259
  case llvm::Triple::mips:
1650
371
  case llvm::Triple::mipsel:
1651
495
  case llvm::Triple::mips64:
1652
584
  case llvm::Triple::mips64el:
1653
584
    AddMIPSTargetArgs(Args, CmdArgs);
1654
584
    break;
1655
1656
103
  case llvm::Triple::ppc:
1657
110
  case llvm::Triple::ppcle:
1658
277
  case llvm::Triple::ppc64:
1659
452
  case llvm::Triple::ppc64le:
1660
452
    AddPPCTargetArgs(Args, CmdArgs);
1661
452
    break;
1662
1663
230
  case llvm::Triple::riscv32:
1664
395
  case llvm::Triple::riscv64:
1665
395
    AddRISCVTargetArgs(Args, CmdArgs);
1666
395
    break;
1667
1668
94
  case llvm::Triple::sparc:
1669
115
  case llvm::Triple::sparcel:
1670
166
  case llvm::Triple::sparcv9:
1671
166
    AddSparcTargetArgs(Args, CmdArgs);
1672
166
    break;
1673
1674
63
  case llvm::Triple::systemz:
1675
63
    AddSystemZTargetArgs(Args, CmdArgs);
1676
63
    break;
1677
1678
10.2k
  case llvm::Triple::x86:
1679
36.2k
  case llvm::Triple::x86_64:
1680
36.2k
    AddX86TargetArgs(Args, CmdArgs);
1681
36.2k
    break;
1682
1683
3
  case llvm::Triple::lanai:
1684
3
    AddLanaiTargetArgs(Args, CmdArgs);
1685
3
    break;
1686
1687
96
  case llvm::Triple::hexagon:
1688
96
    AddHexagonTargetArgs(Args, CmdArgs);
1689
96
    break;
1690
1691
55
  case llvm::Triple::wasm32:
1692
74
  case llvm::Triple::wasm64:
1693
74
    AddWebAssemblyTargetArgs(Args, CmdArgs);
1694
74
    break;
1695
1696
0
  case llvm::Triple::ve:
1697
0
    AddVETargetArgs(Args, CmdArgs);
1698
0
    break;
1699
42.1k
  }
1700
42.1k
}
1701
1702
namespace {
1703
void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1704
1.22k
                      ArgStringList &CmdArgs) {
1705
1.22k
  const char *ABIName = nullptr;
1706
1.22k
  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1707
0
    ABIName = A->getValue();
1708
1.22k
  else if (Triple.isOSDarwin())
1709
93
    ABIName = "darwinpcs";
1710
1.12k
  else
1711
1.12k
    ABIName = "aapcs";
1712
1713
1.22k
  CmdArgs.push_back("-target-abi");
1714
1.22k
  CmdArgs.push_back(ABIName);
1715
1.22k
}
1716
}
1717
1718
void Clang::AddAArch64TargetArgs(const ArgList &Args,
1719
1.22k
                                 ArgStringList &CmdArgs) const {
1720
1.22k
  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1721
1722
1.22k
  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1723
1.22k
      Args.hasArg(options::OPT_mkernel) ||
1724
1.21k
      Args.hasArg(options::OPT_fapple_kext))
1725
2
    CmdArgs.push_back("-disable-red-zone");
1726
1727
1.22k
  if (!Args.hasFlag(options::OPT_mimplicit_float,
1728
1.22k
                    options::OPT_mno_implicit_float, true))
1729
0
    CmdArgs.push_back("-no-implicit-float");
1730
1731
1.22k
  RenderAArch64ABI(Triple, Args, CmdArgs);
1732
1733
1.22k
  if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1734
6
                               options::OPT_mno_fix_cortex_a53_835769)) {
1735
6
    CmdArgs.push_back("-mllvm");
1736
6
    if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1737
3
      CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1738
3
    else
1739
3
      CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1740
1.21k
  } else if (Triple.isAndroid()) {
1741
    // Enabled A53 errata (835769) workaround by default on android
1742
52
    CmdArgs.push_back("-mllvm");
1743
52
    CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1744
52
  }
1745
1746
  // Forward the -mglobal-merge option for explicit control over the pass.
1747
1.22k
  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1748
2
                               options::OPT_mno_global_merge)) {
1749
2
    CmdArgs.push_back("-mllvm");
1750
2
    if (A->getOption().matches(options::OPT_mno_global_merge))
1751
1
      CmdArgs.push_back("-aarch64-enable-global-merge=false");
1752
1
    else
1753
1
      CmdArgs.push_back("-aarch64-enable-global-merge=true");
1754
2
  }
1755
1756
  // Enable/disable return address signing and indirect branch targets.
1757
1.22k
  if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1758
30
                               options::OPT_mbranch_protection_EQ)) {
1759
1760
30
    const Driver &D = getToolChain().getDriver();
1761
1762
30
    StringRef Scope, Key;
1763
30
    bool IndirectBranches;
1764
1765
30
    if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1766
8
      Scope = A->getValue();
1767
8
      if (!Scope.equals("none") && 
!Scope.equals("non-leaf")5
&&
1768
3
          !Scope.equals("all"))
1769
1
        D.Diag(diag::err_invalid_branch_protection)
1770
1
            << Scope << A->getAsString(Args);
1771
8
      Key = "a_key";
1772
8
      IndirectBranches = false;
1773
22
    } else {
1774
22
      StringRef Err;
1775
22
      llvm::AArch64::ParsedBranchProtection PBP;
1776
22
      if (!llvm::AArch64::parseBranchProtection(A->getValue(), PBP, Err))
1777
1
        D.Diag(diag::err_invalid_branch_protection)
1778
1
            << Err << A->getAsString(Args);
1779
22
      Scope = PBP.Scope;
1780
22
      Key = PBP.Key;
1781
22
      IndirectBranches = PBP.BranchTargetEnforcement;
1782
22
    }
1783
1784
30
    CmdArgs.push_back(
1785
30
        Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1786
30
    CmdArgs.push_back(
1787
30
        Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1788
30
    if (IndirectBranches)
1789
7
      CmdArgs.push_back("-mbranch-target-enforce");
1790
30
  }
1791
1792
  // Handle -msve_vector_bits=<bits>
1793
1.22k
  if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1794
15
    StringRef Val = A->getValue();
1795
15
    const Driver &D = getToolChain().getDriver();
1796
15
    if (Val.equals("128") || 
Val.equals("256")12
||
Val.equals("512")10
||
1797
8
        Val.equals("1024") || 
Val.equals("2048")6
)
1798
11
      CmdArgs.push_back(
1799
11
          Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
1800
    // Silently drop requests for vector-length agnostic code as it's implied.
1801
4
    else if (!Val.equals("scalable"))
1802
      // Handle the unsupported values passed to msve-vector-bits.
1803
2
      D.Diag(diag::err_drv_unsupported_option_argument)
1804
2
          << A->getOption().getName() << Val;
1805
15
  }
1806
1807
1.22k
  AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1808
1.22k
}
1809
1810
void Clang::AddMIPSTargetArgs(const ArgList &Args,
1811
584
                              ArgStringList &CmdArgs) const {
1812
584
  const Driver &D = getToolChain().getDriver();
1813
584
  StringRef CPUName;
1814
584
  StringRef ABIName;
1815
584
  const llvm::Triple &Triple = getToolChain().getTriple();
1816
584
  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1817
1818
584
  CmdArgs.push_back("-target-abi");
1819
584
  CmdArgs.push_back(ABIName.data());
1820
1821
584
  mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1822
584
  if (ABI == mips::FloatABI::Soft) {
1823
    // Floating point operations and argument passing are soft.
1824
96
    CmdArgs.push_back("-msoft-float");
1825
96
    CmdArgs.push_back("-mfloat-abi");
1826
96
    CmdArgs.push_back("soft");
1827
488
  } else {
1828
    // Floating point operations and argument passing are hard.
1829
488
    assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1830
0
    CmdArgs.push_back("-mfloat-abi");
1831
488
    CmdArgs.push_back("hard");
1832
488
  }
1833
1834
584
  if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1835
2
                               options::OPT_mno_ldc1_sdc1)) {
1836
2
    if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1837
1
      CmdArgs.push_back("-mllvm");
1838
1
      CmdArgs.push_back("-mno-ldc1-sdc1");
1839
1
    }
1840
2
  }
1841
1842
584
  if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1843
2
                               options::OPT_mno_check_zero_division)) {
1844
2
    if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1845
1
      CmdArgs.push_back("-mllvm");
1846
1
      CmdArgs.push_back("-mno-check-zero-division");
1847
1
    }
1848
2
  }
1849
1850
584
  if (Arg *A = Args.getLastArg(options::OPT_G)) {
1851
3
    StringRef v = A->getValue();
1852
3
    CmdArgs.push_back("-mllvm");
1853
3
    CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1854
3
    A->claim();
1855
3
  }
1856
1857
584
  Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1858
584
  Arg *ABICalls =
1859
584
      Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1860
1861
  // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1862
  // -mgpopt is the default for static, -fno-pic environments but these two
1863
  // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1864
  // the only case where -mllvm -mgpopt is passed.
1865
  // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1866
  //       passed explicitly when compiling something with -mabicalls
1867
  //       (implictly) in affect. Currently the warning is in the backend.
1868
  //
1869
  // When the ABI in use is  N64, we also need to determine the PIC mode that
1870
  // is in use, as -fno-pic for N64 implies -mno-abicalls.
1871
584
  bool NoABICalls =
1872
584
      ABICalls && 
ABICalls->getOption().matches(options::OPT_mno_abicalls)36
;
1873
1874
584
  llvm::Reloc::Model RelocationModel;
1875
584
  unsigned PICLevel;
1876
584
  bool IsPIE;
1877
584
  std::tie(RelocationModel, PICLevel, IsPIE) =
1878
584
      ParsePICArgs(getToolChain(), Args);
1879
1880
584
  NoABICalls = NoABICalls ||
1881
556
               (RelocationModel == llvm::Reloc::Static && 
ABIName == "n64"322
);
1882
1883
584
  bool WantGPOpt = GPOpt && 
GPOpt->getOption().matches(options::OPT_mgpopt)17
;
1884
  // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1885
584
  if (NoABICalls && 
(28
!GPOpt28
||
WantGPOpt12
)) {
1886
26
    CmdArgs.push_back("-mllvm");
1887
26
    CmdArgs.push_back("-mgpopt");
1888
1889
26
    Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1890
26
                                      options::OPT_mno_local_sdata);
1891
26
    Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1892
26
                                       options::OPT_mno_extern_sdata);
1893
26
    Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1894
26
                                        options::OPT_mno_embedded_data);
1895
26
    if (LocalSData) {
1896
2
      CmdArgs.push_back("-mllvm");
1897
2
      if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1898
1
        CmdArgs.push_back("-mlocal-sdata=1");
1899
1
      } else {
1900
1
        CmdArgs.push_back("-mlocal-sdata=0");
1901
1
      }
1902
2
      LocalSData->claim();
1903
2
    }
1904
1905
26
    if (ExternSData) {
1906
2
      CmdArgs.push_back("-mllvm");
1907
2
      if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1908
1
        CmdArgs.push_back("-mextern-sdata=1");
1909
1
      } else {
1910
1
        CmdArgs.push_back("-mextern-sdata=0");
1911
1
      }
1912
2
      ExternSData->claim();
1913
2
    }
1914
1915
26
    if (EmbeddedData) {
1916
2
      CmdArgs.push_back("-mllvm");
1917
2
      if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1918
1
        CmdArgs.push_back("-membedded-data=1");
1919
1
      } else {
1920
1
        CmdArgs.push_back("-membedded-data=0");
1921
1
      }
1922
2
      EmbeddedData->claim();
1923
2
    }
1924
1925
558
  } else if ((!ABICalls || 
(10
!NoABICalls10
&&
ABICalls8
)) &&
WantGPOpt556
)
1926
5
    D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 
02
:
13
);
1927
1928
584
  if (GPOpt)
1929
17
    GPOpt->claim();
1930
1931
584
  if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1932
3
    StringRef Val = StringRef(A->getValue());
1933
3
    if (mips::hasCompactBranches(CPUName)) {
1934
3
      if (Val == "never" || 
Val == "always"2
||
Val == "optimal"1
) {
1935
3
        CmdArgs.push_back("-mllvm");
1936
3
        CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1937
3
      } else
1938
0
        D.Diag(diag::err_drv_unsupported_option_argument)
1939
0
            << A->getOption().getName() << Val;
1940
3
    } else
1941
0
      D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1942
3
  }
1943
1944
584
  if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1945
2
                               options::OPT_mno_relax_pic_calls)) {
1946
2
    if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1947
1
      CmdArgs.push_back("-mllvm");
1948
1
      CmdArgs.push_back("-mips-jalr-reloc=0");
1949
1
    }
1950
2
  }
1951
584
}
1952
1953
void Clang::AddPPCTargetArgs(const ArgList &Args,
1954
452
                             ArgStringList &CmdArgs) const {
1955
  // Select the ABI to use.
1956
452
  const char *ABIName = nullptr;
1957
452
  const llvm::Triple &T = getToolChain().getTriple();
1958
452
  if (T.isOSBinFormatELF()) {
1959
369
    switch (getToolChain().getArch()) {
1960
134
    case llvm::Triple::ppc64: {
1961
134
      if ((T.isOSFreeBSD() && 
T.getOSMajorVersion() >= 1310
) ||
1962
131
          T.isOSOpenBSD() || 
T.isMusl()130
)
1963
6
        ABIName = "elfv2";
1964
128
      else
1965
128
        ABIName = "elfv1";
1966
134
      break;
1967
0
    }
1968
175
    case llvm::Triple::ppc64le:
1969
175
      ABIName = "elfv2";
1970
175
      break;
1971
60
    default:
1972
60
      break;
1973
369
    }
1974
369
  }
1975
1976
452
  bool IEEELongDouble = false;
1977
25
  for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1978
25
    StringRef V = A->getValue();
1979
25
    if (V == "ieeelongdouble")
1980
4
      IEEELongDouble = true;
1981
21
    else if (V == "ibmlongdouble")
1982
3
      IEEELongDouble = false;
1983
18
    else if (V != "altivec")
1984
      // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1985
      // the option if given as we don't have backend support for any targets
1986
      // that don't use the altivec abi.
1987
16
      ABIName = A->getValue();
1988
25
  }
1989
452
  if (IEEELongDouble)
1990
4
    CmdArgs.push_back("-mabi=ieeelongdouble");
1991
1992
452
  ppc::FloatABI FloatABI =
1993
452
      ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1994
1995
452
  if (FloatABI == ppc::FloatABI::Soft) {
1996
    // Floating point operations and argument passing are soft.
1997
9
    CmdArgs.push_back("-msoft-float");
1998
9
    CmdArgs.push_back("-mfloat-abi");
1999
9
    CmdArgs.push_back("soft");
2000
443
  } else {
2001
    // Floating point operations and argument passing are hard.
2002
443
    assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2003
0
    CmdArgs.push_back("-mfloat-abi");
2004
443
    CmdArgs.push_back("hard");
2005
443
  }
2006
2007
452
  if (ABIName) {
2008
309
    CmdArgs.push_back("-target-abi");
2009
309
    CmdArgs.push_back(ABIName);
2010
309
  }
2011
452
}
2012
2013
static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2014
395
                                   ArgStringList &CmdArgs) {
2015
395
  const Driver &D = TC.getDriver();
2016
395
  const llvm::Triple &Triple = TC.getTriple();
2017
  // Default small data limitation is eight.
2018
395
  const char *SmallDataLimit = "8";
2019
  // Get small data limitation.
2020
395
  if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2021
4
                      options::OPT_fPIC)) {
2022
    // Not support linker relaxation for PIC.
2023
4
    SmallDataLimit = "0";
2024
4
    if (Args.hasArg(options::OPT_G)) {
2025
1
      D.Diag(diag::warn_drv_unsupported_sdata);
2026
1
    }
2027
391
  } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2028
391
                 .equals_lower("large") &&
2029
2
             (Triple.getArch() == llvm::Triple::riscv64)) {
2030
    // Not support linker relaxation for RV64 with large code model.
2031
2
    SmallDataLimit = "0";
2032
2
    if (Args.hasArg(options::OPT_G)) {
2033
1
      D.Diag(diag::warn_drv_unsupported_sdata);
2034
1
    }
2035
389
  } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2036
8
    SmallDataLimit = A->getValue();
2037
8
  }
2038
  // Forward the -msmall-data-limit= option.
2039
395
  CmdArgs.push_back("-msmall-data-limit");
2040
395
  CmdArgs.push_back(SmallDataLimit);
2041
395
}
2042
2043
void Clang::AddRISCVTargetArgs(const ArgList &Args,
2044
395
                               ArgStringList &CmdArgs) const {
2045
395
  const llvm::Triple &Triple = getToolChain().getTriple();
2046
395
  StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2047
2048
395
  CmdArgs.push_back("-target-abi");
2049
395
  CmdArgs.push_back(ABIName.data());
2050
2051
395
  SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2052
2053
395
  std::string TuneCPU;
2054
2055
395
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2056
11
    StringRef Name = A->getValue();
2057
2058
11
    Name = llvm::RISCV::resolveTuneCPUAlias(Name, Triple.isArch64Bit());
2059
11
    TuneCPU = std::string(Name);
2060
11
  }
2061
2062
395
  if (!TuneCPU.empty()) {
2063
11
    CmdArgs.push_back("-tune-cpu");
2064
11
    CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2065
11
  }
2066
395
}
2067
2068
void Clang::AddSparcTargetArgs(const ArgList &Args,
2069
166
                               ArgStringList &CmdArgs) const {
2070
166
  sparc::FloatABI FloatABI =
2071
166
      sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2072
2073
166
  if (FloatABI == sparc::FloatABI::Soft) {
2074
    // Floating point operations and argument passing are soft.
2075
4
    CmdArgs.push_back("-msoft-float");
2076
4
    CmdArgs.push_back("-mfloat-abi");
2077
4
    CmdArgs.push_back("soft");
2078
162
  } else {
2079
    // Floating point operations and argument passing are hard.
2080
162
    assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2081
0
    CmdArgs.push_back("-mfloat-abi");
2082
162
    CmdArgs.push_back("hard");
2083
162
  }
2084
166
}
2085
2086
void Clang::AddSystemZTargetArgs(const ArgList &Args,
2087
63
                                 ArgStringList &CmdArgs) const {
2088
63
  bool HasBackchain = Args.hasFlag(options::OPT_mbackchain,
2089
63
                                   options::OPT_mno_backchain, false);
2090
63
  bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2091
63
                                     options::OPT_mno_packed_stack, false);
2092
63
  systemz::FloatABI FloatABI =
2093
63
      systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2094
63
  bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2095
63
  if (HasBackchain && 
HasPackedStack3
&&
!HasSoftFloat2
) {
2096
1
    const Driver &D = getToolChain().getDriver();
2097
1
    D.Diag(diag::err_drv_unsupported_opt)
2098
1
      << "-mpacked-stack -mbackchain -mhard-float";
2099
1
  }
2100
63
  if (HasBackchain)
2101
3
    CmdArgs.push_back("-mbackchain");
2102
63
  if (HasPackedStack)
2103
2
    CmdArgs.push_back("-mpacked-stack");
2104
63
  if (HasSoftFloat) {
2105
    // Floating point operations and argument passing are soft.
2106
3
    CmdArgs.push_back("-msoft-float");
2107
3
    CmdArgs.push_back("-mfloat-abi");
2108
3
    CmdArgs.push_back("soft");
2109
3
  }
2110
63
}
2111
2112
void Clang::AddX86TargetArgs(const ArgList &Args,
2113
36.2k
                             ArgStringList &CmdArgs) const {
2114
36.2k
  const Driver &D = getToolChain().getDriver();
2115
36.2k
  addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2116
2117
36.2k
  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2118
36.2k
      Args.hasArg(options::OPT_mkernel) ||
2119
36.2k
      Args.hasArg(options::OPT_fapple_kext))
2120
18
    CmdArgs.push_back("-disable-red-zone");
2121
2122
36.2k
  if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2123
36.2k
                    options::OPT_mno_tls_direct_seg_refs, true))
2124
1
    CmdArgs.push_back("-mno-tls-direct-seg-refs");
2125
2126
  // Default to avoid implicit floating-point for kernel/kext code, but allow
2127
  // that to be overridden with -mno-soft-float.
2128
36.2k
  bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2129
36.2k
                          Args.hasArg(options::OPT_fapple_kext));
2130
36.2k
  if (Arg *A = Args.getLastArg(
2131
36.2k
          options::OPT_msoft_float, options::OPT_mno_soft_float,
2132
6
          options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2133
6
    const Option &O = A->getOption();
2134
6
    NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2135
5
                       O.matches(options::OPT_msoft_float));
2136
6
  }
2137
36.2k
  if (NoImplicitFloat)
2138
19
    CmdArgs.push_back("-no-implicit-float");
2139
2140
36.2k
  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2141
3
    StringRef Value = A->getValue();
2142
3
    if (Value == "intel" || 
Value == "att"2
) {
2143
2
      CmdArgs.push_back("-mllvm");
2144
2
      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2145
1
    } else {
2146
1
      D.Diag(diag::err_drv_unsupported_option_argument)
2147
1
          << A->getOption().getName() << Value;
2148
1
    }
2149
36.2k
  } else if (D.IsCLMode()) {
2150
528
    CmdArgs.push_back("-mllvm");
2151
528
    CmdArgs.push_back("-x86-asm-syntax=intel");
2152
528
  }
2153
2154
  // Set flags to support MCU ABI.
2155
36.2k
  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2156
8
    CmdArgs.push_back("-mfloat-abi");
2157
8
    CmdArgs.push_back("soft");
2158
8
    CmdArgs.push_back("-mstack-alignment=4");
2159
8
  }
2160
2161
  // Handle -mtune.
2162
2163
  // Default to "generic" unless -march is present or targetting the PS4.
2164
36.2k
  std::string TuneCPU;
2165
36.2k
  if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2166
35.8k
      !getToolChain().getTriple().isPS4CPU())
2167
35.6k
    TuneCPU = "generic";
2168
2169
  // Override based on -mtune.
2170
36.2k
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2171
10
    StringRef Name = A->getValue();
2172
2173
10
    if (Name == "native") {
2174
0
      Name = llvm::sys::getHostCPUName();
2175
0
      if (!Name.empty())
2176
0
        TuneCPU = std::string(Name);
2177
0
    } else
2178
10
      TuneCPU = std::string(Name);
2179
10
  }
2180
2181
36.2k
  if (!TuneCPU.empty()) {
2182
35.6k
    CmdArgs.push_back("-tune-cpu");
2183
35.6k
    CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2184
35.6k
  }
2185
36.2k
}
2186
2187
void Clang::AddHexagonTargetArgs(const ArgList &Args,
2188
96
                                 ArgStringList &CmdArgs) const {
2189
96
  CmdArgs.push_back("-mqdsp6-compat");
2190
96
  CmdArgs.push_back("-Wreturn-type");
2191
2192
96
  if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2193
9
    CmdArgs.push_back("-mllvm");
2194
9
    CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
2195
9
                                         Twine(G.getValue())));
2196
9
  }
2197
2198
96
  if (!Args.hasArg(options::OPT_fno_short_enums))
2199
96
    CmdArgs.push_back("-fshort-enums");
2200
96
  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2201
0
    CmdArgs.push_back("-mllvm");
2202
0
    CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2203
0
  }
2204
96
  CmdArgs.push_back("-mllvm");
2205
96
  CmdArgs.push_back("-machine-sink-split=0");
2206
96
}
2207
2208
void Clang::AddLanaiTargetArgs(const ArgList &Args,
2209
3
                               ArgStringList &CmdArgs) const {
2210
3
  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2211
0
    StringRef CPUName = A->getValue();
2212
2213
0
    CmdArgs.push_back("-target-cpu");
2214
0
    CmdArgs.push_back(Args.MakeArgString(CPUName));
2215
0
  }
2216
3
  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2217
0
    StringRef Value = A->getValue();
2218
    // Only support mregparm=4 to support old usage. Report error for all other
2219
    // cases.
2220
0
    int Mregparm;
2221
0
    if (Value.getAsInteger(10, Mregparm)) {
2222
0
      if (Mregparm != 4) {
2223
0
        getToolChain().getDriver().Diag(
2224
0
            diag::err_drv_unsupported_option_argument)
2225
0
            << A->getOption().getName() << Value;
2226
0
      }
2227
0
    }
2228
0
  }
2229
3
}
2230
2231
void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2232
74
                                     ArgStringList &CmdArgs) const {
2233
  // Default to "hidden" visibility.
2234
74
  if (!Args.hasArg(options::OPT_fvisibility_EQ,
2235
72
                   options::OPT_fvisibility_ms_compat)) {
2236
72
    CmdArgs.push_back("-fvisibility");
2237
72
    CmdArgs.push_back("hidden");
2238
72
  }
2239
74
}
2240
2241
0
void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2242
  // Floating point operations and argument passing are hard.
2243
0
  CmdArgs.push_back("-mfloat-abi");
2244
0
  CmdArgs.push_back("hard");
2245
0
}
2246
2247
void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2248
                                    StringRef Target, const InputInfo &Output,
2249
7
                                    const InputInfo &Input, const ArgList &Args) const {
2250
  // If this is a dry run, do not create the compilation database file.
2251
7
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2252
0
    return;
2253
2254
7
  using llvm::yaml::escape;
2255
7
  const Driver &D = getToolChain().getDriver();
2256
2257
7
  if (!CompilationDatabase) {
2258
3
    std::error_code EC;
2259
3
    auto File = std::make_unique<llvm::raw_fd_ostream>(Filename, EC,
2260
3
                                                        llvm::sys::fs::OF_Text);
2261
3
    if (EC) {
2262
1
      D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2263
1
                                                       << EC.message();
2264
1
      return;
2265
1
    }
2266
2
    CompilationDatabase = std::move(File);
2267
2
  }
2268
6
  auto &CDB = *CompilationDatabase;
2269
6
  auto CWD = D.getVFS().getCurrentWorkingDirectory();
2270
6
  if (!CWD)
2271
0
    CWD = ".";
2272
6
  CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2273
6
  CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2274
6
  CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2275
6
  CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2276
6
  SmallString<128> Buf;
2277
6
  Buf = "-x";
2278
6
  Buf += types::getTypeName(Input.getType());
2279
6
  CDB << ", \"" << escape(Buf) << "\"";
2280
6
  if (!D.SysRoot.empty() && 
!Args.hasArg(options::OPT__sysroot_EQ)2
) {
2281
0
    Buf = "--sysroot=";
2282
0
    Buf += D.SysRoot;
2283
0
    CDB << ", \"" << escape(Buf) << "\"";
2284
0
  }
2285
6
  CDB << ", \"" << escape(Input.getFilename()) << "\"";
2286
64
  for (auto &A: Args) {
2287
64
    auto &O = A->getOption();
2288
    // Skip language selection, which is positional.
2289
64
    if (O.getID() == options::OPT_x)
2290
4
      continue;
2291
    // Skip writing dependency output and the compilation database itself.
2292
60
    if (O.getGroup().isValid() && 
O.getGroup().getID() == options::OPT_M_Group27
)
2293
7
      continue;
2294
53
    if (O.getID() == options::OPT_gen_cdb_fragment_path)
2295
4
      continue;
2296
    // Skip inputs.
2297
49
    if (O.getKind() == Option::InputClass)
2298
8
      continue;
2299
    // All other arguments are quoted and appended.
2300
41
    ArgStringList ASL;
2301
41
    A->render(Args, ASL);
2302
41
    for (auto &it: ASL)
2303
46
      CDB << ", \"" << escape(it) << "\"";
2304
41
  }
2305
6
  Buf = "--target=";
2306
6
  Buf += Target;
2307
6
  CDB << ", \"" << escape(Buf) << "\"]},\n";
2308
6
}
2309
2310
void Clang::DumpCompilationDatabaseFragmentToDir(
2311
    StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2312
4
    const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2313
  // If this is a dry run, do not create the compilation database file.
2314
4
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2315
1
    return;
2316
2317
3
  if (CompilationDatabase)
2318
0
    DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2319
2320
3
  SmallString<256> Path = Dir;
2321
3
  const auto &Driver = C.getDriver();
2322
3
  Driver.getVFS().makeAbsolute(Path);
2323
3
  auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2324
3
  if (Err) {
2325
0
    Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2326
0
    return;
2327
0
  }
2328
2329
3
  llvm::sys::path::append(
2330
3
      Path,
2331
3
      Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2332
3
  int FD;
2333
3
  SmallString<256> TempPath;
2334
3
  Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath);
2335
3
  if (Err) {
2336
0
    Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2337
0
    return;
2338
0
  }
2339
3
  CompilationDatabase =
2340
3
      std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2341
3
  DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2342
3
}
2343
2344
static bool AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2345
41
                                 StringRef Value) {
2346
41
  if (Value == "always" || 
Value == "never"25
||
Value == "arm"15
||
2347
36
      
Value == "thumb"10
) {
2348
36
    CmdArgs.push_back("-mllvm");
2349
36
    CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2350
36
    return true;
2351
36
  }
2352
5
  return false;
2353
41
}
2354
2355
static void CollectArgsForIntegratedAssembler(Compilation &C,
2356
                                              const ArgList &Args,
2357
                                              ArgStringList &CmdArgs,
2358
10.3k
                                              const Driver &D) {
2359
10.3k
  if (UseRelaxAll(C, Args))
2360
9.80k
    CmdArgs.push_back("-mrelax-all");
2361
2362
  // Only default to -mincremental-linker-compatible if we think we are
2363
  // targeting the MSVC linker.
2364
10.3k
  bool DefaultIncrementalLinkerCompatible =
2365
10.3k
      C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2366
10.3k
  if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2367
10.3k
                   options::OPT_mno_incremental_linker_compatible,
2368
10.3k
                   DefaultIncrementalLinkerCompatible))
2369
558
    CmdArgs.push_back("-mincremental-linker-compatible");
2370
2371
10.3k
  switch (C.getDefaultToolChain().getArch()) {
2372
1.17k
  case llvm::Triple::arm:
2373
1.29k
  case llvm::Triple::armeb:
2374
1.32k
  case llvm::Triple::thumb:
2375
1.33k
  case llvm::Triple::thumbeb:
2376
1.33k
    if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2377
8
      StringRef Value = A->getValue();
2378
8
      if (!AddARMImplicitITArgs(Args, CmdArgs, Value))
2379
1
        D.Diag(diag::err_drv_unsupported_option_argument)
2380
1
            << A->getOption().getName() << Value;
2381
8
    }
2382
1.33k
    break;
2383
9.04k
  default:
2384
9.04k
    break;
2385
10.3k
  }
2386
2387
  // If you add more args here, also add them to the block below that
2388
  // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2389
2390
  // When passing -I arguments to the assembler we sometimes need to
2391
  // unconditionally take the next argument.  For example, when parsing
2392
  // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2393
  // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2394
  // arg after parsing the '-I' arg.
2395
10.3k
  bool TakeNextArg = false;
2396
2397
10.3k
  bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2398
10.3k
  bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
2399
10.3k
  const char *MipsTargetFeature = nullptr;
2400
10.3k
  for (const Arg *A :
2401
144
       Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2402
144
    A->claim();
2403
2404
165
    for (StringRef Value : A->getValues()) {
2405
165
      if (TakeNextArg) {
2406
7
        CmdArgs.push_back(Value.data());
2407
7
        TakeNextArg = false;
2408
7
        continue;
2409
7
      }
2410
2411
158
      if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2412
2
          Value == "-mbig-obj")
2413
2
        continue; // LLVM handles bigobj automatically
2414
2415
156
      switch (C.getDefaultToolChain().getArch()) {
2416
38
      default:
2417
38
        break;
2418
0
      case llvm::Triple::thumb:
2419
0
      case llvm::Triple::thumbeb:
2420
86
      case llvm::Triple::arm:
2421
86
      case llvm::Triple::armeb:
2422
86
        if (Value.startswith("-mimplicit-it=") &&
2423
33
            AddARMImplicitITArgs(Args, CmdArgs, Value.split("=").second))
2424
29
          continue;
2425
57
        if (Value == "-mthumb")
2426
          // -mthumb has already been processed in ComputeLLVMTriple()
2427
          // recognize but skip over here.
2428
6
          continue;
2429
51
        break;
2430
32
      case llvm::Triple::mips:
2431
32
      case llvm::Triple::mipsel:
2432
32
      case llvm::Triple::mips64:
2433
32
      case llvm::Triple::mips64el:
2434
32
        if (Value == "--trap") {
2435
3
          CmdArgs.push_back("-target-feature");
2436
3
          CmdArgs.push_back("+use-tcc-in-div");
2437
3
          continue;
2438
3
        }
2439
29
        if (Value == "--break") {
2440
3
          CmdArgs.push_back("-target-feature");
2441
3
          CmdArgs.push_back("-use-tcc-in-div");
2442
3
          continue;
2443
3
        }
2444
26
        if (Value.startswith("-msoft-float")) {
2445
3
          CmdArgs.push_back("-target-feature");
2446
3
          CmdArgs.push_back("+soft-float");
2447
3
          continue;
2448
3
        }
2449
23
        if (Value.startswith("-mhard-float")) {
2450
3
          CmdArgs.push_back("-target-feature");
2451
3
          CmdArgs.push_back("-soft-float");
2452
3
          continue;
2453
3
        }
2454
2455
20
        MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2456
20
                                .Case("-mips1", "+mips1")
2457
20
                                .Case("-mips2", "+mips2")
2458
20
                                .Case("-mips3", "+mips3")
2459
20
                                .Case("-mips4", "+mips4")
2460
20
                                .Case("-mips5", "+mips5")
2461
20
                                .Case("-mips32", "+mips32")
2462
20
                                .Case("-mips32r2", "+mips32r2")
2463
20
                                .Case("-mips32r3", "+mips32r3")
2464
20
                                .Case("-mips32r5", "+mips32r5")
2465
20
                                .Case("-mips32r6", "+mips32r6")
2466
20
                                .Case("-mips64", "+mips64")
2467
20
                                .Case("-mips64r2", "+mips64r2")
2468
20
                                .Case("-mips64r3", "+mips64r3")
2469
20
                                .Case("-mips64r5", "+mips64r5")
2470
20
                                .Case("-mips64r6", "+mips64r6")
2471
20
                                .Default(nullptr);
2472
20
        if (MipsTargetFeature)
2473
20
          continue;
2474
156
      }
2475
2476
89
      if (Value == "-force_cpusubtype_ALL") {
2477
        // Do nothing, this is the default and we don't support anything else.
2478
89
      } else if (Value == "-L") {
2479
1
        CmdArgs.push_back("-msave-temp-labels");
2480
88
      } else if (Value == "--fatal-warnings") {
2481
2
        CmdArgs.push_back("-massembler-fatal-warnings");
2482
86
      } else if (Value == "--no-warn" || Value == "-W") {
2483
0
        CmdArgs.push_back("-massembler-no-warn");
2484
86
      } else if (Value == "--noexecstack") {
2485
1
        UseNoExecStack = true;
2486
85
      } else if (Value.startswith("-compress-debug-sections") ||
2487
83
                 Value.startswith("--compress-debug-sections") ||
2488
79
                 Value == "-nocompress-debug-sections" ||
2489
79
                 Value == "--nocompress-debug-sections") {
2490
7
        CmdArgs.push_back(Value.data());
2491
78
      } else if (Value == "-mrelax-relocations=yes" ||
2492
76
                 Value == "--mrelax-relocations=yes") {
2493
4
        UseRelaxRelocations = true;
2494
74
      } else if (Value == "-mrelax-relocations=no" ||
2495
72
                 Value == "--mrelax-relocations=no") {
2496
2
        UseRelaxRelocations = false;
2497
72
      } else if (Value.startswith("-I")) {
2498
5
        CmdArgs.push_back(Value.data());
2499
        // We need to consume the next argument if the current arg is a plain
2500
        // -I. The next arg will be the include directory.
2501
5
        if (Value == "-I")
2502
3
          TakeNextArg = true;
2503
67
      } else if (Value.startswith("-gdwarf-")) {
2504
        // "-gdwarf-N" options are not cc1as options.
2505
3
        unsigned DwarfVersion = DwarfVersionNum(Value);
2506
3
        if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2507
1
          CmdArgs.push_back(Value.data());
2508
2
        } else {
2509
2
          RenderDebugEnablingArgs(Args, CmdArgs,
2510
2
                                  codegenoptions::LimitedDebugInfo,
2511
2
                                  DwarfVersion, llvm::DebuggerKind::Default);
2512
2
        }
2513
64
      } else if (Value.startswith("-mcpu") || 
Value.startswith("-mfpu")47
||
2514
47
                 
Value.startswith("-mhwdiv")44
||
Value.startswith("-march")40
) {
2515
        // Do nothing, we'll validate it later.
2516
17
      } else if (Value == "-defsym") {
2517
7
          if (A->getNumValues() != 2) {
2518
2
            D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2519
2
            break;
2520
2
          }
2521
5
          const char *S = A->getValue(1);
2522
5
          auto Pair = StringRef(S).split('=');
2523
5
          auto Sym = Pair.first;
2524
5
          auto SVal = Pair.second;
2525
2526
5
          if (Sym.empty() || 
SVal.empty()4
) {
2527
2
            D.Diag(diag::err_drv_defsym_invalid_format) << S;
2528
2
            break;
2529
2
          }
2530
3
          int64_t IVal;
2531
3
          if (SVal.getAsInteger(0, IVal)) {
2532
1
            D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2533
1
            break;
2534
1
          }
2535
2
          CmdArgs.push_back(Value.data());
2536
2
          TakeNextArg = true;
2537
10
      } else if (Value == "-fdebug-compilation-dir") {
2538
2
        CmdArgs.push_back("-fdebug-compilation-dir");
2539
2
        TakeNextArg = true;
2540
8
      } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2541
        // The flag is a -Wa / -Xassembler argument and Options doesn't
2542
        // parse the argument, so this isn't automatically aliased to
2543
        // -fdebug-compilation-dir (without '=') here.
2544
2
        CmdArgs.push_back("-fdebug-compilation-dir");
2545
2
        CmdArgs.push_back(Value.data());
2546
6
      } else {
2547
6
        D.Diag(diag::err_drv_unsupported_option_argument)
2548
6
            << A->getOption().getName() << Value;
2549
6
      }
2550
89
    }
2551
144
  }
2552
10.3k
  if (UseRelaxRelocations)
2553
10.3k
    CmdArgs.push_back("--mrelax-relocations");
2554
10.3k
  if (UseNoExecStack)
2555
196
    CmdArgs.push_back("-mnoexecstack");
2556
10.3k
  if (MipsTargetFeature != nullptr) {
2557
17
    CmdArgs.push_back("-target-feature");
2558
17
    CmdArgs.push_back(MipsTargetFeature);
2559
17
  }
2560
2561
  // forward -fembed-bitcode to assmebler
2562
10.3k
  if (C.getDriver().embedBitcodeEnabled() ||
2563
10.3k
      C.getDriver().embedBitcodeMarkerOnly())
2564
17
    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2565
10.3k
}
2566
2567
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2568
                                       bool OFastEnabled, const ArgList &Args,
2569
                                       ArgStringList &CmdArgs,
2570
42.1k
                                       const JobAction &JA) {
2571
  // Handle various floating point optimization flags, mapping them to the
2572
  // appropriate LLVM code generation flags. This is complicated by several
2573
  // "umbrella" flags, so we do this by stepping through the flags incrementally
2574
  // adjusting what we think is enabled/disabled, then at the end setting the
2575
  // LLVM flags based on the final state.
2576
42.1k
  bool HonorINFs = true;
2577
42.1k
  bool HonorNaNs = true;
2578
  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2579
42.1k
  bool MathErrno = TC.IsMathErrnoDefault();
2580
42.1k
  bool AssociativeMath = false;
2581
42.1k
  bool ReciprocalMath = false;
2582
42.1k
  bool SignedZeros = true;
2583
42.1k
  bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2584
42.1k
  bool TrappingMathPresent = false; // Is trapping-math in args, and not
2585
                                    // overriden by ffp-exception-behavior?
2586
42.1k
  bool RoundingFPMath = false;
2587
42.1k
  bool RoundingMathPresent = false; // Is rounding-math in args?
2588
  // -ffp-model values: strict, fast, precise
2589
42.1k
  StringRef FPModel = "";
2590
  // -ffp-exception-behavior options: strict, maytrap, ignore
2591
42.1k
  StringRef FPExceptionBehavior = "";
2592
42.1k
  const llvm::DenormalMode DefaultDenormalFPMath =
2593
42.1k
      TC.getDefaultDenormalModeForType(Args, JA);
2594
42.1k
  const llvm::DenormalMode DefaultDenormalFP32Math =
2595
42.1k
      TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2596
2597
42.1k
  llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2598
42.1k
  llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2599
42.1k
  StringRef FPContract = "";
2600
42.1k
  bool StrictFPModel = false;
2601
2602
2603
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2604
0
    CmdArgs.push_back("-mlimit-float-precision");
2605
0
    CmdArgs.push_back(A->getValue());
2606
0
  }
2607
2608
752k
  for (const Arg *A : Args) {
2609
752k
    auto optID = A->getOption().getID();
2610
752k
    bool PreciseFPModel = false;
2611
752k
    switch (optID) {
2612
752k
    default:
2613
752k
      break;
2614
23
    case options::OPT_ffp_model_EQ: {
2615
      // If -ffp-model= is seen, reset to fno-fast-math
2616
23
      HonorINFs = true;
2617
23
      HonorNaNs = true;
2618
      // Turning *off* -ffast-math restores the toolchain default.
2619
23
      MathErrno = TC.IsMathErrnoDefault();
2620
23
      AssociativeMath = false;
2621
23
      ReciprocalMath = false;
2622
23
      SignedZeros = true;
2623
      // -fno_fast_math restores default denormal and fpcontract handling
2624
23
      FPContract = "";
2625
23
      DenormalFPMath = llvm::DenormalMode::getIEEE();
2626
2627
      // FIXME: The target may have picked a non-IEEE default mode here based on
2628
      // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2629
23
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
2630
2631
23
      StringRef Val = A->getValue();
2632
23
      if (OFastEnabled && 
!Val.equals("fast")1
) {
2633
          // Only -ffp-model=fast is compatible with OFast, ignore.
2634
1
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2635
1
          << Args.MakeArgString("-ffp-model=" + Val)
2636
1
          << "-Ofast";
2637
1
        break;
2638
1
      }
2639
22
      StrictFPModel = false;
2640
22
      PreciseFPModel = true;
2641
      // ffp-model= is a Driver option, it is entirely rewritten into more
2642
      // granular options before being passed into cc1.
2643
      // Use the gcc option in the switch below.
2644
22
      if (!FPModel.empty() && 
!FPModel.equals(Val)0
) {
2645
0
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2646
0
          << Args.MakeArgString("-ffp-model=" + FPModel)
2647
0
          << Args.MakeArgString("-ffp-model=" + Val);
2648
0
        FPContract = "";
2649
0
      }
2650
22
      if (Val.equals("fast")) {
2651
4
        optID = options::OPT_ffast_math;
2652
4
        FPModel = Val;
2653
4
        FPContract = "fast";
2654
18
      } else if (Val.equals("precise")) {
2655
2
        optID = options::OPT_ffp_contract;
2656
2
        FPModel = Val;
2657
2
        FPContract = "fast";
2658
2
        PreciseFPModel = true;
2659
16
      } else if (Val.equals("strict")) {
2660
15
        StrictFPModel = true;
2661
15
        optID = options::OPT_frounding_math;
2662
15
        FPExceptionBehavior = "strict";
2663
15
        FPModel = Val;
2664
15
        FPContract = "off";
2665
15
        TrappingMath = true;
2666
15
      } else
2667
1
        D.Diag(diag::err_drv_unsupported_option_argument)
2668
1
            << A->getOption().getName() << Val;
2669
22
      break;
2670
23
      }
2671
752k
    }
2672
2673
752k
    switch (optID) {
2674
    // If this isn't an FP option skip the claim below
2675
752k
    default: continue;
2676
2677
    // Options controlling individual features
2678
3
    case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2679
7
    case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2680
3
    case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2681
8
    case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2682
8
    case options::OPT_fmath_errno:          MathErrno = true;         break;
2683
14
    case options::OPT_fno_math_errno:       MathErrno = false;        break;
2684
11
    case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2685
4
    case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2686
14
    case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2687
3
    case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2688
3
    case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2689
14
    case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2690
6
    case options::OPT_ftrapping_math:
2691
6
      if (!TrappingMathPresent && 
!FPExceptionBehavior.empty()5
&&
2692
0
          !FPExceptionBehavior.equals("strict"))
2693
        // Warn that previous value of option is overridden.
2694
0
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2695
0
          << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2696
0
          << "-ftrapping-math";
2697
6
      TrappingMath = true;
2698
6
      TrappingMathPresent = true;
2699
6
      FPExceptionBehavior = "strict";
2700
6
      break;
2701
12
    case options::OPT_fno_trapping_math:
2702
12
      if (!TrappingMathPresent && 
!FPExceptionBehavior.empty()11
&&
2703
1
          !FPExceptionBehavior.equals("ignore"))
2704
        // Warn that previous value of option is overridden.
2705
1
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2706
1
          << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2707
1
          << "-fno-trapping-math";
2708
12
      TrappingMath = false;
2709
12
      TrappingMathPresent = true;
2710
12
      FPExceptionBehavior = "ignore";
2711
12
      break;
2712
2713
18
    case options::OPT_frounding_math:
2714
18
      RoundingFPMath = true;
2715
18
      RoundingMathPresent = true;
2716
18
      break;
2717
2718
4
    case options::OPT_fno_rounding_math:
2719
4
      RoundingFPMath = false;
2720
4
      RoundingMathPresent = false;
2721
4
      break;
2722
2723
10
    case options::OPT_fdenormal_fp_math_EQ:
2724
10
      DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2725
10
      if (!DenormalFPMath.isValid()) {
2726
4
        D.Diag(diag::err_drv_invalid_value)
2727
4
            << A->getAsString(Args) << A->getValue();
2728
4
      }
2729
10
      break;
2730
2731
0
    case options::OPT_fdenormal_fp_math_f32_EQ:
2732
0
      DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2733
0
      if (!DenormalFP32Math.isValid()) {
2734
0
        D.Diag(diag::err_drv_invalid_value)
2735
0
            << A->getAsString(Args) << A->getValue();
2736
0
      }
2737
0
      break;
2738
2739
    // Validate and pass through -ffp-contract option.
2740
11
    case options::OPT_ffp_contract: {
2741
11
      StringRef Val = A->getValue();
2742
11
      if (PreciseFPModel) {
2743
        // -ffp-model=precise enables ffp-contract=fast as a side effect
2744
        // the FPContract value has already been set to a string literal
2745
        // and the Val string isn't a pertinent value.
2746
2
        ;
2747
9
      } else if (Val.equals("fast") || 
Val.equals("on")5
||
Val.equals("off")3
)
2748
9
        FPContract = Val;
2749
0
      else
2750
0
        D.Diag(diag::err_drv_unsupported_option_argument)
2751
0
           << A->getOption().getName() << Val;
2752
11
      break;
2753
0
    }
2754
2755
    // Validate and pass through -ffp-model option.
2756
2
    case options::OPT_ffp_model_EQ:
2757
      // This should only occur in the error case
2758
      // since the optID has been replaced by a more granular
2759
      // floating point option.
2760
2
      break;
2761
2762
    // Validate and pass through -ffp-exception-behavior option.
2763
7
    case options::OPT_ffp_exception_behavior_EQ: {
2764
7
      StringRef Val = A->getValue();
2765
7
      if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2766
0
          !FPExceptionBehavior.equals(Val))
2767
        // Warn that previous value of option is overridden.
2768
0
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2769
0
          << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2770
0
          << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2771
7
      TrappingMath = TrappingMathPresent = false;
2772
7
      if (Val.equals("ignore") || 
Val.equals("maytrap")5
)
2773
4
        FPExceptionBehavior = Val;
2774
3
      else if (Val.equals("strict")) {
2775
2
        FPExceptionBehavior = Val;
2776
2
        TrappingMath = TrappingMathPresent = true;
2777
2
      } else
2778
1
        D.Diag(diag::err_drv_unsupported_option_argument)
2779
1
            << A->getOption().getName() << Val;
2780
7
      break;
2781
0
    }
2782
2783
8
    case options::OPT_ffinite_math_only:
2784
8
      HonorINFs = false;
2785
8
      HonorNaNs = false;
2786
8
      break;
2787
6
    case options::OPT_fno_finite_math_only:
2788
6
      HonorINFs = true;
2789
6
      HonorNaNs = true;
2790
6
      break;
2791
2792
9
    case options::OPT_funsafe_math_optimizations:
2793
9
      AssociativeMath = true;
2794
9
      ReciprocalMath = true;
2795
9
      SignedZeros = false;
2796
9
      TrappingMath = false;
2797
9
      FPExceptionBehavior = "";
2798
9
      break;
2799
6
    case options::OPT_fno_unsafe_math_optimizations:
2800
6
      AssociativeMath = false;
2801
6
      ReciprocalMath = false;
2802
6
      SignedZeros = true;
2803
6
      TrappingMath = true;
2804
6
      FPExceptionBehavior = "strict";
2805
2806
      // The target may have opted to flush by default, so force IEEE.
2807
6
      DenormalFPMath = llvm::DenormalMode::getIEEE();
2808
6
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
2809
6
      break;
2810
2811
27
    case options::OPT_Ofast:
2812
      // If -Ofast is the optimization level, then -ffast-math should be enabled
2813
27
      if (!OFastEnabled)
2814
2
        continue;
2815
25
      LLVM_FALLTHROUGH;
2816
70
    case options::OPT_ffast_math:
2817
70
      HonorINFs = false;
2818
70
      HonorNaNs = false;
2819
70
      MathErrno = false;
2820
70
      AssociativeMath = true;
2821
70
      ReciprocalMath = true;
2822
70
      SignedZeros = false;
2823
70
      TrappingMath = false;
2824
70
      RoundingFPMath = false;
2825
      // If fast-math is set then set the fp-contract mode to fast.
2826
70
      FPContract = "fast";
2827
70
      break;
2828
31
    case options::OPT_fno_fast_math:
2829
31
      HonorINFs = true;
2830
31
      HonorNaNs = true;
2831
      // Turning on -ffast-math (with either flag) removes the need for
2832
      // MathErrno. However, turning *off* -ffast-math merely restores the
2833
      // toolchain default (which may be false).
2834
31
      MathErrno = TC.IsMathErrnoDefault();
2835
31
      AssociativeMath = false;
2836
31
      ReciprocalMath = false;
2837
31
      SignedZeros = true;
2838
31
      TrappingMath = false;
2839
31
      RoundingFPMath = false;
2840
      // -fno_fast_math restores default denormal and fpcontract handling
2841
31
      DenormalFPMath = DefaultDenormalFPMath;
2842
31
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
2843
31
      FPContract = "";
2844
31
      break;
2845
752k
    }
2846
292
    if (StrictFPModel) {
2847
      // If -ffp-model=strict has been specified on command line but
2848
      // subsequent options conflict then emit warning diagnostic.
2849
28
      if (HonorINFs && 
HonorNaNs25
&&
2850
24
        !AssociativeMath && 
!ReciprocalMath22
&&
2851
21
        SignedZeros && 
TrappingMath20
&&
RoundingFPMath19
&&
2852
18
        (FPContract.equals("off") || 
FPContract.empty()2
) &&
2853
16
        DenormalFPMath == llvm::DenormalMode::getIEEE() &&
2854
15
        DenormalFP32Math == llvm::DenormalMode::getIEEE())
2855
        // OK: Current Arg doesn't conflict with -ffp-model=strict
2856
15
        ;
2857
13
      else {
2858
13
        StrictFPModel = false;
2859
13
        FPModel = "";
2860
13
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2861
13
            << "-ffp-model=strict" <<
2862
13
            ((A->getNumValues() == 0) ?  
A->getSpelling()10
2863
3
            : Args.MakeArgString(A->getSpelling() + A->getValue()));
2864
13
      }
2865
28
    }
2866
2867
    // If we handled this option claim it
2868
292
    A->claim();
2869
292
  }
2870
2871
42.1k
  if (!HonorINFs)
2872
70
    CmdArgs.push_back("-menable-no-infs");
2873
2874
42.1k
  if (!HonorNaNs)
2875
71
    CmdArgs.push_back("-menable-no-nans");
2876
2877
42.1k
  if (MathErrno)
2878
24.7k
    CmdArgs.push_back("-fmath-errno");
2879
2880
42.1k
  if (!MathErrno && 
AssociativeMath17.4k
&&
ReciprocalMath72
&&
!SignedZeros68
&&
2881
65
      !TrappingMath)
2882
61
    CmdArgs.push_back("-menable-unsafe-fp-math");
2883
2884
42.1k
  if (!SignedZeros)
2885
79
    CmdArgs.push_back("-fno-signed-zeros");
2886
2887
42.1k
  if (AssociativeMath && 
!SignedZeros75
&&
!TrappingMath71
)
2888
67
    CmdArgs.push_back("-mreassociate");
2889
2890
42.1k
  if (ReciprocalMath)
2891
78
    CmdArgs.push_back("-freciprocal-math");
2892
2893
42.1k
  if (TrappingMath) {
2894
    // FP Exception Behavior is also set to strict
2895
24
    assert(FPExceptionBehavior.equals("strict"));
2896
24
  }
2897
2898
  // The default is IEEE.
2899
42.1k
  if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
2900
150
    llvm::SmallString<64> DenormFlag;
2901
150
    llvm::raw_svector_ostream ArgStr(DenormFlag);
2902
150
    ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
2903
150
    CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
2904
150
  }
2905
2906
  // Add f32 specific denormal mode flag if it's different.
2907
42.1k
  if (DenormalFP32Math != DenormalFPMath) {
2908
122
    llvm::SmallString<64> DenormFlag;
2909
122
    llvm::raw_svector_ostream ArgStr(DenormFlag);
2910
122
    ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
2911
122
    CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
2912
122
  }
2913
2914
42.1k
  if (!FPContract.empty())
2915
85
    CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2916
2917
42.1k
  if (!RoundingFPMath)
2918
42.1k
    CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
2919
2920
42.1k
  if (RoundingFPMath && 
RoundingMathPresent15
)
2921
15
    CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
2922
2923
42.1k
  if (!FPExceptionBehavior.empty())
2924
41
    CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
2925
41
                      FPExceptionBehavior));
2926
2927
42.1k
  ParseMRecip(D, Args, CmdArgs);
2928
2929
  // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2930
  // individual features enabled by -ffast-math instead of the option itself as
2931
  // that's consistent with gcc's behaviour.
2932
42.1k
  if (!HonorINFs && 
!HonorNaNs70
&&
!MathErrno64
&&
AssociativeMath62
&&
2933
54
      ReciprocalMath && 
!SignedZeros53
&&
!TrappingMath52
&&
!RoundingFPMath50
) {
2934
50
    CmdArgs.push_back("-ffast-math");
2935
50
    if (FPModel.equals("fast")) {
2936
4
      if (FPContract.equals("fast"))
2937
        // All set, do nothing.
2938
2
        ;
2939
2
      else if (FPContract.empty())
2940
        // Enable -ffp-contract=fast
2941
0
        CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2942
2
      else
2943
2
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2944
2
          << "-ffp-model=fast"
2945
2
          << Args.MakeArgString("-ffp-contract=" + FPContract);
2946
4
    }
2947
50
  }
2948
2949
  // Handle __FINITE_MATH_ONLY__ similarly.
2950
42.1k
  if (!HonorINFs && 
!HonorNaNs70
)
2951
64
    CmdArgs.push_back("-ffinite-math-only");
2952
2953
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2954
0
    CmdArgs.push_back("-mfpmath");
2955
0
    CmdArgs.push_back(A->getValue());
2956
0
  }
2957
2958
  // Disable a codegen optimization for floating-point casts.
2959
42.1k
  if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2960
42.1k
                   options::OPT_fstrict_float_cast_overflow, false))
2961
1
    CmdArgs.push_back("-fno-strict-float-cast-overflow");
2962
42.1k
}
2963
2964
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2965
                                  const llvm::Triple &Triple,
2966
41
                                  const InputInfo &Input) {
2967
  // Enable region store model by default.
2968
41
  CmdArgs.push_back("-analyzer-store=region");
2969
2970
  // Treat blocks as analysis entry points.
2971
41
  CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2972
2973
  // Add default argument set.
2974
41
  if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2975
41
    CmdArgs.push_back("-analyzer-checker=core");
2976
41
    CmdArgs.push_back("-analyzer-checker=apiModeling");
2977
2978
41
    if (!Triple.isWindowsMSVCEnvironment()) {
2979
40
      CmdArgs.push_back("-analyzer-checker=unix");
2980
1
    } else {
2981
      // Enable "unix" checkers that also work on Windows.
2982
1
      CmdArgs.push_back("-analyzer-checker=unix.API");
2983
1
      CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2984
1
      CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2985
1
      CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2986
1
      CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2987
1
      CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2988
1
    }
2989
2990
    // Disable some unix checkers for PS4.
2991
41
    if (Triple.isPS4CPU()) {
2992
3
      CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2993
3
      CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2994
3
    }
2995
2996
41
    if (Triple.isOSDarwin()) {
2997
34
      CmdArgs.push_back("-analyzer-checker=osx");
2998
34
      CmdArgs.push_back(
2999
34
          "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3000
34
    }
3001
7
    else if (Triple.isOSFuchsia())
3002
0
      CmdArgs.push_back("-analyzer-checker=fuchsia");
3003
3004
41
    CmdArgs.push_back("-analyzer-checker=deadcode");
3005
3006
41
    if (types::isCXX(Input.getType()))
3007
15
      CmdArgs.push_back("-analyzer-checker=cplusplus");
3008
3009
41
    if (!Triple.isPS4CPU()) {
3010
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3011
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3012
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3013
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3014
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3015
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3016
38
    }
3017
3018
    // Default nullability checks.
3019
41
    CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3020
41
    CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3021
41
  }
3022
3023
  // Set the output format. The default is plist, for (lame) historical reasons.
3024
41
  CmdArgs.push_back("-analyzer-output");
3025
41
  if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3026
0
    CmdArgs.push_back(A->getValue());
3027
41
  else
3028
41
    CmdArgs.push_back("plist");
3029
3030
  // Disable the presentation of standard compiler warnings when using
3031
  // --analyze.  We only want to show static analyzer diagnostics or frontend
3032
  // errors.
3033
41
  CmdArgs.push_back("-w");
3034
3035
  // Add -Xanalyzer arguments when running as analyzer.
3036
41
  Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3037
41
}
3038
3039
static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3040
                             const ArgList &Args, ArgStringList &CmdArgs,
3041
42.1k
                             bool KernelOrKext) {
3042
42.1k
  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3043
3044
  // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3045
  // doesn't even have a stack!
3046
42.1k
  if (EffectiveTriple.isNVPTX())
3047
340
    return;
3048
3049
  // -stack-protector=0 is default.
3050
41.8k
  LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3051
41.8k
  LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3052
41.8k
      TC.GetDefaultStackProtectorLevel(KernelOrKext);
3053
3054
41.8k
  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3055
41.8k
                               options::OPT_fstack_protector_all,
3056
41.8k
                               options::OPT_fstack_protector_strong,
3057
15
                               options::OPT_fstack_protector)) {
3058
15
    if (A->getOption().matches(options::OPT_fstack_protector))
3059
9
      StackProtectorLevel =
3060
9
          std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3061
6
    else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3062
2
      StackProtectorLevel = LangOptions::SSPStrong;
3063
4
    else if (A->getOption().matches(options::OPT_fstack_protector_all))
3064
3
      StackProtectorLevel = LangOptions::SSPReq;
3065
41.7k
  } else {
3066
41.7k
    StackProtectorLevel = DefaultStackProtectorLevel;
3067
41.7k
  }
3068
3069
41.8k
  if (StackProtectorLevel) {
3070
16.0k
    CmdArgs.push_back("-stack-protector");
3071
16.0k
    CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3072
16.0k
  }
3073
3074
  // --param ssp-buffer-size=
3075
5
  for (const Arg *A : Args.filtered(options::OPT__param)) {
3076
5
    StringRef Str(A->getValue());
3077
5
    if (Str.startswith("ssp-buffer-size=")) {
3078
2
      if (StackProtectorLevel) {
3079
2
        CmdArgs.push_back("-stack-protector-buffer-size");
3080
        // FIXME: Verify the argument is a valid integer.
3081
2
        CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3082
2
      }
3083
2
      A->claim();
3084
2
    }
3085
5
  }
3086
3087
  // First support "tls" and "global" for X86 target.
3088
  // TODO: Support "sysreg" for AArch64.
3089
41.8k
  const std::string &TripleStr = EffectiveTriple.getTriple();
3090
41.8k
  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3091
4
    StringRef Value = A->getValue();
3092
4
    if (!EffectiveTriple.isX86() && 
!EffectiveTriple.isAArch64()1
)
3093
1
      D.Diag(diag::err_drv_unsupported_opt_for_target)
3094
1
          << A->getAsString(Args) << TripleStr;
3095
4
    if (Value != "tls" && 
Value != "global"2
) {
3096
1
      D.Diag(diag::err_drv_invalid_value_with_suggestion)
3097
1
      << A->getOption().getName() << Value
3098
1
      << "valid arguments to '-mstack-protector-guard=' are:tls global";
3099
1
      return;
3100
1
    }
3101
3
    A->render(Args, CmdArgs);
3102
3
  }
3103
3104
41.8k
  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3105
2
    StringRef Value = A->getValue();
3106
2
    if (!EffectiveTriple.isX86())
3107
1
      D.Diag(diag::err_drv_unsupported_opt_for_target)
3108
1
          << A->getAsString(Args) << TripleStr;
3109
2
    unsigned Offset;
3110
2
    if (Value.getAsInteger(10, Offset)) {
3111
0
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3112
0
      return;
3113
0
    }
3114
2
    A->render(Args, CmdArgs);
3115
2
  }
3116
3117
41.8k
  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3118
5
    StringRef Value = A->getValue();
3119
5
    if (!EffectiveTriple.isX86())
3120
1
      D.Diag(diag::err_drv_unsupported_opt_for_target)
3121
1
          << A->getAsString(Args) << TripleStr;
3122
5
    if (EffectiveTriple.isX86() && 
(4
Value != "fs"4
&&
Value != "gs"3
)) {
3123
2
      D.Diag(diag::err_drv_invalid_value_with_suggestion)
3124
2
      << A->getOption().getName() << Value
3125
2
      << "for X86, valid arguments to '-mstack-protector-guard-reg=' are:fs gs";
3126
2
      return;
3127
2
    }
3128
3
    A->render(Args, CmdArgs);
3129
3
  }
3130
41.8k
}
3131
3132
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3133
42.1k
                             ArgStringList &CmdArgs) {
3134
42.1k
  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3135
3136
42.1k
  if (!EffectiveTriple.isOSLinux())
3137
37.5k
    return;
3138
3139
4.60k
  if (!EffectiveTriple.isX86() && 
!EffectiveTriple.isSystemZ()1.86k
&&
3140
1.82k
      !EffectiveTriple.isPPC64())
3141
1.58k
    return;
3142
3143
3.02k
  if (Args.hasFlag(options::OPT_fstack_clash_protection,
3144
3.02k
                   options::OPT_fno_stack_clash_protection, false))
3145
7
    CmdArgs.push_back("-fstack-clash-protection");
3146
3.02k
}
3147
3148
static void RenderTrivialAutoVarInitOptions(const Driver &D,
3149
                                            const ToolChain &TC,
3150
                                            const ArgList &Args,
3151
42.1k
                                            ArgStringList &CmdArgs) {
3152
42.1k
  auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3153
42.1k
  StringRef TrivialAutoVarInit = "";
3154
3155
752k
  for (const Arg *A : Args) {
3156
752k
    switch (A->getOption().getID()) {
3157
752k
    default:
3158
752k
      continue;
3159
8
    case options::OPT_ftrivial_auto_var_init: {
3160
8
      A->claim();
3161
8
      StringRef Val = A->getValue();
3162
8
      if (Val == "uninitialized" || 
Val == "zero"7
||
Val == "pattern"3
)
3163
8
        TrivialAutoVarInit = Val;
3164
0
      else
3165
0
        D.Diag(diag::err_drv_unsupported_option_argument)
3166
0
            << A->getOption().getName() << Val;
3167
8
      break;
3168
0
    }
3169
752k
    }
3170
752k
  }
3171
3172
42.1k
  if (TrivialAutoVarInit.empty())
3173
42.1k
    switch (DefaultTrivialAutoVarInit) {
3174
42.1k
    case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3175
42.1k
      break;
3176
0
    case LangOptions::TrivialAutoVarInitKind::Pattern:
3177
0
      TrivialAutoVarInit = "pattern";
3178
0
      break;
3179
0
    case LangOptions::TrivialAutoVarInitKind::Zero:
3180
0
      TrivialAutoVarInit = "zero";
3181
0
      break;
3182
42.1k
    }
3183
3184
42.1k
  if (!TrivialAutoVarInit.empty()) {
3185
8
    if (TrivialAutoVarInit == "zero" && 
!Args.hasArg(options::OPT_enable_trivial_var_init_zero)4
)
3186
1
      D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
3187
8
    CmdArgs.push_back(
3188
8
        Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3189
8
  }
3190
3191
42.1k
  if (Arg *A =
3192
5
          Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3193
5
    if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3194
4
        StringRef(
3195
4
            Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3196
4
            "uninitialized")
3197
1
      D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3198
5
    A->claim();
3199
5
    StringRef Val = A->getValue();
3200
5
    if (std::stoi(Val.str()) <= 0)
3201
3
      D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3202
5
    CmdArgs.push_back(
3203
5
        Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3204
5
  }
3205
42.1k
}
3206
3207
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3208
42.1k
                                types::ID InputType) {
3209
  // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3210
  // for denormal flushing handling based on the target.
3211
42.1k
  const unsigned ForwardedArguments[] = {
3212
42.1k
      options::OPT_cl_opt_disable,
3213
42.1k
      options::OPT_cl_strict_aliasing,
3214
42.1k
      options::OPT_cl_single_precision_constant,
3215
42.1k
      options::OPT_cl_finite_math_only,
3216
42.1k
      options::OPT_cl_kernel_arg_info,
3217
42.1k
      options::OPT_cl_unsafe_math_optimizations,
3218
42.1k
      options::OPT_cl_fast_relaxed_math,
3219
42.1k
      options::OPT_cl_mad_enable,
3220
42.1k
      options::OPT_cl_no_signed_zeros,
3221
42.1k
      options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3222
42.1k
      options::OPT_cl_uniform_work_group_size
3223
42.1k
  };
3224
3225
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3226
15
    std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3227
15
    CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3228
15
  }
3229
3230
42.1k
  for (const auto &Arg : ForwardedArguments)
3231
463k
    if (const auto *A = Args.getLastArg(Arg))
3232
16
      CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3233
3234
  // Only add the default headers if we are compiling OpenCL sources.
3235
42.1k
  if ((types::isOpenCL(InputType) || 
Args.hasArg(options::OPT_cl_std_EQ)41.8k
) &&
3236
264
      !Args.hasArg(options::OPT_cl_no_stdinc)) {
3237
261
    CmdArgs.push_back("-finclude-default-header");
3238
261
    CmdArgs.push_back("-fdeclare-opencl-builtins");
3239
261
  }
3240
42.1k
}
3241
3242
static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3243
42.1k
                                        ArgStringList &CmdArgs) {
3244
42.1k
  bool ARCMTEnabled = false;
3245
42.1k
  if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3246
40.7k
    if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3247
40.7k
                                       options::OPT_ccc_arcmt_modify,
3248
1
                                       options::OPT_ccc_arcmt_migrate)) {
3249
1
      ARCMTEnabled = true;
3250
1
      switch (A->getOption().getID()) {
3251
0
      default: llvm_unreachable("missed a case");
3252
0
      case options::OPT_ccc_arcmt_check:
3253
0
        CmdArgs.push_back("-arcmt-action=check");
3254
0
        break;
3255
0
      case options::OPT_ccc_arcmt_modify:
3256
0
        CmdArgs.push_back("-arcmt-action=modify");
3257
0
        break;
3258
1
      case options::OPT_ccc_arcmt_migrate:
3259
1
        CmdArgs.push_back("-arcmt-action=migrate");
3260
1
        CmdArgs.push_back("-mt-migrate-directory");
3261
1
        CmdArgs.push_back(A->getValue());
3262
3263
1
        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3264
1
        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3265
1
        break;
3266
1
      }
3267
1
    }
3268
1.38k
  } else {
3269
1.38k
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3270
1.38k
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3271
1.38k
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3272
1.38k
  }
3273
3274
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3275
0
    if (ARCMTEnabled)
3276
0
      D.Diag(diag::err_drv_argument_not_allowed_with)
3277
0
          << A->getAsString(Args) << "-ccc-arcmt-migrate";
3278
3279
0
    CmdArgs.push_back("-mt-migrate-directory");
3280
0
    CmdArgs.push_back(A->getValue());
3281
3282
0
    if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3283
0
                     options::OPT_objcmt_migrate_subscripting,
3284
0
                     options::OPT_objcmt_migrate_property)) {
3285
      // None specified, means enable them all.
3286
0
      CmdArgs.push_back("-objcmt-migrate-literals");
3287
0
      CmdArgs.push_back("-objcmt-migrate-subscripting");
3288
0
      CmdArgs.push_back("-objcmt-migrate-property");
3289
0
    } else {
3290
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3291
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3292
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3293
0
    }
3294
42.1k
  } else {
3295
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3296
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3297
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3298
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3299
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3300
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3301
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3302
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3303
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3304
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3305
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3306
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3307
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3308
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3309
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3310
42.1k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3311
42.1k
  }
3312
42.1k
}
3313
3314
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3315
42.1k
                                 const ArgList &Args, ArgStringList &CmdArgs) {
3316
  // -fbuiltin is default unless -mkernel is used.
3317
42.1k
  bool UseBuiltins =
3318
42.1k
      Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3319
42.1k
                   !Args.hasArg(options::OPT_mkernel));
3320
42.1k
  if (!UseBuiltins)
3321
3.04k
    CmdArgs.push_back("-fno-builtin");
3322
3323
  // -ffreestanding implies -fno-builtin.
3324
42.1k
  if (Args.hasArg(options::OPT_ffreestanding))
3325
55
    UseBuiltins = false;
3326
3327
  // Process the -fno-builtin-* options.
3328
752k
  for (const auto &Arg : Args) {
3329
752k
    const Option &O = Arg->getOption();
3330
752k
    if (!O.matches(options::OPT_fno_builtin_))
3331
752k
      continue;
3332
3333
22
    Arg->claim();
3334
3335
    // If -fno-builtin is specified, then there's no need to pass the option to
3336
    // the frontend.
3337
22
    if (!UseBuiltins)
3338
3
      continue;
3339
3340
19
    StringRef FuncName = Arg->getValue();
3341
19
    CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3342
19
  }
3343
3344
  // le32-specific flags:
3345
  //  -fno-math-builtin: clang should not convert math builtins to intrinsics
3346
  //                     by default.
3347
42.1k
  if (TC.getArch() == llvm::Triple::le32)
3348
5
    CmdArgs.push_back("-fno-math-builtin");
3349
42.1k
}
3350
3351
3.26k
bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3352
3.26k
  if (llvm::sys::path::cache_directory(Result)) {
3353
3.26k
    llvm::sys::path::append(Result, "clang");
3354
3.26k
    llvm::sys::path::append(Result, "ModuleCache");
3355
3.26k
    return true;
3356
3.26k
  }
3357
0
  return false;
3358
3.26k
}
3359
3360
static void RenderModulesOptions(Compilation &C, const Driver &D,
3361
                                 const ArgList &Args, const InputInfo &Input,
3362
                                 const InputInfo &Output,
3363
42.1k
                                 ArgStringList &CmdArgs, bool &HaveModules) {
3364
  // -fmodules enables the use of precompiled modules (off by default).
3365
  // Users can pass -fno-cxx-modules to turn off modules support for
3366
  // C++/Objective-C++ programs.
3367
42.1k
  bool HaveClangModules = false;
3368
42.1k
  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3369
2.28k
    bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3370
2.28k
                                     options::OPT_fno_cxx_modules, true);
3371
2.28k
    if (AllowedInCXX || 
!types::isCXX(Input.getType())1
) {
3372
2.28k
      CmdArgs.push_back("-fmodules");
3373
2.28k
      HaveClangModules = true;
3374
2.28k
    }
3375
2.28k
  }
3376
3377
42.1k
  HaveModules |= HaveClangModules;
3378
42.1k
  if (Args.hasArg(options::OPT_fmodules_ts)) {
3379
8
    CmdArgs.push_back("-fmodules-ts");
3380
8
    HaveModules = true;
3381
8
  }
3382
3383
  // -fmodule-maps enables implicit reading of module map files. By default,
3384
  // this is enabled if we are using Clang's flavor of precompiled modules.
3385
42.1k
  if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3386
42.1k
                   options::OPT_fno_implicit_module_maps, HaveClangModules))
3387
2.28k
    CmdArgs.push_back("-fimplicit-module-maps");
3388
3389
  // -fmodules-decluse checks that modules used are declared so (off by default)
3390
42.1k
  if (Args.hasFlag(options::OPT_fmodules_decluse,
3391
42.1k
                   options::OPT_fno_modules_decluse, false))
3392
1
    CmdArgs.push_back("-fmodules-decluse");
3393
3394
  // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3395
  // all #included headers are part of modules.
3396
42.1k
  if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3397
42.1k
                   options::OPT_fno_modules_strict_decluse, false))
3398
0
    CmdArgs.push_back("-fmodules-strict-decluse");
3399
3400
  // -fno-implicit-modules turns off implicitly compiling modules on demand.
3401
42.1k
  bool ImplicitModules = false;
3402
42.1k
  if (!Args.hasFlag(options::OPT_fimplicit_modules,
3403
39.8k
                    options::OPT_fno_implicit_modules, HaveClangModules)) {
3404
39.8k
    if (HaveModules)
3405
2.83k
      CmdArgs.push_back("-fno-implicit-modules");
3406
2.28k
  } else if (HaveModules) {
3407
2.28k
    ImplicitModules = true;
3408
    // -fmodule-cache-path specifies where our implicitly-built module files
3409
    // should be written.
3410
2.28k
    SmallString<128> Path;
3411
2.28k
    if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3412
2.27k
      Path = A->getValue();
3413
3414
2.28k
    bool HasPath = true;
3415
2.28k
    if (C.isForDiagnostics()) {
3416
      // When generating crash reports, we want to emit the modules along with
3417
      // the reproduction sources, so we ignore any provided module path.
3418
14
      Path = Output.getFilename();
3419
14
      llvm::sys::path::replace_extension(Path, ".cache");
3420
14
      llvm::sys::path::append(Path, "modules");
3421
2.27k
    } else if (Path.empty()) {
3422
      // No module path was provided: use the default.
3423
17
      HasPath = Driver::getDefaultModuleCachePath(Path);
3424
17
    }
3425
3426
    // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3427
    // That being said, that failure is unlikely and not caching is harmless.
3428
2.28k
    if (HasPath) {
3429
2.28k
      const char Arg[] = "-fmodules-cache-path=";
3430
2.28k
      Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3431
2.28k
      CmdArgs.push_back(Args.MakeArgString(Path));
3432
2.28k
    }
3433
2.28k
  }
3434
3435
42.1k
  if (HaveModules) {
3436
    // -fprebuilt-module-path specifies where to load the prebuilt module files.
3437
2
    for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3438
2
      CmdArgs.push_back(Args.MakeArgString(
3439
2
          std::string("-fprebuilt-module-path=") + A->getValue()));
3440
2
      A->claim();
3441
2
    }
3442
5.12k
    if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3443
5.12k
                     options::OPT_fno_prebuilt_implicit_modules, false))
3444
0
      CmdArgs.push_back("-fprebuilt-implicit-modules");
3445
5.12k
    if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3446
5.12k
                     options::OPT_fno_modules_validate_input_files_content,
3447
5.12k
                     false))
3448
1
      CmdArgs.push_back("-fvalidate-ast-input-files-content");
3449
5.12k
  }
3450
3451
  // -fmodule-name specifies the module that is currently being built (or
3452
  // used for header checking by -fmodule-maps).
3453
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3454
3455
  // -fmodule-map-file can be used to specify files containing module
3456
  // definitions.
3457
42.1k
  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3458
3459
  // -fbuiltin-module-map can be used to load the clang
3460
  // builtin headers modulemap file.
3461
42.1k
  if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3462
1
    SmallString<128> BuiltinModuleMap(D.ResourceDir);
3463
1
    llvm::sys::path::append(BuiltinModuleMap, "include");
3464
1
    llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3465
1
    if (llvm::sys::fs::exists(BuiltinModuleMap))
3466
1
      CmdArgs.push_back(
3467
1
          Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3468
1
  }
3469
3470
  // The -fmodule-file=<name>=<file> form specifies the mapping of module
3471
  // names to precompiled module files (the module is loaded only if used).
3472
  // The -fmodule-file=<file> form can be used to unconditionally load
3473
  // precompiled module files (whether used or not).
3474
42.1k
  if (HaveModules)
3475
5.12k
    Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3476
37.0k
  else
3477
37.0k
    Args.ClaimAllArgs(options::OPT_fmodule_file);
3478
3479
  // When building modules and generating crashdumps, we need to dump a module
3480
  // dependency VFS alongside the output.
3481
42.1k
  if (HaveClangModules && 
C.isForDiagnostics()2.28k
) {
3482
14
    SmallString<128> VFSDir(Output.getFilename());
3483
14
    llvm::sys::path::replace_extension(VFSDir, ".cache");
3484
    // Add the cache directory as a temp so the crash diagnostics pick it up.
3485
14
    C.addTempFile(Args.MakeArgString(VFSDir));
3486
3487
14
    llvm::sys::path::append(VFSDir, "vfs");
3488
14
    CmdArgs.push_back("-module-dependency-dir");
3489
14
    CmdArgs.push_back(Args.MakeArgString(VFSDir));
3490
14
  }
3491
3492
42.1k
  if (HaveClangModules)
3493
2.28k
    Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3494
3495
  // Pass through all -fmodules-ignore-macro arguments.
3496
42.1k
  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3497
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3498
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3499
3500
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3501
3502
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3503
4
    if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3504
1
      D.Diag(diag::err_drv_argument_not_allowed_with)
3505
1
          << A->getAsString(Args) << "-fbuild-session-timestamp";
3506
3507
4
    llvm::sys::fs::file_status Status;
3508
4
    if (llvm::sys::fs::status(A->getValue(), Status))
3509
1
      D.Diag(diag::err_drv_no_such_file) << A->getValue();
3510
4
    CmdArgs.push_back(
3511
4
        Args.MakeArgString("-fbuild-session-timestamp=" +
3512
4
                           Twine((uint64_t)Status.getLastModificationTime()
3513
4
                                     .time_since_epoch()
3514
4
                                     .count())));
3515
4
  }
3516
3517
42.1k
  if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3518
3
    if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3519
3
                         options::OPT_fbuild_session_file))
3520
1
      D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3521
3522
3
    Args.AddLastArg(CmdArgs,
3523
3
                    options::OPT_fmodules_validate_once_per_build_session);
3524
3
  }
3525
3526
42.1k
  if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3527
42.1k
                   options::OPT_fno_modules_validate_system_headers,
3528
42.1k
                   ImplicitModules))
3529
2.28k
    CmdArgs.push_back("-fmodules-validate-system-headers");
3530
3531
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3532
42.1k
}
3533
3534
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3535
42.1k
                                   ArgStringList &CmdArgs) {
3536
  // -fsigned-char is default.
3537
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3538
42.1k
                                     options::OPT_fno_signed_char,
3539
42.1k
                                     options::OPT_funsigned_char,
3540
12
                                     options::OPT_fno_unsigned_char)) {
3541
12
    if (A->getOption().matches(options::OPT_funsigned_char) ||
3542
7
        A->getOption().matches(options::OPT_fno_signed_char)) {
3543
7
      CmdArgs.push_back("-fno-signed-char");
3544
7
    }
3545
42.1k
  } else if (!isSignedCharDefault(T)) {
3546
3.76k
    CmdArgs.push_back("-fno-signed-char");
3547
3.76k
  }
3548
3549
  // The default depends on the language standard.
3550
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3551
3552
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3553
26
                                     options::OPT_fno_short_wchar)) {
3554
26
    if (A->getOption().matches(options::OPT_fshort_wchar)) {
3555
4
      CmdArgs.push_back("-fwchar-type=short");
3556
4
      CmdArgs.push_back("-fno-signed-wchar");
3557
22
    } else {
3558
22
      bool IsARM = T.isARM() || 
T.isThumb()9
||
T.isAArch64()9
;
3559
22
      CmdArgs.push_back("-fwchar-type=int");
3560
22
      if (T.isOSzOS() ||
3561
22
          (IsARM && 
!(20
T.isOSWindows()20
||
T.isOSNetBSD()18
||
T.isOSOpenBSD()12
)))
3562
6
        CmdArgs.push_back("-fno-signed-wchar");
3563
16
      else
3564
16
        CmdArgs.push_back("-fsigned-wchar");
3565
22
    }
3566
26
  }
3567
42.1k
}
3568
3569
static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3570
                              const llvm::Triple &T, const ArgList &Args,
3571
                              ObjCRuntime &Runtime, bool InferCovariantReturns,
3572
42.1k
                              const InputInfo &Input, ArgStringList &CmdArgs) {
3573
42.1k
  const llvm::Triple::ArchType Arch = TC.getArch();
3574
3575
  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3576
  // is the default. Except for deployment target of 10.5, next runtime is
3577
  // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3578
42.1k
  if (Runtime.isNonFragile()) {
3579
17.0k
    if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3580
17.0k
                      options::OPT_fno_objc_legacy_dispatch,
3581
28
                      Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3582
28
      if (TC.UseObjCMixedDispatch())
3583
2
        CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3584
26
      else
3585
26
        CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3586
28
    }
3587
17.0k
  }
3588
3589
  // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3590
  // to do Array/Dictionary subscripting by default.
3591
42.1k
  if (Arch == llvm::Triple::x86 && 
T.isMacOSX()10.2k
&&
3592
106
      Runtime.getKind() == ObjCRuntime::FragileMacOSX && 
Runtime.isNeXTFamily()92
)
3593
92
    CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3594
3595
  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3596
  // NOTE: This logic is duplicated in ToolChains.cpp.
3597
42.1k
  if (isObjCAutoRefCount(Args)) {
3598
1.37k
    TC.CheckObjCARC();
3599
3600
1.37k
    CmdArgs.push_back("-fobjc-arc");
3601
3602
    // FIXME: It seems like this entire block, and several around it should be
3603
    // wrapped in isObjC, but for now we just use it here as this is where it
3604
    // was being used previously.
3605
1.37k
    if (types::isCXX(Input.getType()) && 
types::isObjC(Input.getType())1.34k
) {
3606
1.34k
      if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3607
1.31k
        CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3608
38
      else
3609
38
        CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3610
1.34k
    }
3611
3612
    // Allow the user to enable full exceptions code emission.
3613
    // We default off for Objective-C, on for Objective-C++.
3614
1.37k
    if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3615
1.37k
                     options::OPT_fno_objc_arc_exceptions,
3616
1.37k
                     /*Default=*/types::isCXX(Input.getType())))
3617
1.34k
      CmdArgs.push_back("-fobjc-arc-exceptions");
3618
1.37k
  }
3619
3620
  // Silence warning for full exception code emission options when explicitly
3621
  // set to use no ARC.
3622
42.1k
  if (Args.hasArg(options::OPT_fno_objc_arc)) {
3623
5
    Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3624
5
    Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3625
5
  }
3626
3627
  // Allow the user to control whether messages can be converted to runtime
3628
  // functions.
3629
42.1k
  if (types::isObjC(Input.getType())) {
3630
3.21k
    auto *Arg = Args.getLastArg(
3631
3.21k
        options::OPT_fobjc_convert_messages_to_runtime_calls,
3632
3.21k
        options::OPT_fno_objc_convert_messages_to_runtime_calls);
3633
3.21k
    if (Arg &&
3634
2
        Arg->getOption().matches(
3635
2
            options::OPT_fno_objc_convert_messages_to_runtime_calls))
3636
1
      CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3637
3.21k
  }
3638
3639
  // -fobjc-infer-related-result-type is the default, except in the Objective-C
3640
  // rewriter.
3641
42.1k
  if (InferCovariantReturns)
3642
8
    CmdArgs.push_back("-fno-objc-infer-related-result-type");
3643
3644
  // Pass down -fobjc-weak or -fno-objc-weak if present.
3645
42.1k
  if (types::isObjC(Input.getType())) {
3646
3.21k
    auto WeakArg =
3647
3.21k
        Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3648
3.21k
    if (!WeakArg) {
3649
      // nothing to do
3650
12
    } else if (!Runtime.allowsWeak()) {
3651
4
      if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3652
4
        D.Diag(diag::err_objc_weak_unsupported);
3653
8
    } else {
3654
8
      WeakArg->render(Args, CmdArgs);
3655
8
    }
3656
3.21k
  }
3657
42.1k
}
3658
3659
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3660
42.1k
                                     ArgStringList &CmdArgs) {
3661
42.1k
  bool CaretDefault = true;
3662
42.1k
  bool ColumnDefault = true;
3663
3664
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3665
42.1k
                                     options::OPT__SLASH_diagnostics_column,
3666
5
                                     options::OPT__SLASH_diagnostics_caret)) {
3667
5
    switch (A->getOption().getID()) {
3668
2
    case options::OPT__SLASH_diagnostics_caret:
3669
2
      CaretDefault = true;
3670
2
      ColumnDefault = true;
3671
2
      break;
3672
1
    case options::OPT__SLASH_diagnostics_column:
3673
1
      CaretDefault = false;
3674
1
      ColumnDefault = true;
3675
1
      break;
3676
2
    case options::OPT__SLASH_diagnostics_classic:
3677
2
      CaretDefault = false;
3678
2
      ColumnDefault = false;
3679
2
      break;
3680
5
    }
3681
5
  }
3682
3683
  // -fcaret-diagnostics is default.
3684
42.1k
  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3685
42.1k
                    options::OPT_fno_caret_diagnostics, CaretDefault))
3686
3
    CmdArgs.push_back("-fno-caret-diagnostics");
3687
3688
  // -fdiagnostics-fixit-info is default, only pass non-default.
3689
42.1k
  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3690
42.1k
                    options::OPT_fno_diagnostics_fixit_info))
3691
0
    CmdArgs.push_back("-fno-diagnostics-fixit-info");
3692
3693
  // Enable -fdiagnostics-show-option by default.
3694
42.1k
  if (!Args.hasFlag(options::OPT_fdiagnostics_show_option,
3695
42.1k
                    options::OPT_fno_diagnostics_show_option, true))
3696
1
    CmdArgs.push_back("-fno-diagnostics-show-option");
3697
3698
42.1k
  if (const Arg *A =
3699
0
          Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3700
0
    CmdArgs.push_back("-fdiagnostics-show-category");
3701
0
    CmdArgs.push_back(A->getValue());
3702
0
  }
3703
3704
42.1k
  if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3705
42.1k
                   options::OPT_fno_diagnostics_show_hotness, false))
3706
4
    CmdArgs.push_back("-fdiagnostics-show-hotness");
3707
3708
42.1k
  if (const Arg *A =
3709
6
          Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3710
6
    std::string Opt =
3711
6
        std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3712
6
    CmdArgs.push_back(Args.MakeArgString(Opt));
3713
6
  }
3714
3715
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3716
16
    CmdArgs.push_back("-fdiagnostics-format");
3717
16
    CmdArgs.push_back(A->getValue());
3718
16
  }
3719
3720
42.1k
  if (const Arg *A = Args.getLastArg(
3721
42.1k
          options::OPT_fdiagnostics_show_note_include_stack,
3722
0
          options::OPT_fno_diagnostics_show_note_include_stack)) {
3723
0
    const Option &O = A->getOption();
3724
0
    if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3725
0
      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3726
0
    else
3727
0
      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3728
0
  }
3729
3730
  // Color diagnostics are parsed by the driver directly from argv and later
3731
  // re-parsed to construct this job; claim any possible color diagnostic here
3732
  // to avoid warn_drv_unused_argument and diagnose bad
3733
  // OPT_fdiagnostics_color_EQ values.
3734
752k
  for (const Arg *A : Args) {
3735
752k
    const Option &O = A->getOption();
3736
752k
    if (!O.matches(options::OPT_fcolor_diagnostics) &&
3737
752k
        !O.matches(options::OPT_fdiagnostics_color) &&
3738
752k
        !O.matches(options::OPT_fno_color_diagnostics) &&
3739
752k
        !O.matches(options::OPT_fno_diagnostics_color) &&
3740
752k
        !O.matches(options::OPT_fdiagnostics_color_EQ))
3741
752k
      continue;
3742
3743
30
    if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3744
6
      StringRef Value(A->getValue());
3745
6
      if (Value != "always" && 
Value != "never"4
&&
Value != "auto"3
)
3746
1
        D.Diag(diag::err_drv_clang_unsupported)
3747
1
            << ("-fdiagnostics-color=" + Value).str();
3748
6
    }
3749
30
    A->claim();
3750
30
  }
3751
3752
42.1k
  if (D.getDiags().getDiagnosticOptions().ShowColors)
3753
9
    CmdArgs.push_back("-fcolor-diagnostics");
3754
3755
42.1k
  if (Args.hasArg(options::OPT_fansi_escape_codes))
3756
1
    CmdArgs.push_back("-fansi-escape-codes");
3757
3758
42.1k
  if (!Args.hasFlag(options::OPT_fshow_source_location,
3759
42.1k
                    options::OPT_fno_show_source_location))
3760
1
    CmdArgs.push_back("-fno-show-source-location");
3761
3762
42.1k
  if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3763
0
    CmdArgs.push_back("-fdiagnostics-absolute-paths");
3764
3765
42.1k
  if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3766
42.1k
                    ColumnDefault))
3767
4
    CmdArgs.push_back("-fno-show-column");
3768
3769
42.1k
  if (!Args.hasFlag(options::OPT_fspell_checking,
3770
42.1k
                    options::OPT_fno_spell_checking))
3771
997
    CmdArgs.push_back("-fno-spell-checking");
3772
42.1k
}
3773
3774
enum class DwarfFissionKind { None, Split, Single };
3775
3776
static DwarfFissionKind getDebugFissionKind(const Driver &D,
3777
4.38k
                                            const ArgList &Args, Arg *&Arg) {
3778
4.38k
  Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
3779
4.38k
                        options::OPT_gno_split_dwarf);
3780
4.38k
  if (!Arg || 
Arg->getOption().matches(options::OPT_gno_split_dwarf)51
)
3781
4.33k
    return DwarfFissionKind::None;
3782
3783
49
  if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3784
38
    return DwarfFissionKind::Split;
3785
3786
11
  StringRef Value = Arg->getValue();
3787
11
  if (Value == "split")
3788
5
    return DwarfFissionKind::Split;
3789
6
  if (Value == "single")
3790
6
    return DwarfFissionKind::Single;
3791
3792
0
  D.Diag(diag::err_drv_unsupported_option_argument)
3793
0
      << Arg->getOption().getName() << Arg->getValue();
3794
0
  return DwarfFissionKind::None;
3795
6
}
3796
3797
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
3798
                              const ArgList &Args, ArgStringList &CmdArgs,
3799
42.5k
                              unsigned DwarfVersion) {
3800
42.5k
  auto *DwarfFormatArg =
3801
42.5k
      Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
3802
42.5k
  if (!DwarfFormatArg)
3803
42.5k
    return;
3804
3805
16
  if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
3806
14
    if (DwarfVersion < 3)
3807
2
      D.Diag(diag::err_drv_argument_only_allowed_with)
3808
2
          << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
3809
12
    else if (!T.isArch64Bit())
3810
2
      D.Diag(diag::err_drv_argument_only_allowed_with)
3811
2
          << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
3812
10
    else if (!T.isOSBinFormatELF())
3813
2
      D.Diag(diag::err_drv_argument_only_allowed_with)
3814
2
          << DwarfFormatArg->getAsString(Args) << "ELF platforms";
3815
14
  }
3816
3817
16
  DwarfFormatArg->render(Args, CmdArgs);
3818
16
}
3819
3820
static void renderDebugOptions(const ToolChain &TC, const Driver &D,
3821
                               const llvm::Triple &T, const ArgList &Args,
3822
                               bool EmitCodeView, bool IRInput,
3823
                               ArgStringList &CmdArgs,
3824
                               codegenoptions::DebugInfoKind &DebugInfoKind,
3825
42.1k
                               DwarfFissionKind &DwarfFission) {
3826
  // These two forms of profiling info can't be used together.
3827
42.1k
  if (const Arg *A1 = Args.getLastArg(options::OPT_fpseudo_probe_for_profiling))
3828
2
    if (const Arg *A2 = Args.getLastArg(options::OPT_fdebug_info_for_profiling))
3829
1
      D.Diag(diag::err_drv_argument_not_allowed_with)
3830
1
          << A1->getAsString(Args) << A2->getAsString(Args);
3831
3832
42.1k
  if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3833
42.1k
                   options::OPT_fno_debug_info_for_profiling, false) &&
3834
2
      checkDebugInfoOption(
3835
2
          Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3836
2
    CmdArgs.push_back("-fdebug-info-for-profiling");
3837
3838
  // The 'g' groups options involve a somewhat intricate sequence of decisions
3839
  // about what to pass from the driver to the frontend, but by the time they
3840
  // reach cc1 they've been factored into three well-defined orthogonal choices:
3841
  //  * what level of debug info to generate
3842
  //  * what dwarf version to write
3843
  //  * what debugger tuning to use
3844
  // This avoids having to monkey around further in cc1 other than to disable
3845
  // codeview if not running in a Windows environment. Perhaps even that
3846
  // decision should be made in the driver as well though.
3847
42.1k
  llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3848
3849
42.1k
  bool SplitDWARFInlining =
3850
42.1k
      Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3851
42.1k
                   options::OPT_fno_split_dwarf_inlining, false);
3852
3853
  // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
3854
  // object file generation and no IR generation, -gN should not be needed. So
3855
  // allow -gsplit-dwarf with either -gN or IR input.
3856
42.1k
  if (IRInput || 
Args.hasArg(options::OPT_g_Group)41.8k
) {
3857
3.93k
    Arg *SplitDWARFArg;
3858
3.93k
    DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
3859
3.93k
    if (DwarfFission != DwarfFissionKind::None &&
3860
44
        !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3861
0
      DwarfFission = DwarfFissionKind::None;
3862
0
      SplitDWARFInlining = false;
3863
0
    }
3864
3.93k
  }
3865
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3866
3.71k
    DebugInfoKind = codegenoptions::LimitedDebugInfo;
3867
3868
    // If the last option explicitly specified a debug-info level, use it.
3869
3.71k
    if (checkDebugInfoOption(A, Args, D, TC) &&
3870
3.71k
        A->getOption().matches(options::OPT_gN_Group)) {
3871
913
      DebugInfoKind = DebugLevelToInfoKind(*A);
3872
      // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3873
      // complicated if you've disabled inline info in the skeleton CUs
3874
      // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3875
      // line-tables-only, so let those compose naturally in that case.
3876
913
      if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3877
876
          DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3878
865
          (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3879
30
           SplitDWARFInlining))
3880
49
        DwarfFission = DwarfFissionKind::None;
3881
913
    }
3882
3.71k
  }
3883
3884
  // If a debugger tuning argument appeared, remember it.
3885
42.1k
  if (const Arg *A =
3886
185
          Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3887
185
    if (checkDebugInfoOption(A, Args, D, TC)) {
3888
184
      if (A->getOption().matches(options::OPT_glldb))
3889
104
        DebuggerTuning = llvm::DebuggerKind::LLDB;
3890
80
      else if (A->getOption().matches(options::OPT_gsce))
3891
3
        DebuggerTuning = llvm::DebuggerKind::SCE;
3892
77
      else
3893
77
        DebuggerTuning = llvm::DebuggerKind::GDB;
3894
184
    }
3895
185
  }
3896
3897
  // If a -gdwarf argument appeared, remember it.
3898
42.1k
  const Arg *GDwarfN = getDwarfNArg(Args);
3899
42.1k
  bool EmitDwarf = false;
3900
42.1k
  if (GDwarfN) {
3901
46
    if (checkDebugInfoOption(GDwarfN, Args, D, TC))
3902
46
      EmitDwarf = true;
3903
0
    else
3904
0
      GDwarfN = nullptr;
3905
46
  }
3906
3907
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3908
11
    if (checkDebugInfoOption(A, Args, D, TC))
3909
11
      EmitCodeView = true;
3910
11
  }
3911
3912
  // If the user asked for debug info but did not explicitly specify -gcodeview
3913
  // or -gdwarf, ask the toolchain for the default format.
3914
42.1k
  if (!EmitCodeView && 
!EmitDwarf42.1k
&&
3915
42.0k
      DebugInfoKind != codegenoptions::NoDebugInfo) {
3916
3.62k
    switch (TC.getDefaultDebugFormat()) {
3917
4
    case codegenoptions::DIF_CodeView:
3918
4
      EmitCodeView = true;
3919
4
      break;
3920
3.61k
    case codegenoptions::DIF_DWARF:
3921
3.61k
      EmitDwarf = true;
3922
3.61k
      break;
3923
3.62k
    }
3924
3.62k
  }
3925
3926
42.1k
  unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
3927
42.1k
  unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
3928
                                      // be lower than what the user wanted.
3929
42.1k
  unsigned DefaultDWARFVersion = ParseDebugDefaultVersion(TC, Args);
3930
42.1k
  if (EmitDwarf) {
3931
    // Start with the platform default DWARF version
3932
3.66k
    RequestedDWARFVersion = TC.GetDefaultDwarfVersion();
3933
3.66k
    assert(RequestedDWARFVersion &&
3934
3.66k
           "toolchain default DWARF version must be nonzero");
3935
3936
    // If the user specified a default DWARF version, that takes precedence
3937
    // over the platform default.
3938
3.66k
    if (DefaultDWARFVersion)
3939
8
      RequestedDWARFVersion = DefaultDWARFVersion;
3940
3941
    // Override with a user-specified DWARF version
3942
3.66k
    if (GDwarfN)
3943
46
      if (auto ExplicitVersion = DwarfVersionNum(GDwarfN->getSpelling()))
3944
38
        RequestedDWARFVersion = ExplicitVersion;
3945
    // Clamp effective DWARF version to the max supported by the toolchain.
3946
3.66k
    EffectiveDWARFVersion =
3947
3.66k
        std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
3948
3.66k
  }
3949
3950
  // -gline-directives-only supported only for the DWARF debug info.
3951
42.1k
  if (RequestedDWARFVersion == 0 &&
3952
38.4k
      DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3953
0
    DebugInfoKind = codegenoptions::NoDebugInfo;
3954
3955
  // We ignore flag -gstrict-dwarf for now.
3956
  // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3957
42.1k
  Args.ClaimAllArgs(options::OPT_g_flags_Group);
3958
3959
  // Column info is included by default for everything except SCE and
3960
  // CodeView. Clang doesn't track end columns, just starting columns, which,
3961
  // in theory, is fine for CodeView (and PDB).  In practice, however, the
3962
  // Microsoft debuggers don't handle missing end columns well, so it's better
3963
  // not to include any column info.
3964
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3965
19
    (void)checkDebugInfoOption(A, Args, D, TC);
3966
42.1k
  if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3967
42.1k
                    !EmitCodeView && 
DebuggerTuning != llvm::DebuggerKind::SCE42.1k
))
3968
163
    CmdArgs.push_back("-gno-column-info");
3969
3970
  // FIXME: Move backend command line options to the module.
3971
  // If -gline-tables-only or -gline-directives-only is the last option it wins.
3972
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3973
823
    if (checkDebugInfoOption(A, Args, D, TC)) {
3974
823
      if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3975
822
          DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
3976
821
        DebugInfoKind = codegenoptions::LimitedDebugInfo;
3977
821
        CmdArgs.push_back("-dwarf-ext-refs");
3978
821
        CmdArgs.push_back("-fmodule-format=obj");
3979
821
      }
3980
823
    }
3981
3982
42.1k
  if (T.isOSBinFormatELF() && 
SplitDWARFInlining18.3k
)
3983
4
    CmdArgs.push_back("-fsplit-dwarf-inlining");
3984
3985
  // After we've dealt with all combinations of things that could
3986
  // make DebugInfoKind be other than None or DebugLineTablesOnly,
3987
  // figure out if we need to "upgrade" it to standalone debug info.
3988
  // We parse these two '-f' options whether or not they will be used,
3989
  // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3990
42.1k
  bool NeedFullDebug = Args.hasFlag(
3991
42.1k
      options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3992
42.1k
      DebuggerTuning == llvm::DebuggerKind::LLDB ||
3993
26.4k
          TC.GetDefaultStandaloneDebug());
3994
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3995
3.03k
    (void)checkDebugInfoOption(A, Args, D, TC);
3996
3997
42.1k
  if (DebugInfoKind == codegenoptions::LimitedDebugInfo) {
3998
3.64k
    if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
3999
3.64k
                     options::OPT_feliminate_unused_debug_types, false))
4000
1
      DebugInfoKind = codegenoptions::UnusedTypeInfo;
4001
3.64k
    else if (NeedFullDebug)
4002
3.39k
      DebugInfoKind = codegenoptions::FullDebugInfo;
4003
3.64k
  }
4004
4005
42.1k
  if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4006
6
                   false)) {
4007
    // Source embedding is a vendor extension to DWARF v5. By now we have
4008
    // checked if a DWARF version was stated explicitly, and have otherwise
4009
    // fallen back to the target default, so if this is still not at least 5
4010
    // we emit an error.
4011
6
    const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4012
6
    if (RequestedDWARFVersion < 5)
4013
1
      D.Diag(diag::err_drv_argument_only_allowed_with)
4014
1
          << A->getAsString(Args) << "-gdwarf-5";
4015
5
    else if (EffectiveDWARFVersion < 5)
4016
      // The toolchain has reduced allowed dwarf version, so we can't enable
4017
      // -gembed-source.
4018
2
      D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4019
2
          << A->getAsString(Args) << TC.getTripleString() << 5
4020
2
          << EffectiveDWARFVersion;
4021
3
    else if (checkDebugInfoOption(A, Args, D, TC))
4022
3
      CmdArgs.push_back("-gembed-source");
4023
6
  }
4024
4025
42.1k
  if (EmitCodeView) {
4026
27
    CmdArgs.push_back("-gcodeview");
4027
4028
    // Emit codeview type hashes if requested.
4029
27
    if (Args.hasFlag(options::OPT_gcodeview_ghash,
4030
2
                     options::OPT_gno_codeview_ghash, false)) {
4031
2
      CmdArgs.push_back("-gcodeview-ghash");
4032
2
    }
4033
27
  }
4034
4035
  // Omit inline line tables if requested.
4036
42.1k
  if (Args.hasFlag(options::OPT_gno_inline_line_tables,
4037
1
                   options::OPT_ginline_line_tables, false)) {
4038
1
    CmdArgs.push_back("-gno-inline-line-tables");
4039
1
  }
4040
4041
  // When emitting remarks, we need at least debug lines in the output.
4042
42.1k
  if (willEmitRemarks(Args) &&
4043
38
      DebugInfoKind <= codegenoptions::DebugDirectivesOnly)
4044
37
    DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4045
4046
  // Adjust the debug info kind for the given toolchain.
4047
42.1k
  TC.adjustDebugInfoKind(DebugInfoKind, Args);
4048
4049
42.1k
  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4050
42.1k
                          DebuggerTuning);
4051
4052
  // -fdebug-macro turns on macro debug info generation.
4053
42.1k
  if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4054
42.1k
                   false))
4055
1
    if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4056
1
                             D, TC))
4057
1
      CmdArgs.push_back("-debug-info-macro");
4058
4059
  // -ggnu-pubnames turns on gnu style pubnames in the backend.
4060
42.1k
  const auto *PubnamesArg =
4061
42.1k
      Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4062
42.1k
                      options::OPT_gpubnames, options::OPT_gno_pubnames);
4063
42.1k
  if (DwarfFission != DwarfFissionKind::None ||
4064
42.1k
      (PubnamesArg && 
checkDebugInfoOption(PubnamesArg, Args, D, TC)7
))
4065
45
    if (!PubnamesArg ||
4066
10
        (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4067
7
         !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4068
37
      CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4069
2
                                           options::OPT_gpubnames)
4070
1
                            ? "-gpubnames"
4071
36
                            : "-ggnu-pubnames");
4072
4073
42.1k
  if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
4074
1
                   options::OPT_fno_debug_ranges_base_address, false)) {
4075
1
    CmdArgs.push_back("-fdebug-ranges-base-address");
4076
1
  }
4077
4078
  // -gdwarf-aranges turns on the emission of the aranges section in the
4079
  // backend.
4080
  // Always enabled for SCE tuning.
4081
42.1k
  bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4082
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4083
1
    NeedAranges = checkDebugInfoOption(A, Args, D, TC) || 
NeedAranges0
;
4084
42.1k
  if (NeedAranges) {
4085
138
    CmdArgs.push_back("-mllvm");
4086
138
    CmdArgs.push_back("-generate-arange-section");
4087
138
  }
4088
4089
42.1k
  if (Args.hasFlag(options::OPT_fforce_dwarf_frame,
4090
42.1k
                   options::OPT_fno_force_dwarf_frame, false))
4091
1
    CmdArgs.push_back("-fforce-dwarf-frame");
4092
4093
42.1k
  if (Args.hasFlag(options::OPT_fdebug_types_section,
4094
4
                   options::OPT_fno_debug_types_section, false)) {
4095
4
    if (!(T.isOSBinFormatELF() || 
T.isOSBinFormatWasm()2
)) {
4096
1
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4097
1
          << Args.getLastArg(options::OPT_fdebug_types_section)
4098
1
                 ->getAsString(Args)
4099
1
          << T.getTriple();
4100
3
    } else if (checkDebugInfoOption(
4101
3
                   Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4102
3
                   TC)) {
4103
3
      CmdArgs.push_back("-mllvm");
4104
3
      CmdArgs.push_back("-generate-type-units");
4105
3
    }
4106
4
  }
4107
4108
  // Decide how to render forward declarations of template instantiations.
4109
  // SCE wants full descriptions, others just get them in the name.
4110
42.1k
  if (DebuggerTuning == llvm::DebuggerKind::SCE)
4111
137
    CmdArgs.push_back("-debug-forward-template-params");
4112
4113
  // Do we need to explicitly import anonymous namespaces into the parent
4114
  // scope?
4115
42.1k
  if (DebuggerTuning == llvm::DebuggerKind::SCE)
4116
137
    CmdArgs.push_back("-dwarf-explicit-import");
4117
4118
42.1k
  renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4119
42.1k
  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4120
42.1k
}
4121
4122
void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4123
                         const InputInfo &Output, const InputInfoList &Inputs,
4124
42.1k
                         const ArgList &Args, const char *LinkingOutput) const {
4125
42.1k
  const auto &TC = getToolChain();
4126
42.1k
  const llvm::Triple &RawTriple = TC.getTriple();
4127
42.1k
  const llvm::Triple &Triple = TC.getEffectiveTriple();
4128
42.1k
  const std::string &TripleStr = Triple.getTriple();
4129
4130
42.1k
  bool KernelOrKext =
4131
42.1k
      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4132
42.1k
  const Driver &D = TC.getDriver();
4133
42.1k
  ArgStringList CmdArgs;
4134
4135
  // Check number of inputs for sanity. We need at least one input.
4136
42.1k
  assert(Inputs.size() >= 1 && "Must have at least one input.");
4137
  // CUDA/HIP compilation may have multiple inputs (source file + results of
4138
  // device-side compilations). OpenMP device jobs also take the host IR as a
4139
  // second input. Module precompilation accepts a list of header files to
4140
  // include as part of the module. All other jobs are expected to have exactly
4141
  // one input.
4142
0
  bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4143
42.1k
  bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4144
42.1k
  bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4145
42.1k
  bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
4146
4147
  // A header module compilation doesn't have a main input file, so invent a
4148
  // fake one as a placeholder.
4149
42.1k
  const char *ModuleName = [&]{
4150
42.1k
    auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
4151
42.1k
    return ModuleNameArg ? 
ModuleNameArg->getValue()5
:
""42.1k
;
4152
42.1k
  }();
4153
42.1k
  InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
4154
4155
42.1k
  const InputInfo &Input =
4156
42.1k
      IsHeaderModulePrecompile ? 
HeaderModuleInput3
:
Inputs[0]42.1k
;
4157
4158
42.1k
  InputInfoList ModuleHeaderInputs;
4159
42.1k
  const InputInfo *CudaDeviceInput = nullptr;
4160
42.1k
  const InputInfo *OpenMPDeviceInput = nullptr;
4161
42.5k
  for (const InputInfo &I : Inputs) {
4162
42.5k
    if (&I == &Input) {
4163
      // This is the primary input.
4164
368
    } else if (IsHeaderModulePrecompile &&
4165
7
               types::getPrecompiledType(I.getType()) == types::TY_PCH) {
4166
7
      types::ID Expected = HeaderModuleInput.getType();
4167
7
      if (I.getType() != Expected) {
4168
0
        D.Diag(diag::err_drv_module_header_wrong_kind)
4169
0
            << I.getFilename() << types::getTypeName(I.getType())
4170
0
            << types::getTypeName(Expected);
4171
0
      }
4172
7
      ModuleHeaderInputs.push_back(I);
4173
361
    } else if ((IsCuda || 
IsHIP182
) &&
!CudaDeviceInput283
) {
4174
283
      CudaDeviceInput = &I;
4175
78
    } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4176
78
      OpenMPDeviceInput = &I;
4177
0
    } else {
4178
0
      llvm_unreachable("unexpectedly given multiple inputs");
4179
0
    }
4180
42.5k
  }
4181
4182
42.1k
  const llvm::Triple *AuxTriple =
4183
42.1k
      (IsCuda || 
IsHIP41.6k
) ?
TC.getAuxTriple()913
:
nullptr41.2k
;
4184
42.1k
  bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4185
42.1k
  bool IsIAMCU = RawTriple.isOSIAMCU();
4186
4187
  // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
4188
  // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4189
  // Windows), we need to pass Windows-specific flags to cc1.
4190
42.1k
  if (IsCuda || 
IsHIP41.6k
)
4191
913
    IsWindowsMSVC |= AuxTriple && 
AuxTriple->isWindowsMSVCEnvironment()528
;
4192
4193
  // C++ is not supported for IAMCU.
4194
42.1k
  if (IsIAMCU && 
types::isCXX(Input.getType())9
)
4195
1
    D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4196
4197
  // Invoke ourselves in -cc1 mode.
4198
  //
4199
  // FIXME: Implement custom jobs for internal actions.
4200
42.1k
  CmdArgs.push_back("-cc1");
4201
4202
  // Add the "effective" target triple.
4203
42.1k
  CmdArgs.push_back("-triple");
4204
42.1k
  CmdArgs.push_back(Args.MakeArgString(TripleStr));
4205
4206
42.1k
  if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4207
4
    DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4208
4
    Args.ClaimAllArgs(options::OPT_MJ);
4209
42.1k
  } else if (const Arg *GenCDBFragment =
4210
4
                 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4211
4
    DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4212
4
                                         TripleStr, Output, Input, Args);
4213
4
    Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4214
4
  }
4215
4216
42.1k
  if (IsCuda || 
IsHIP41.6k
) {
4217
    // We have to pass the triple of the host if compiling for a CUDA/HIP device
4218
    // and vice-versa.
4219
913
    std::string NormalizedTriple;
4220
913
    if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4221
637
        JA.isDeviceOffloading(Action::OFK_HIP))
4222
528
      NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4223
528
                             ->getTriple()
4224
528
                             .normalize();
4225
385
    else {
4226
      // Host-side compilation.
4227
385
      NormalizedTriple =
4228
385
          (IsCuda ? 
C.getSingleOffloadToolChain<Action::OFK_Cuda>()227
4229
158
                  : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4230
385
              ->getTriple()
4231
385
              .normalize();
4232
385
      if (IsCuda) {
4233
        // We need to figure out which CUDA version we're compiling for, as that
4234
        // determines how we load and launch GPU kernels.
4235
227
        auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4236
227
            C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4237
227
        assert(CTC && "Expected valid CUDA Toolchain.");
4238
227
        if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4239
40
          CmdArgs.push_back(Args.MakeArgString(
4240
40
              Twine("-target-sdk-version=") +
4241
40
              CudaVersionToString(CTC->CudaInstallation.version())));
4242
227
      }
4243
385
    }
4244
0
    CmdArgs.push_back("-aux-triple");
4245
913
    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4246
913
  }
4247
4248
42.1k
  if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4249
10
    CmdArgs.push_back("-fsycl");
4250
10
    CmdArgs.push_back("-fsycl-is-device");
4251
4252
10
    if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4253
5
      A->render(Args, CmdArgs);
4254
5
    } else {
4255
      // Ensure the default version in SYCL mode is 1.2.1 (aka 2017)
4256
5
      CmdArgs.push_back("-sycl-std=2017");
4257
5
    }
4258
10
  }
4259
4260
42.1k
  if (IsOpenMPDevice) {
4261
    // We have to pass the triple of the host if compiling for an OpenMP device.
4262
113
    std::string NormalizedTriple =
4263
113
        C.getSingleOffloadToolChain<Action::OFK_Host>()
4264
113
            ->getTriple()
4265
113
            .normalize();
4266
113
    CmdArgs.push_back("-aux-triple");
4267
113
    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4268
113
  }
4269
4270
42.1k
  if (Triple.isOSWindows() && 
(7.91k
Triple.getArch() == llvm::Triple::arm7.91k
||
4271
7.91k
                               Triple.getArch() == llvm::Triple::thumb)) {
4272
61
    unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 
40
: 6;
4273
61
    unsigned Version = 0;
4274
61
    bool Failure =
4275
61
        Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4276
61
    if (Failure || Version < 7)
4277
2
      D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4278
2
                                                << TripleStr;
4279
61
  }
4280
4281
  // Push all default warning arguments that are specific to
4282
  // the given target.  These come before user provided warning options
4283
  // are provided.
4284
42.1k
  TC.addClangWarningOptions(CmdArgs);
4285
4286
  // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4287
42.1k
  if (Triple.isSPIR())
4288
1
    CmdArgs.push_back("-Wspir-compat");
4289
4290
  // Select the appropriate action.
4291
42.1k
  RewriteKind rewriteKind = RK_None;
4292
4293
  // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4294
  // it claims when not running an assembler. Otherwise, clang would emit
4295
  // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4296
  // flags while debugging something. That'd be somewhat inconvenient, and it's
4297
  // also inconsistent with most other flags -- we don't warn on
4298
  // -ffunction-sections not being used in -E mode either for example, even
4299
  // though it's not really used either.
4300
42.1k
  if (!isa<AssembleJobAction>(JA)) {
4301
    // The args claimed here should match the args used in
4302
    // CollectArgsForIntegratedAssembler().
4303
32.2k
    if (TC.useIntegratedAs()) {
4304
31.2k
      Args.ClaimAllArgs(options::OPT_mrelax_all);
4305
31.2k
      Args.ClaimAllArgs(options::OPT_mno_relax_all);
4306
31.2k
      Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4307
31.2k
      Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4308
31.2k
      switch (C.getDefaultToolChain().getArch()) {
4309
502
      case llvm::Triple::arm:
4310
503
      case llvm::Triple::armeb:
4311
506
      case llvm::Triple::thumb:
4312
507
      case llvm::Triple::thumbeb:
4313
507
        Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4314
507
        break;
4315
30.7k
      default:
4316
30.7k
        break;
4317
31.2k
      }
4318
31.2k
    }
4319
32.2k
    Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4320
32.2k
    Args.ClaimAllArgs(options::OPT_Xassembler);
4321
32.2k
  }
4322
4323
42.1k
  if (isa<AnalyzeJobAction>(JA)) {
4324
41
    assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4325
0
    CmdArgs.push_back("-analyze");
4326
42.1k
  } else if (isa<MigrateJobAction>(JA)) {
4327
0
    CmdArgs.push_back("-migrate");
4328
42.1k
  } else if (isa<PreprocessJobAction>(JA)) {
4329
1.45k
    if (Output.getType() == types::TY_Dependencies)
4330
74
      CmdArgs.push_back("-Eonly");
4331
1.38k
    else {
4332
1.38k
      CmdArgs.push_back("-E");
4333
1.38k
      if (Args.hasArg(options::OPT_rewrite_objc) &&
4334
5
          !Args.hasArg(options::OPT_g_Group))
4335
4
        CmdArgs.push_back("-P");
4336
1.38k
    }
4337
40.6k
  } else if (isa<AssembleJobAction>(JA)) {
4338
9.93k
    CmdArgs.push_back("-emit-obj");
4339
4340
9.93k
    CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4341
4342
    // Also ignore explicit -force_cpusubtype_ALL option.
4343
9.93k
    (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4344
30.7k
  } else if (isa<PrecompileJobAction>(JA)) {
4345
78
    if (JA.getType() == types::TY_Nothing)
4346
31
      CmdArgs.push_back("-fsyntax-only");
4347
47
    else if (JA.getType() == types::TY_ModuleFile)
4348
8
      CmdArgs.push_back(IsHeaderModulePrecompile
4349
2
                            ? "-emit-header-module"
4350
6
                            : "-emit-module-interface");
4351
39
    else
4352
39
      CmdArgs.push_back("-emit-pch");
4353
30.6k
  } else if (isa<VerifyPCHJobAction>(JA)) {
4354
2
    CmdArgs.push_back("-verify-pch");
4355
30.6k
  } else {
4356
30.6k
    assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4357
30.6k
           "Invalid action for clang tool.");
4358
30.6k
    if (JA.getType() == types::TY_Nothing) {
4359
27.9k
      CmdArgs.push_back("-fsyntax-only");
4360
2.71k
    } else if (JA.getType() == types::TY_LLVM_IR ||
4361
2.19k
               JA.getType() == types::TY_LTO_IR) {
4362
594
      CmdArgs.push_back("-emit-llvm");
4363
2.11k
    } else if (JA.getType() == types::TY_LLVM_BC ||
4364
1.81k
               JA.getType() == types::TY_LTO_BC) {
4365
458
      CmdArgs.push_back("-emit-llvm-bc");
4366
1.66k
    } else if (JA.getType() == types::TY_IFS ||
4367
1.66k
               JA.getType() == types::TY_IFS_CPP) {
4368
26
      StringRef ArgStr =
4369
26
          Args.hasArg(options::OPT_interface_stub_version_EQ)
4370
7
              ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4371
19
              : "experimental-ifs-v2";
4372
26
      CmdArgs.push_back("-emit-interface-stubs");
4373
26
      CmdArgs.push_back(
4374
26
          Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4375
1.63k
    } else if (JA.getType() == types::TY_PP_Asm) {
4376
1.61k
      CmdArgs.push_back("-S");
4377
17
    } else if (JA.getType() == types::TY_AST) {
4378
9
      CmdArgs.push_back("-emit-pch");
4379
8
    } else if (JA.getType() == types::TY_ModuleFile) {
4380
0
      CmdArgs.push_back("-module-file-info");
4381
8
    } else if (JA.getType() == types::TY_RewrittenObjC) {
4382
5
      CmdArgs.push_back("-rewrite-objc");
4383
5
      rewriteKind = RK_NonFragile;
4384
3
    } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4385
3
      CmdArgs.push_back("-rewrite-objc");
4386
3
      rewriteKind = RK_Fragile;
4387
0
    } else {
4388
0
      assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4389
0
    }
4390
4391
    // Preserve use-list order by default when emitting bitcode, so that
4392
    // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4393
    // same result as running passes here.  For LTO, we don't need to preserve
4394
    // the use-list order, since serialization to bitcode is part of the flow.
4395
30.6k
    if (JA.getType() == types::TY_LLVM_BC)
4396
305
      CmdArgs.push_back("-emit-llvm-uselists");
4397
4398
    // Device-side jobs do not support LTO.
4399
30.6k
    bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4400
414
                                   JA.isDeviceOffloading(Action::OFK_Host));
4401
4402
30.6k
    if (D.isUsingLTO() && 
!isDeviceOffloadAction247
) {
4403
239
      Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
4404
239
      CmdArgs.push_back("-flto-unit");
4405
239
    }
4406
30.6k
  }
4407
4408
42.1k
  if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4409
28
    if (!types::isLLVMIR(Input.getType()))
4410
1
      D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4411
28
    Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4412
28
  }
4413
4414
42.1k
  if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4415
1
    Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4416
4417
42.1k
  if (Args.getLastArg(options::OPT_save_temps_EQ))
4418
371
    Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4419
4420
42.1k
  auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4421
42.1k
                                     options::OPT_fmemory_profile_EQ,
4422
42.1k
                                     options::OPT_fno_memory_profile);
4423
42.1k
  if (MemProfArg &&
4424
6
      !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4425
4
    MemProfArg->render(Args, CmdArgs);
4426
4427
  // Embed-bitcode option.
4428
  // Only white-listed flags below are allowed to be embedded.
4429
42.1k
  if (C.getDriver().embedBitcodeInObject() && 
!C.getDriver().isUsingLTO()32
&&
4430
27
      (isa<BackendJobAction>(JA) || 
isa<AssembleJobAction>(JA)26
)) {
4431
    // Add flags implied by -fembed-bitcode.
4432
12
    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4433
    // Disable all llvm IR level optimizations.
4434
12
    CmdArgs.push_back("-disable-llvm-passes");
4435
4436
    // Render target options.
4437
12
    TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4438
4439
    // reject options that shouldn't be supported in bitcode
4440
    // also reject kernel/kext
4441
12
    static const constexpr unsigned kBitcodeOptionBlacklist[] = {
4442
12
        options::OPT_mkernel,
4443
12
        options::OPT_fapple_kext,
4444
12
        options::OPT_ffunction_sections,
4445
12
        options::OPT_fno_function_sections,
4446
12
        options::OPT_fdata_sections,
4447
12
        options::OPT_fno_data_sections,
4448
12
        options::OPT_fbasic_block_sections_EQ,
4449
12
        options::OPT_funique_internal_linkage_names,
4450
12
        options::OPT_fno_unique_internal_linkage_names,
4451
12
        options::OPT_funique_section_names,
4452
12
        options::OPT_fno_unique_section_names,
4453
12
        options::OPT_funique_basic_block_section_names,
4454
12
        options::OPT_fno_unique_basic_block_section_names,
4455
12
        options::OPT_mrestrict_it,
4456
12
        options::OPT_mno_restrict_it,
4457
12
        options::OPT_mstackrealign,
4458
12
        options::OPT_mno_stackrealign,
4459
12
        options::OPT_mstack_alignment,
4460
12
        options::OPT_mcmodel_EQ,
4461
12
        options::OPT_mlong_calls,
4462
12
        options::OPT_mno_long_calls,
4463
12
        options::OPT_ggnu_pubnames,
4464
12
        options::OPT_gdwarf_aranges,
4465
12
        options::OPT_fdebug_types_section,
4466
12
        options::OPT_fno_debug_types_section,
4467
12
        options::OPT_fdwarf_directory_asm,
4468
12
        options::OPT_fno_dwarf_directory_asm,
4469
12
        options::OPT_mrelax_all,
4470
12
        options::OPT_mno_relax_all,
4471
12
        options::OPT_ftrap_function_EQ,
4472
12
        options::OPT_ffixed_r9,
4473
12
        options::OPT_mfix_cortex_a53_835769,
4474
12
        options::OPT_mno_fix_cortex_a53_835769,
4475
12
        options::OPT_ffixed_x18,
4476
12
        options::OPT_mglobal_merge,
4477
12
        options::OPT_mno_global_merge,
4478
12
        options::OPT_mred_zone,
4479
12
        options::OPT_mno_red_zone,
4480
12
        options::OPT_Wa_COMMA,
4481
12
        options::OPT_Xassembler,
4482
12
        options::OPT_mllvm,
4483
12
    };
4484
12
    for (const auto &A : Args)
4485
98
      if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
4486
98
          std::end(kBitcodeOptionBlacklist))
4487
0
        D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
4488
4489
    // Render the CodeGen options that need to be passed.
4490
12
    if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4491
12
                      options::OPT_fno_optimize_sibling_calls))
4492
0
      CmdArgs.push_back("-mdisable-tail-calls");
4493
4494
12
    RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
4495
12
                               CmdArgs, JA);
4496
4497
    // Render ABI arguments
4498
12
    switch (TC.getArch()) {
4499
8
    default: break;
4500
3
    case llvm::Triple::arm:
4501
3
    case llvm::Triple::armeb:
4502
3
    case llvm::Triple::thumbeb:
4503
3
      RenderARMABI(Triple, Args, CmdArgs);
4504
3
      break;
4505
1
    case llvm::Triple::aarch64:
4506
1
    case llvm::Triple::aarch64_32:
4507
1
    case llvm::Triple::aarch64_be:
4508
1
      RenderAArch64ABI(Triple, Args, CmdArgs);
4509
1
      break;
4510
12
    }
4511
4512
    // Optimization level for CodeGen.
4513
12
    if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4514
0
      if (A->getOption().matches(options::OPT_O4)) {
4515
0
        CmdArgs.push_back("-O3");
4516
0
        D.Diag(diag::warn_O4_is_O3);
4517
0
      } else {
4518
0
        A->render(Args, CmdArgs);
4519
0
      }
4520
0
    }
4521
4522
    // Input/Output file.
4523
12
    if (Output.getType() == types::TY_Dependencies) {
4524
      // Handled with other dependency code.
4525
12
    } else if (Output.isFilename()) {
4526
12
      CmdArgs.push_back("-o");
4527
12
      CmdArgs.push_back(Output.getFilename());
4528
0
    } else {
4529
0
      assert(Output.isNothing() && "Input output.");
4530
0
    }
4531
4532
12
    for (const auto &II : Inputs) {
4533
12
      addDashXForInput(Args, II, CmdArgs);
4534
12
      if (II.isFilename())
4535
12
        CmdArgs.push_back(II.getFilename());
4536
0
      else
4537
0
        II.getInputArg().renderAsInput(Args, CmdArgs);
4538
12
    }
4539
4540
12
    C.addCommand(std::make_unique<Command>(
4541
12
        JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
4542
12
        CmdArgs, Inputs, Output));
4543
12
    return;
4544
12
  }
4545
4546
42.1k
  if (C.getDriver().embedBitcodeMarkerOnly() && 
!C.getDriver().isUsingLTO()3
)
4547
3
    CmdArgs.push_back("-fembed-bitcode=marker");
4548
4549
  // We normally speed up the clang process a bit by skipping destructors at
4550
  // exit, but when we're generating diagnostics we can rely on some of the
4551
  // cleanup.
4552
42.1k
  if (!C.isForDiagnostics())
4553
42.1k
    CmdArgs.push_back("-disable-free");
4554
4555
#ifdef NDEBUG
4556
  const bool IsAssertBuild = false;
4557
#else
4558
42.1k
  const bool IsAssertBuild = true;
4559
42.1k
#endif
4560
4561
  // Disable the verification pass in -asserts builds.
4562
42.1k
  if (!IsAssertBuild)
4563
0
    CmdArgs.push_back("-disable-llvm-verifier");
4564
4565
  // Discard value names in assert builds unless otherwise specified.
4566
42.1k
  if (Args.hasFlag(options::OPT_fdiscard_value_names,
4567
2
                   options::OPT_fno_discard_value_names, !IsAssertBuild)) {
4568
2
    if (Args.hasArg(options::OPT_fdiscard_value_names) &&
4569
2
        (std::any_of(Inputs.begin(), Inputs.end(),
4570
2
                     [](const clang::driver::InputInfo &II) {
4571
2
                       return types::isLLVMIR(II.getType());
4572
1
                     }))) {
4573
1
      D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
4574
1
    }
4575
2
    CmdArgs.push_back("-discard-value-names");
4576
2
  }
4577
4578
  // Set the main file name, so that debug info works even with
4579
  // -save-temps.
4580
42.1k
  CmdArgs.push_back("-main-file-name");
4581
42.1k
  CmdArgs.push_back(getBaseInputName(Args, Input));
4582
4583
  // Some flags which affect the language (via preprocessor
4584
  // defines).
4585
42.1k
  if (Args.hasArg(options::OPT_static))
4586
110
    CmdArgs.push_back("-static-define");
4587
4588
42.1k
  if (Args.hasArg(options::OPT_municode))
4589
1
    CmdArgs.push_back("-DUNICODE");
4590
4591
42.1k
  if (isa<AnalyzeJobAction>(JA))
4592
41
    RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
4593
4594
42.1k
  if (isa<AnalyzeJobAction>(JA) ||
4595
42.0k
      (isa<PreprocessJobAction>(JA) && 
Args.hasArg(options::OPT__analyze)1.45k
))
4596
42
    CmdArgs.push_back("-setup-static-analyzer");
4597
4598
  // Enable compatilibily mode to avoid analyzer-config related errors.
4599
  // Since we can't access frontend flags through hasArg, let's manually iterate
4600
  // through them.
4601
42.1k
  bool FoundAnalyzerConfig = false;
4602
42.1k
  for (auto Arg : Args.filtered(options::OPT_Xclang))
4603
1.48k
    if (StringRef(Arg->getValue()) == "-analyzer-config") {
4604
8
      FoundAnalyzerConfig = true;
4605
8
      break;
4606
8
    }
4607
42.1k
  if (!FoundAnalyzerConfig)
4608
42.1k
    for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
4609
4
      if (StringRef(Arg->getValue()) == "-analyzer-config") {
4610
4
        FoundAnalyzerConfig = true;
4611
4
        break;
4612
4
      }
4613
42.1k
  if (FoundAnalyzerConfig)
4614
12
    CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
4615
4616
42.1k
  CheckCodeGenerationOptions(D, Args);
4617
4618
42.1k
  unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
4619
42.1k
  assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
4620
42.1k
  if (FunctionAlignment) {
4621
4
    CmdArgs.push_back("-function-alignment");
4622
4
    CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
4623
4
  }
4624
4625
42.1k
  llvm::Reloc::Model RelocationModel;
4626
42.1k
  unsigned PICLevel;
4627
42.1k
  bool IsPIE;
4628
42.1k
  std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
4629
4630
42.1k
  bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
4631
42.1k
                RelocationModel == llvm::Reloc::ROPI_RWPI;
4632
42.1k
  bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
4633
42.1k
                RelocationModel == llvm::Reloc::ROPI_RWPI;
4634
4635
42.1k
  if (Args.hasArg(options::OPT_mcmse) &&
4636
15
      !Args.hasArg(options::OPT_fallow_unsupported)) {
4637
12
    if (IsROPI)
4638
2
      D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
4639
12
    if (IsRWPI)
4640
2
      D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
4641
12
  }
4642
4643
42.1k
  if (IsROPI && 
types::isCXX(Input.getType())17
&&
4644
3
      !Args.hasArg(options::OPT_fallow_unsupported))
4645
2
    D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
4646
4647
42.1k
  const char *RMName = RelocationModelName(RelocationModel);
4648
42.1k
  if (
RMName42.1k
) {
4649
42.1k
    CmdArgs.push_back("-mrelocation-model");
4650
42.1k
    CmdArgs.push_back(RMName);
4651
42.1k
  }
4652
42.1k
  if (PICLevel > 0) {
4653
24.8k
    CmdArgs.push_back("-pic-level");
4654
24.8k
    CmdArgs.push_back(PICLevel == 1 ? 
"1"845
:
"2"24.0k
);
4655
24.8k
    if (IsPIE)
4656
430
      CmdArgs.push_back("-pic-is-pie");
4657
24.8k
  }
4658
4659
42.1k
  if (RelocationModel == llvm::Reloc::ROPI ||
4660
42.1k
      RelocationModel == llvm::Reloc::ROPI_RWPI)
4661
17
    CmdArgs.push_back("-fropi");
4662
42.1k
  if (RelocationModel == llvm::Reloc::RWPI ||
4663
42.1k
      RelocationModel == llvm::Reloc::ROPI_RWPI)
4664
12
    CmdArgs.push_back("-frwpi");
4665
4666
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4667
28
    CmdArgs.push_back("-meabi");
4668
28
    CmdArgs.push_back(A->getValue());
4669
28
  }
4670
4671
  // -fsemantic-interposition is forwarded to CC1: set the
4672
  // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
4673
  // make default visibility external linkage definitions dso_preemptable.
4674
  //
4675
  // -fno-semantic-interposition: if the target supports .Lfoo$local local
4676
  // aliases (make default visibility external linkage definitions dso_local).
4677
  // This is the CC1 default for ELF to match COFF/Mach-O.
4678
  //
4679
  // Otherwise use Clang's traditional behavior: like
4680
  // -fno-semantic-interposition but local aliases are not used. So references
4681
  // can be interposed if not optimized out.
4682
42.1k
  if (Triple.isOSBinFormatELF()) {
4683
18.3k
    Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
4684
18.3k
                             options::OPT_fno_semantic_interposition);
4685
18.3k
    if (RelocationModel != llvm::Reloc::Static && 
!IsPIE1.40k
) {
4686
      // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
4687
987
      bool SupportsLocalAlias = Triple.isX86();
4688
987
      if (!A)
4689
981
        CmdArgs.push_back("-fhalf-no-semantic-interposition");
4690
6
      else if (A->getOption().matches(options::OPT_fsemantic_interposition))
4691
2
        A->render(Args, CmdArgs);
4692
4
      else if (!SupportsLocalAlias)
4693
2
        CmdArgs.push_back("-fhalf-no-semantic-interposition");
4694
987
    }
4695
18.3k
  }
4696
4697
42.1k
  {
4698
42.1k
    std::string Model;
4699
42.1k
    if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
4700
6
      if (!TC.isThreadModelSupported(A->getValue()))
4701
2
        D.Diag(diag::err_drv_invalid_thread_model_for_target)
4702
2
            << A->getValue() << A->getAsString(Args);
4703
6
      Model = A->getValue();
4704
6
    } else
4705
42.1k
      Model = TC.getThreadModel();
4706
42.1k
    if (Model != "posix") {
4707
4
      CmdArgs.push_back("-mthread-model");
4708
4
      CmdArgs.push_back(Args.MakeArgString(Model));
4709
4
    }
4710
42.1k
  }
4711
4712
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4713
4714
42.1k
  if (Args.hasFlag(options::OPT_fmerge_all_constants,
4715
42.1k
                   options::OPT_fno_merge_all_constants, false))
4716
1
    CmdArgs.push_back("-fmerge-all-constants");
4717
4718
42.1k
  if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
4719
42.1k
                   options::OPT_fdelete_null_pointer_checks, false))
4720
3
    CmdArgs.push_back("-fno-delete-null-pointer-checks");
4721
4722
  // LLVM Code Generator Options.
4723
4724
6
  for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) {
4725
6
    StringRef Map = A->getValue();
4726
6
    if (!llvm::sys::fs::exists(Map)) {
4727
1
      D.Diag(diag::err_drv_no_such_file) << Map;
4728
5
    } else {
4729
5
      A->render(Args, CmdArgs);
4730
5
      A->claim();
4731
5
    }
4732
6
  }
4733
4734
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi,
4735
10
                               options::OPT_mabi_EQ_vec_default)) {
4736
10
    if (!Triple.isOSAIX())
4737
2
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4738
2
          << A->getSpelling() << RawTriple.str();
4739
10
    if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi)
4740
5
      CmdArgs.push_back("-mabi=vec-extabi");
4741
5
    else
4742
5
      D.Diag(diag::err_aix_default_altivec_abi);
4743
10
  }
4744
4745
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4746
2
    StringRef v = A->getValue();
4747
2
    CmdArgs.push_back("-mllvm");
4748
2
    CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4749
2
    A->claim();
4750
2
  }
4751
4752
42.1k
  if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4753
42.1k
                    true))
4754
0
    CmdArgs.push_back("-fno-jump-tables");
4755
4756
42.1k
  if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
4757
42.1k
                   options::OPT_fno_profile_sample_accurate, false))
4758
3
    CmdArgs.push_back("-fprofile-sample-accurate");
4759
4760
42.1k
  if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
4761
42.1k
                    options::OPT_fno_preserve_as_comments, true))
4762
1
    CmdArgs.push_back("-fno-preserve-as-comments");
4763
4764
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4765
0
    CmdArgs.push_back("-mregparm");
4766
0
    CmdArgs.push_back(A->getValue());
4767
0
  }
4768
4769
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
4770
4
                               options::OPT_msvr4_struct_return)) {
4771
4
    if (!TC.getTriple().isPPC32()) {
4772
4
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4773
4
          << A->getSpelling() << RawTriple.str();
4774
0
    } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
4775
0
      CmdArgs.push_back("-maix-struct-return");
4776
0
    } else {
4777
0
      assert(A->getOption().matches(options::OPT_msvr4_struct_return));
4778
0
      CmdArgs.push_back("-msvr4-struct-return");
4779
0
    }
4780
4
  }
4781
4782
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4783
0
                               options::OPT_freg_struct_return)) {
4784
0
    if (TC.getArch() != llvm::Triple::x86) {
4785
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4786
0
          << A->getSpelling() << RawTriple.str();
4787
0
    } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4788
0
      CmdArgs.push_back("-fpcc-struct-return");
4789
0
    } else {
4790
0
      assert(A->getOption().matches(options::OPT_freg_struct_return));
4791
0
      CmdArgs.push_back("-freg-struct-return");
4792
0
    }
4793
0
  }
4794
4795
42.1k
  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4796
0
    CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4797
4798
42.1k
  if (Args.hasArg(options::OPT_fenable_matrix)) {
4799
    // enable-matrix is needed by both the LangOpts and by LLVM.
4800
14
    CmdArgs.push_back("-fenable-matrix");
4801
14
    CmdArgs.push_back("-mllvm");
4802
14
    CmdArgs.push_back("-enable-matrix");
4803
14
  }
4804
4805
42.1k
  CodeGenOptions::FramePointerKind FPKeepKind =
4806
42.1k
                  getFramePointerKind(Args, RawTriple);
4807
42.1k
  const char *FPKeepKindStr = nullptr;
4808
42.1k
  switch (FPKeepKind) {
4809
8.06k
  case CodeGenOptions::FramePointerKind::None:
4810
8.06k
    FPKeepKindStr = "-mframe-pointer=none";
4811
8.06k
    break;
4812
1.35k
  case CodeGenOptions::FramePointerKind::NonLeaf:
4813
1.35k
    FPKeepKindStr = "-mframe-pointer=non-leaf";
4814
1.35k
    break;
4815
32.7k
  case CodeGenOptions::FramePointerKind::All:
4816
32.7k
    FPKeepKindStr = "-mframe-pointer=all";
4817
32.7k
    break;
4818
42.1k
  }
4819
42.1k
  assert(FPKeepKindStr && "unknown FramePointerKind");
4820
0
  CmdArgs.push_back(FPKeepKindStr);
4821
4822
42.1k
  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4823
42.1k
                    options::OPT_fno_zero_initialized_in_bss, true))
4824
1
    CmdArgs.push_back("-fno-zero-initialized-in-bss");
4825
4826
42.1k
  bool OFastEnabled = isOptimizationLevelFast(Args);
4827
  // If -Ofast is the optimization level, then -fstrict-aliasing should be
4828
  // enabled.  This alias option is being used to simplify the hasFlag logic.
4829
42.1k
  OptSpecifier StrictAliasingAliasOption =
4830
42.1k
      OFastEnabled ? 
options::OPT_Ofast25
:
options::OPT_fstrict_aliasing42.1k
;
4831
  // We turn strict aliasing off by default if we're in CL mode, since MSVC
4832
  // doesn't do any TBAA.
4833
42.1k
  bool TBAAOnByDefault = !D.IsCLMode();
4834
42.1k
  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4835
42.1k
                    options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4836
535
    CmdArgs.push_back("-relaxed-aliasing");
4837
42.1k
  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4838
42.1k
                    options::OPT_fno_struct_path_tbaa))
4839
0
    CmdArgs.push_back("-no-struct-path-tbaa");
4840
42.1k
  if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4841
42.1k
                   false))
4842
0
    CmdArgs.push_back("-fstrict-enums");
4843
42.1k
  if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4844
42.1k
                    true))
4845
1
    CmdArgs.push_back("-fno-strict-return");
4846
42.1k
  if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
4847
42.1k
                   options::OPT_fno_allow_editor_placeholders, false))
4848
1.00k
    CmdArgs.push_back("-fallow-editor-placeholders");
4849
42.1k
  if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4850
42.1k
                   options::OPT_fno_strict_vtable_pointers,
4851
42.1k
                   false))
4852
0
    CmdArgs.push_back("-fstrict-vtable-pointers");
4853
42.1k
  if (Args.hasFlag(options::OPT_fforce_emit_vtables,
4854
42.1k
                   options::OPT_fno_force_emit_vtables,
4855
42.1k
                   false))
4856
0
    CmdArgs.push_back("-fforce-emit-vtables");
4857
42.1k
  if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4858
42.1k
                    options::OPT_fno_optimize_sibling_calls))
4859
1
    CmdArgs.push_back("-mdisable-tail-calls");
4860
42.1k
  if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
4861
42.1k
                   options::OPT_fescaping_block_tail_calls, false))
4862
1
    CmdArgs.push_back("-fno-escaping-block-tail-calls");
4863
4864
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4865
42.1k
                  options::OPT_fno_fine_grained_bitfield_accesses);
4866
4867
  // Handle segmented stacks.
4868
42.1k
  if (Args.hasArg(options::OPT_fsplit_stack))
4869
5
    CmdArgs.push_back("-split-stacks");
4870
4871
42.1k
  RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
4872
4873
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
4874
2
    if (TC.getArch() == llvm::Triple::avr)
4875
1
      A->render(Args, CmdArgs);
4876
1
    else
4877
1
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4878
1
          << A->getAsString(Args) << TripleStr;
4879
2
  }
4880
4881
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
4882
15
    if (TC.getTriple().isX86())
4883
5
      A->render(Args, CmdArgs);
4884
10
    else if (TC.getTriple().isPPC() &&
4885
8
             (A->getOption().getID() != options::OPT_mlong_double_80))
4886
7
      A->render(Args, CmdArgs);
4887
3
    else
4888
3
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4889
3
          << A->getAsString(Args) << TripleStr;
4890
15
  }
4891
4892
  // Decide whether to use verbose asm. Verbose assembly is the default on
4893
  // toolchains which have the integrated assembler on by default.
4894
42.1k
  bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
4895
42.1k
  if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4896
42.1k
                    IsIntegratedAssemblerDefault))
4897
1.41k
    CmdArgs.push_back("-fno-verbose-asm");
4898
4899
  // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
4900
  // use that to indicate the MC default in the backend.
4901
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
4902
7
    StringRef V = A->getValue();
4903
7
    unsigned Num;
4904
7
    if (V == "none")
4905
1
      A->render(Args, CmdArgs);
4906
6
    else if (!V.consumeInteger(10, Num) && 
Num > 05
&&
4907
4
             (V.empty() || 
(3
V.consume_front(".")3
&&
4908
3
                            !V.consumeInteger(10, Num) && 
V.empty()1
)))
4909
2
      A->render(Args, CmdArgs);
4910
4
    else
4911
4
      D.Diag(diag::err_drv_invalid_argument_to_option)
4912
4
          << A->getValue() << A->getOption().getName();
4913
7
  }
4914
4915
42.1k
  if (!TC.useIntegratedAs())
4916
1.00k
    CmdArgs.push_back("-no-integrated-as");
4917
4918
42.1k
  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4919
0
    CmdArgs.push_back("-mdebug-pass");
4920
0
    CmdArgs.push_back("Structure");
4921
0
  }
4922
42.1k
  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4923
0
    CmdArgs.push_back("-mdebug-pass");
4924
0
    CmdArgs.push_back("Arguments");
4925
0
  }
4926
4927
  // Enable -mconstructor-aliases except on darwin, where we have to work around
4928
  // a linker bug (see <rdar://problem/7651567>), and CUDA/AMDGPU device code,
4929
  // where aliases aren't supported. Similarly, aliases aren't yet supported
4930
  // for AIX.
4931
42.1k
  if (!RawTriple.isOSDarwin() && 
!RawTriple.isNVPTX()26.4k
&&
4932
26.0k
      !RawTriple.isAMDGPU() && 
!RawTriple.isOSAIX()25.5k
)
4933
25.4k
    CmdArgs.push_back("-mconstructor-aliases");
4934
4935
  // Darwin's kernel doesn't support guard variables; just die if we
4936
  // try to use them.
4937
42.1k
  if (KernelOrKext && 
RawTriple.isOSDarwin()27
)
4938
24
    CmdArgs.push_back("-fforbid-guard-variables");
4939
4940
42.1k
  if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4941
103
                   Triple.isWindowsGNUEnvironment())) {
4942
103
    CmdArgs.push_back("-mms-bitfields");
4943
103
  }
4944
4945
  // Non-PIC code defaults to -fdirect-access-external-data while PIC code
4946
  // defaults to -fno-direct-access-external-data. Pass the option if different
4947
  // from the default.
4948
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
4949
42.1k
                               options::OPT_fno_direct_access_external_data))
4950
6
    if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
4951
6
        (PICLevel == 0))
4952
5
      A->render(Args, CmdArgs);
4953
4954
42.1k
  if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4955
0
    CmdArgs.push_back("-fno-plt");
4956
0
  }
4957
4958
  // -fhosted is default.
4959
  // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4960
  // use Freestanding.
4961
42.1k
  bool Freestanding =
4962
42.1k
      Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4963
42.0k
      KernelOrKext;
4964
42.1k
  if (Freestanding)
4965
82
    CmdArgs.push_back("-ffreestanding");
4966
4967
  // This is a coarse approximation of what llvm-gcc actually does, both
4968
  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4969
  // complicated ways.
4970
42.1k
  bool AsynchronousUnwindTables =
4971
42.1k
      Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4972
42.1k
                   options::OPT_fno_asynchronous_unwind_tables,
4973
42.1k
                   (TC.IsUnwindTablesDefault(Args) ||
4974
14.4k
                    TC.getSanitizerArgs().needsUnwindTables()) &&
4975
27.7k
                       !Freestanding);
4976
42.1k
  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4977
42.1k
                   AsynchronousUnwindTables))
4978
27.6k
    CmdArgs.push_back("-munwind-tables");
4979
4980
  // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
4981
  // `--gpu-use-aux-triple-only` is specified.
4982
42.1k
  if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
4983
42.1k
      ((IsCuda && 
JA.isDeviceOffloading(Action::OFK_Cuda)503
) ||
4984
41.8k
       (IsHIP && 
JA.isDeviceOffloading(Action::OFK_HIP)408
))) {
4985
527
    const ArgList &HostArgs =
4986
527
        C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
4987
527
    std::string HostCPU =
4988
527
        getCPUName(HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
4989
527
    if (!HostCPU.empty()) {
4990
527
      CmdArgs.push_back("-aux-target-cpu");
4991
527
      CmdArgs.push_back(Args.MakeArgString(HostCPU));
4992
527
    }
4993
527
    getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
4994
527
                      /*ForAS*/ false, /*IsAux*/ true);
4995
527
  }
4996
4997
42.1k
  TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4998
4999
  // FIXME: Handle -mtune=.
5000
42.1k
  (void)Args.hasArg(options::OPT_mtune_EQ);
5001
5002
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5003
21
    StringRef CM = A->getValue();
5004
21
    if (CM == "small" || 
CM == "kernel"16
||
CM == "medium"11
||
CM == "large"5
||
5005
2
        CM == "tiny")
5006
20
      A->render(Args, CmdArgs);
5007
1
    else
5008
1
      D.Diag(diag::err_drv_invalid_argument_to_option)
5009
1
          << CM << A->getOption().getName();
5010
21
  }
5011
5012
42.1k
  if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5013
7
    StringRef Value = A->getValue();
5014
7
    unsigned TLSSize = 0;
5015
7
    Value.getAsInteger(10, TLSSize);
5016
7
    if (!Triple.isAArch64() || 
!Triple.isOSBinFormatELF()6
)
5017
2
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5018
2
          << A->getOption().getName() << TripleStr;
5019
7
    if (TLSSize != 12 && 
TLSSize != 246
&&
TLSSize != 323
&&
TLSSize != 482
)
5020
1
      D.Diag(diag::err_drv_invalid_int_value)
5021
1
          << A->getOption().getName() << Value;
5022
7
    Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5023
7
  }
5024
5025
  // Add the target cpu
5026
42.1k
  std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
5027
42.1k
  if (!CPU.empty()) {
5028
41.5k
    CmdArgs.push_back("-target-cpu");
5029
41.5k
    CmdArgs.push_back(Args.MakeArgString(CPU));
5030
41.5k
  }
5031
5032
42.1k
  RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5033
5034
  // These two are potentially updated by AddClangCLArgs.
5035
42.1k
  codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5036
42.1k
  bool EmitCodeView = false;
5037
5038
  // Add clang-cl arguments.
5039
42.1k
  types::ID InputType = Input.getType();
5040
42.1k
  if (D.IsCLMode())
5041
535
    AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
5042
5043
42.1k
  DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5044
42.1k
  renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
5045
42.1k
                     types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
5046
42.1k
                     DwarfFission);
5047
5048
  // Add the split debug info name to the command lines here so we
5049
  // can propagate it to the backend.
5050
42.1k
  bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5051
38
                    (TC.getTriple().isOSBinFormatELF() ||
5052
3
                     TC.getTriple().isOSBinFormatWasm()) &&
5053
36
                    (isa<AssembleJobAction>(JA) || 
isa<CompileJobAction>(JA)9
||
5054
9
                     isa<BackendJobAction>(JA));
5055
42.1k
  if (SplitDWARF) {
5056
36
    const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5057
36
    CmdArgs.push_back("-split-dwarf-file");
5058
36
    CmdArgs.push_back(SplitDWARFOut);
5059
36
    if (DwarfFission == DwarfFissionKind::Split) {
5060
34
      CmdArgs.push_back("-split-dwarf-output");
5061
34
      CmdArgs.push_back(SplitDWARFOut);
5062
34
    }
5063
36
  }
5064
5065
  // Pass the linker version in use.
5066
42.1k
  if (Arg *
A42.1k
= Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5067
42.1k
    CmdArgs.push_back("-target-linker-version");
5068
42.1k
    CmdArgs.push_back(A->getValue());
5069
42.1k
  }
5070
5071
  // Explicitly error on some things we know we don't support and can't just
5072
  // ignore.
5073
42.1k
  if (
!Args.hasArg(options::OPT_fallow_unsupported)42.1k
) {
5074
42.1k
    Arg *Unsupported;
5075
42.1k
    if (types::isCXX(InputType) && 
RawTriple.isOSDarwin()28.1k
&&
5076
11.2k
        TC.getArch() == llvm::Triple::x86) {
5077
21
      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5078
21
          (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5079
1
        D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5080
1
            << Unsupported->getOption().getName();
5081
21
    }
5082
    // The faltivec option has been superseded by the maltivec option.
5083
42.1k
    if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5084
1
      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5085
1
          << Unsupported->getOption().getName()
5086
1
          << "please use -maltivec and include altivec.h explicitly";
5087
42.1k
    if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5088
1
      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5089
1
          << Unsupported->getOption().getName() << "please use -mno-altivec";
5090
42.1k
  }
5091
5092
42.1k
  Args.AddAllArgs(CmdArgs, options::OPT_v);
5093
5094
42.1k
  if (Args.getLastArg(options::OPT_H)) {
5095
1
    CmdArgs.push_back("-H");
5096
1
    CmdArgs.push_back("-sys-header-deps");
5097
1
  }
5098
5099
42.1k
  if (D.CCPrintHeaders && 
!D.CCGenDiagnostics11
) {
5100
6
    CmdArgs.push_back("-header-include-file");
5101
6
    CmdArgs.push_back(D.CCPrintHeadersFilename ? 
D.CCPrintHeadersFilename0
5102
6
                                               : "-");
5103
6
    CmdArgs.push_back("-sys-header-deps");
5104
6
  }
5105
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_P);
5106
42.1k
  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5107
5108
42.1k
  if (D.CCLogDiagnostics && 
!D.CCGenDiagnostics12
) {
5109
7
    CmdArgs.push_back("-diagnostic-log-file");
5110
7
    CmdArgs.push_back(D.CCLogDiagnosticsFilename ? 
D.CCLogDiagnosticsFilename2
5111
5
                                                 : "-");
5112
7
  }
5113
5114
  // Give the gen diagnostics more chances to succeed, by avoiding intentional
5115
  // crashes.
5116
42.1k
  if (D.CCGenDiagnostics)
5117
35
    CmdArgs.push_back("-disable-pragma-debug-crash");
5118
5119
42.1k
  bool UseSeparateSections = isUseSeparateSections(Triple);
5120