Coverage Report

Created: 2024-01-17 10:31

/src/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/CSKY.h"
14
#include "Arch/LoongArch.h"
15
#include "Arch/M68k.h"
16
#include "Arch/Mips.h"
17
#include "Arch/PPC.h"
18
#include "Arch/RISCV.h"
19
#include "Arch/Sparc.h"
20
#include "Arch/SystemZ.h"
21
#include "Arch/VE.h"
22
#include "Arch/X86.h"
23
#include "CommonArgs.h"
24
#include "Hexagon.h"
25
#include "MSP430.h"
26
#include "PS4CPU.h"
27
#include "clang/Basic/CLWarnings.h"
28
#include "clang/Basic/CharInfo.h"
29
#include "clang/Basic/CodeGenOptions.h"
30
#include "clang/Basic/HeaderInclude.h"
31
#include "clang/Basic/LangOptions.h"
32
#include "clang/Basic/MakeSupport.h"
33
#include "clang/Basic/ObjCRuntime.h"
34
#include "clang/Basic/Version.h"
35
#include "clang/Config/config.h"
36
#include "clang/Driver/Action.h"
37
#include "clang/Driver/Distro.h"
38
#include "clang/Driver/DriverDiagnostic.h"
39
#include "clang/Driver/InputInfo.h"
40
#include "clang/Driver/Options.h"
41
#include "clang/Driver/SanitizerArgs.h"
42
#include "clang/Driver/Types.h"
43
#include "clang/Driver/XRayArgs.h"
44
#include "llvm/ADT/SmallSet.h"
45
#include "llvm/ADT/StringExtras.h"
46
#include "llvm/BinaryFormat/Magic.h"
47
#include "llvm/Config/llvm-config.h"
48
#include "llvm/Object/ObjectFile.h"
49
#include "llvm/Option/ArgList.h"
50
#include "llvm/Support/CodeGen.h"
51
#include "llvm/Support/Compiler.h"
52
#include "llvm/Support/Compression.h"
53
#include "llvm/Support/Error.h"
54
#include "llvm/Support/FileSystem.h"
55
#include "llvm/Support/Path.h"
56
#include "llvm/Support/Process.h"
57
#include "llvm/Support/RISCVISAInfo.h"
58
#include "llvm/Support/YAMLParser.h"
59
#include "llvm/TargetParser/ARMTargetParserCommon.h"
60
#include "llvm/TargetParser/Host.h"
61
#include "llvm/TargetParser/LoongArchTargetParser.h"
62
#include "llvm/TargetParser/RISCVTargetParser.h"
63
#include <cctype>
64
65
using namespace clang::driver;
66
using namespace clang::driver::tools;
67
using namespace clang;
68
using namespace llvm::opt;
69
70
0
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
71
0
  if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
72
0
                               options::OPT_fminimize_whitespace,
73
0
                               options::OPT_fno_minimize_whitespace,
74
0
                               options::OPT_fkeep_system_includes,
75
0
                               options::OPT_fno_keep_system_includes)) {
76
0
    if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
77
0
        !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
78
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
79
0
          << A->getBaseArg().getAsString(Args)
80
0
          << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
81
0
    }
82
0
  }
83
0
}
84
85
0
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
86
  // In gcc, only ARM checks this, but it seems reasonable to check universally.
87
0
  if (Args.hasArg(options::OPT_static))
88
0
    if (const Arg *A =
89
0
            Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
90
0
      D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
91
0
                                                      << "-static";
92
0
}
93
94
// Add backslashes to escape spaces and other backslashes.
95
// This is used for the space-separated argument list specified with
96
// the -dwarf-debug-flags option.
97
static void EscapeSpacesAndBackslashes(const char *Arg,
98
0
                                       SmallVectorImpl<char> &Res) {
99
0
  for (; *Arg; ++Arg) {
100
0
    switch (*Arg) {
101
0
    default:
102
0
      break;
103
0
    case ' ':
104
0
    case '\\':
105
0
      Res.push_back('\\');
106
0
      break;
107
0
    }
108
0
    Res.push_back(*Arg);
109
0
  }
110
0
}
111
112
/// Apply \a Work on the current tool chain \a RegularToolChain and any other
113
/// offloading tool chain that is associated with the current action \a JA.
114
static void
115
forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
116
                           const ToolChain &RegularToolChain,
117
0
                           llvm::function_ref<void(const ToolChain &)> Work) {
118
  // Apply Work on the current/regular tool chain.
119
0
  Work(RegularToolChain);
120
121
  // Apply Work on all the offloading tool chains associated with the current
122
  // action.
123
0
  if (JA.isHostOffloading(Action::OFK_Cuda))
124
0
    Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
125
0
  else if (JA.isDeviceOffloading(Action::OFK_Cuda))
126
0
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
127
0
  else if (JA.isHostOffloading(Action::OFK_HIP))
128
0
    Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
129
0
  else if (JA.isDeviceOffloading(Action::OFK_HIP))
130
0
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
131
132
0
  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
133
0
    auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
134
0
    for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
135
0
      Work(*II->second);
136
0
  } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
137
0
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
138
139
  //
140
  // TODO: Add support for other offloading programming models here.
141
  //
142
0
}
143
144
/// This is a helper function for validating the optional refinement step
145
/// parameter in reciprocal argument strings. Return false if there is an error
146
/// parsing the refinement step. Otherwise, return true and set the Position
147
/// of the refinement step in the input string.
148
static bool getRefinementStep(StringRef In, const Driver &D,
149
0
                              const Arg &A, size_t &Position) {
150
0
  const char RefinementStepToken = ':';
151
0
  Position = In.find(RefinementStepToken);
152
0
  if (Position != StringRef::npos) {
153
0
    StringRef Option = A.getOption().getName();
154
0
    StringRef RefStep = In.substr(Position + 1);
155
    // Allow exactly one numeric character for the additional refinement
156
    // step parameter. This is reasonable for all currently-supported
157
    // operations and architectures because we would expect that a larger value
158
    // of refinement steps would cause the estimate "optimization" to
159
    // under-perform the native operation. Also, if the estimate does not
160
    // converge quickly, it probably will not ever converge, so further
161
    // refinement steps will not produce a better answer.
162
0
    if (RefStep.size() != 1) {
163
0
      D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
164
0
      return false;
165
0
    }
166
0
    char RefStepChar = RefStep[0];
167
0
    if (RefStepChar < '0' || RefStepChar > '9') {
168
0
      D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
169
0
      return false;
170
0
    }
171
0
  }
172
0
  return true;
173
0
}
174
175
/// The -mrecip flag requires processing of many optional parameters.
176
static void ParseMRecip(const Driver &D, const ArgList &Args,
177
0
                        ArgStringList &OutStrings) {
178
0
  StringRef DisabledPrefixIn = "!";
179
0
  StringRef DisabledPrefixOut = "!";
180
0
  StringRef EnabledPrefixOut = "";
181
0
  StringRef Out = "-mrecip=";
182
183
0
  Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
184
0
  if (!A)
185
0
    return;
186
187
0
  unsigned NumOptions = A->getNumValues();
188
0
  if (NumOptions == 0) {
189
    // No option is the same as "all".
190
0
    OutStrings.push_back(Args.MakeArgString(Out + "all"));
191
0
    return;
192
0
  }
193
194
  // Pass through "all", "none", or "default" with an optional refinement step.
195
0
  if (NumOptions == 1) {
196
0
    StringRef Val = A->getValue(0);
197
0
    size_t RefStepLoc;
198
0
    if (!getRefinementStep(Val, D, *A, RefStepLoc))
199
0
      return;
200
0
    StringRef ValBase = Val.slice(0, RefStepLoc);
201
0
    if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
202
0
      OutStrings.push_back(Args.MakeArgString(Out + Val));
203
0
      return;
204
0
    }
205
0
  }
206
207
  // Each reciprocal type may be enabled or disabled individually.
208
  // Check each input value for validity, concatenate them all back together,
209
  // and pass through.
210
211
0
  llvm::StringMap<bool> OptionStrings;
212
0
  OptionStrings.insert(std::make_pair("divd", false));
213
0
  OptionStrings.insert(std::make_pair("divf", false));
214
0
  OptionStrings.insert(std::make_pair("divh", false));
215
0
  OptionStrings.insert(std::make_pair("vec-divd", false));
216
0
  OptionStrings.insert(std::make_pair("vec-divf", false));
217
0
  OptionStrings.insert(std::make_pair("vec-divh", false));
218
0
  OptionStrings.insert(std::make_pair("sqrtd", false));
219
0
  OptionStrings.insert(std::make_pair("sqrtf", false));
220
0
  OptionStrings.insert(std::make_pair("sqrth", false));
221
0
  OptionStrings.insert(std::make_pair("vec-sqrtd", false));
222
0
  OptionStrings.insert(std::make_pair("vec-sqrtf", false));
223
0
  OptionStrings.insert(std::make_pair("vec-sqrth", false));
224
225
0
  for (unsigned i = 0; i != NumOptions; ++i) {
226
0
    StringRef Val = A->getValue(i);
227
228
0
    bool IsDisabled = Val.starts_with(DisabledPrefixIn);
229
    // Ignore the disablement token for string matching.
230
0
    if (IsDisabled)
231
0
      Val = Val.substr(1);
232
233
0
    size_t RefStep;
234
0
    if (!getRefinementStep(Val, D, *A, RefStep))
235
0
      return;
236
237
0
    StringRef ValBase = Val.slice(0, RefStep);
238
0
    llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
239
0
    if (OptionIter == OptionStrings.end()) {
240
      // Try again specifying float suffix.
241
0
      OptionIter = OptionStrings.find(ValBase.str() + 'f');
242
0
      if (OptionIter == OptionStrings.end()) {
243
        // The input name did not match any known option string.
244
0
        D.Diag(diag::err_drv_unknown_argument) << Val;
245
0
        return;
246
0
      }
247
      // The option was specified without a half or float or double suffix.
248
      // Make sure that the double or half entry was not already specified.
249
      // The float entry will be checked below.
250
0
      if (OptionStrings[ValBase.str() + 'd'] ||
251
0
          OptionStrings[ValBase.str() + 'h']) {
252
0
        D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
253
0
        return;
254
0
      }
255
0
    }
256
257
0
    if (OptionIter->second == true) {
258
      // Duplicate option specified.
259
0
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
260
0
      return;
261
0
    }
262
263
    // Mark the matched option as found. Do not allow duplicate specifiers.
264
0
    OptionIter->second = true;
265
266
    // If the precision was not specified, also mark the double and half entry
267
    // as found.
268
0
    if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
269
0
      OptionStrings[ValBase.str() + 'd'] = true;
270
0
      OptionStrings[ValBase.str() + 'h'] = true;
271
0
    }
272
273
    // Build the output string.
274
0
    StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
275
0
    Out = Args.MakeArgString(Out + Prefix + Val);
276
0
    if (i != NumOptions - 1)
277
0
      Out = Args.MakeArgString(Out + ",");
278
0
  }
279
280
0
  OutStrings.push_back(Args.MakeArgString(Out));
281
0
}
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
0
                                    ArgStringList &CmdArgs) {
287
0
  Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
288
0
  if (!A)
289
0
    return;
290
291
0
  StringRef Value = A->getValue();
292
0
  if (Value == "none") {
293
0
    CmdArgs.push_back("-mprefer-vector-width=none");
294
0
  } else {
295
0
    unsigned Width;
296
0
    if (Value.getAsInteger(10, Width)) {
297
0
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
298
0
      return;
299
0
    }
300
0
    CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
301
0
  }
302
0
}
303
304
static bool
305
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
306
0
                                          const llvm::Triple &Triple) {
307
  // We use the zero-cost exception tables for Objective-C if the non-fragile
308
  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
309
  // later.
310
0
  if (runtime.isNonFragile())
311
0
    return true;
312
313
0
  if (!Triple.isMacOSX())
314
0
    return false;
315
316
0
  return (!Triple.isMacOSXVersionLT(10, 5) &&
317
0
          (Triple.getArch() == llvm::Triple::x86_64 ||
318
0
           Triple.getArch() == llvm::Triple::arm));
319
0
}
320
321
/// Adds exception related arguments to the driver command arguments. There's a
322
/// main flag, -fexceptions and also language specific flags to enable/disable
323
/// C++ and Objective-C exceptions. This makes it possible to for example
324
/// disable C++ exceptions but enable Objective-C exceptions.
325
static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
326
                             const ToolChain &TC, bool KernelOrKext,
327
                             const ObjCRuntime &objcRuntime,
328
0
                             ArgStringList &CmdArgs) {
329
0
  const llvm::Triple &Triple = TC.getTriple();
330
331
0
  if (KernelOrKext) {
332
    // -mkernel and -fapple-kext imply no exceptions, so claim exception related
333
    // arguments now to avoid warnings about unused arguments.
334
0
    Args.ClaimAllArgs(options::OPT_fexceptions);
335
0
    Args.ClaimAllArgs(options::OPT_fno_exceptions);
336
0
    Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
337
0
    Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
338
0
    Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
339
0
    Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
340
0
    Args.ClaimAllArgs(options::OPT_fasync_exceptions);
341
0
    Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
342
0
    return false;
343
0
  }
344
345
  // See if the user explicitly enabled exceptions.
346
0
  bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
347
0
                         false);
348
349
0
  bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
350
0
                          options::OPT_fno_async_exceptions, false);
351
0
  if (EHa) {
352
0
    CmdArgs.push_back("-fasync-exceptions");
353
0
    EH = true;
354
0
  }
355
356
  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
357
  // is not necessarily sensible, but follows GCC.
358
0
  if (types::isObjC(InputType) &&
359
0
      Args.hasFlag(options::OPT_fobjc_exceptions,
360
0
                   options::OPT_fno_objc_exceptions, true)) {
361
0
    CmdArgs.push_back("-fobjc-exceptions");
362
363
0
    EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
364
0
  }
365
366
0
  if (types::isCXX(InputType)) {
367
    // Disable C++ EH by default on XCore and PS4/PS5.
368
0
    bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
369
0
                                !Triple.isPS() && !Triple.isDriverKit();
370
0
    Arg *ExceptionArg = Args.getLastArg(
371
0
        options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
372
0
        options::OPT_fexceptions, options::OPT_fno_exceptions);
373
0
    if (ExceptionArg)
374
0
      CXXExceptionsEnabled =
375
0
          ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
376
0
          ExceptionArg->getOption().matches(options::OPT_fexceptions);
377
378
0
    if (CXXExceptionsEnabled) {
379
0
      CmdArgs.push_back("-fcxx-exceptions");
380
381
0
      EH = true;
382
0
    }
383
0
  }
384
385
  // OPT_fignore_exceptions means exception could still be thrown,
386
  // but no clean up or catch would happen in current module.
387
  // So we do not set EH to false.
388
0
  Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
389
390
0
  Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
391
0
                    options::OPT_fno_assume_nothrow_exception_dtor);
392
393
0
  if (EH)
394
0
    CmdArgs.push_back("-fexceptions");
395
0
  return EH;
396
0
}
397
398
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
399
0
                                 const JobAction &JA) {
400
0
  bool Default = true;
401
0
  if (TC.getTriple().isOSDarwin()) {
402
    // The native darwin assembler doesn't support the linker_option directives,
403
    // so we disable them if we think the .s file will be passed to it.
404
0
    Default = TC.useIntegratedAs();
405
0
  }
406
  // The linker_option directives are intended for host compilation.
407
0
  if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
408
0
      JA.isDeviceOffloading(Action::OFK_HIP))
409
0
    Default = false;
410
0
  return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
411
0
                      Default);
412
0
}
413
414
/// Add a CC1 option to specify the debug compilation directory.
415
static const char *addDebugCompDirArg(const ArgList &Args,
416
                                      ArgStringList &CmdArgs,
417
0
                                      const llvm::vfs::FileSystem &VFS) {
418
0
  if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
419
0
                               options::OPT_fdebug_compilation_dir_EQ)) {
420
0
    if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
421
0
      CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
422
0
                                           A->getValue()));
423
0
    else
424
0
      A->render(Args, CmdArgs);
425
0
  } else if (llvm::ErrorOr<std::string> CWD =
426
0
                 VFS.getCurrentWorkingDirectory()) {
427
0
    CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
428
0
  }
429
0
  StringRef Path(CmdArgs.back());
430
0
  return Path.substr(Path.find('=') + 1).data();
431
0
}
432
433
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
434
                               const char *DebugCompilationDir,
435
0
                               const char *OutputFileName) {
436
  // No need to generate a value for -object-file-name if it was provided.
437
0
  for (auto *Arg : Args.filtered(options::OPT_Xclang))
438
0
    if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
439
0
      return;
440
441
0
  if (Args.hasArg(options::OPT_object_file_name_EQ))
442
0
    return;
443
444
0
  SmallString<128> ObjFileNameForDebug(OutputFileName);
445
0
  if (ObjFileNameForDebug != "-" &&
446
0
      !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
447
0
      (!DebugCompilationDir ||
448
0
       llvm::sys::path::is_absolute(DebugCompilationDir))) {
449
    // Make the path absolute in the debug infos like MSVC does.
450
0
    llvm::sys::fs::make_absolute(ObjFileNameForDebug);
451
0
  }
452
  // If the object file name is a relative path, then always use Windows
453
  // backslash style as -object-file-name is used for embedding object file path
454
  // in codeview and it can only be generated when targeting on Windows.
455
  // Otherwise, just use native absolute path.
456
0
  llvm::sys::path::Style Style =
457
0
      llvm::sys::path::is_absolute(ObjFileNameForDebug)
458
0
          ? llvm::sys::path::Style::native
459
0
          : llvm::sys::path::Style::windows_backslash;
460
0
  llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
461
0
                               Style);
462
0
  CmdArgs.push_back(
463
0
      Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
464
0
}
465
466
/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
467
static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
468
0
                                 const ArgList &Args, ArgStringList &CmdArgs) {
469
0
  auto AddOneArg = [&](StringRef Map, StringRef Name) {
470
0
    if (!Map.contains('='))
471
0
      D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
472
0
    else
473
0
      CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
474
0
  };
475
476
0
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
477
0
                                    options::OPT_fdebug_prefix_map_EQ)) {
478
0
    AddOneArg(A->getValue(), A->getOption().getName());
479
0
    A->claim();
480
0
  }
481
0
  std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
482
0
  if (GlobalRemapEntry.empty())
483
0
    return;
484
0
  AddOneArg(GlobalRemapEntry, "environment");
485
0
}
486
487
/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
488
static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
489
0
                                 ArgStringList &CmdArgs) {
490
0
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
491
0
                                    options::OPT_fmacro_prefix_map_EQ)) {
492
0
    StringRef Map = A->getValue();
493
0
    if (!Map.contains('='))
494
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
495
0
          << Map << A->getOption().getName();
496
0
    else
497
0
      CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
498
0
    A->claim();
499
0
  }
500
0
}
501
502
/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
503
static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
504
0
                                   ArgStringList &CmdArgs) {
505
0
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
506
0
                                    options::OPT_fcoverage_prefix_map_EQ)) {
507
0
    StringRef Map = A->getValue();
508
0
    if (!Map.contains('='))
509
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
510
0
          << Map << A->getOption().getName();
511
0
    else
512
0
      CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
513
0
    A->claim();
514
0
  }
515
0
}
516
517
/// Vectorize at all optimization levels greater than 1 except for -Oz.
518
/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
519
/// enabled.
520
0
static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
521
0
  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
522
0
    if (A->getOption().matches(options::OPT_O4) ||
523
0
        A->getOption().matches(options::OPT_Ofast))
524
0
      return true;
525
526
0
    if (A->getOption().matches(options::OPT_O0))
527
0
      return false;
528
529
0
    assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
530
531
    // Vectorize -Os.
532
0
    StringRef S(A->getValue());
533
0
    if (S == "s")
534
0
      return true;
535
536
    // Don't vectorize -Oz, unless it's the slp vectorizer.
537
0
    if (S == "z")
538
0
      return isSlpVec;
539
540
0
    unsigned OptLevel = 0;
541
0
    if (S.getAsInteger(10, OptLevel))
542
0
      return false;
543
544
0
    return OptLevel > 1;
545
0
  }
546
547
0
  return false;
548
0
}
549
550
/// Add -x lang to \p CmdArgs for \p Input.
551
static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
552
0
                             ArgStringList &CmdArgs) {
553
  // When using -verify-pch, we don't want to provide the type
554
  // 'precompiled-header' if it was inferred from the file extension
555
0
  if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
556
0
    return;
557
558
0
  CmdArgs.push_back("-x");
559
0
  if (Args.hasArg(options::OPT_rewrite_objc))
560
0
    CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
561
0
  else {
562
    // Map the driver type to the frontend type. This is mostly an identity
563
    // mapping, except that the distinction between module interface units
564
    // and other source files does not exist at the frontend layer.
565
0
    const char *ClangType;
566
0
    switch (Input.getType()) {
567
0
    case types::TY_CXXModule:
568
0
      ClangType = "c++";
569
0
      break;
570
0
    case types::TY_PP_CXXModule:
571
0
      ClangType = "c++-cpp-output";
572
0
      break;
573
0
    default:
574
0
      ClangType = types::getTypeName(Input.getType());
575
0
      break;
576
0
    }
577
0
    CmdArgs.push_back(ClangType);
578
0
  }
579
0
}
580
581
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
582
                                   const JobAction &JA, const InputInfo &Output,
583
                                   const ArgList &Args, SanitizerArgs &SanArgs,
584
0
                                   ArgStringList &CmdArgs) {
585
0
  const Driver &D = TC.getDriver();
586
0
  auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
587
0
                                         options::OPT_fprofile_generate_EQ,
588
0
                                         options::OPT_fno_profile_generate);
589
0
  if (PGOGenerateArg &&
590
0
      PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
591
0
    PGOGenerateArg = nullptr;
592
593
0
  auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
594
595
0
  auto *ProfileGenerateArg = Args.getLastArg(
596
0
      options::OPT_fprofile_instr_generate,
597
0
      options::OPT_fprofile_instr_generate_EQ,
598
0
      options::OPT_fno_profile_instr_generate);
599
0
  if (ProfileGenerateArg &&
600
0
      ProfileGenerateArg->getOption().matches(
601
0
          options::OPT_fno_profile_instr_generate))
602
0
    ProfileGenerateArg = nullptr;
603
604
0
  if (PGOGenerateArg && ProfileGenerateArg)
605
0
    D.Diag(diag::err_drv_argument_not_allowed_with)
606
0
        << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
607
608
0
  auto *ProfileUseArg = getLastProfileUseArg(Args);
609
610
0
  if (PGOGenerateArg && ProfileUseArg)
611
0
    D.Diag(diag::err_drv_argument_not_allowed_with)
612
0
        << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
613
614
0
  if (ProfileGenerateArg && ProfileUseArg)
615
0
    D.Diag(diag::err_drv_argument_not_allowed_with)
616
0
        << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
617
618
0
  if (CSPGOGenerateArg && PGOGenerateArg) {
619
0
    D.Diag(diag::err_drv_argument_not_allowed_with)
620
0
        << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
621
0
    PGOGenerateArg = nullptr;
622
0
  }
623
624
0
  if (TC.getTriple().isOSAIX()) {
625
0
    if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
626
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
627
0
          << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
628
0
  }
629
630
0
  if (ProfileGenerateArg) {
631
0
    if (ProfileGenerateArg->getOption().matches(
632
0
            options::OPT_fprofile_instr_generate_EQ))
633
0
      CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
634
0
                                           ProfileGenerateArg->getValue()));
635
    // The default is to use Clang Instrumentation.
636
0
    CmdArgs.push_back("-fprofile-instrument=clang");
637
0
    if (TC.getTriple().isWindowsMSVCEnvironment()) {
638
      // Add dependent lib for clang_rt.profile
639
0
      CmdArgs.push_back(Args.MakeArgString(
640
0
          "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
641
0
    }
642
0
  }
643
644
0
  Arg *PGOGenArg = nullptr;
645
0
  if (PGOGenerateArg) {
646
0
    assert(!CSPGOGenerateArg);
647
0
    PGOGenArg = PGOGenerateArg;
648
0
    CmdArgs.push_back("-fprofile-instrument=llvm");
649
0
  }
650
0
  if (CSPGOGenerateArg) {
651
0
    assert(!PGOGenerateArg);
652
0
    PGOGenArg = CSPGOGenerateArg;
653
0
    CmdArgs.push_back("-fprofile-instrument=csllvm");
654
0
  }
655
0
  if (PGOGenArg) {
656
0
    if (TC.getTriple().isWindowsMSVCEnvironment()) {
657
      // Add dependent lib for clang_rt.profile
658
0
      CmdArgs.push_back(Args.MakeArgString(
659
0
          "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
660
0
    }
661
0
    if (PGOGenArg->getOption().matches(
662
0
            PGOGenerateArg ? options::OPT_fprofile_generate_EQ
663
0
                           : options::OPT_fcs_profile_generate_EQ)) {
664
0
      SmallString<128> Path(PGOGenArg->getValue());
665
0
      llvm::sys::path::append(Path, "default_%m.profraw");
666
0
      CmdArgs.push_back(
667
0
          Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
668
0
    }
669
0
  }
670
671
0
  if (ProfileUseArg) {
672
0
    if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
673
0
      CmdArgs.push_back(Args.MakeArgString(
674
0
          Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
675
0
    else if ((ProfileUseArg->getOption().matches(
676
0
                  options::OPT_fprofile_use_EQ) ||
677
0
              ProfileUseArg->getOption().matches(
678
0
                  options::OPT_fprofile_instr_use))) {
679
0
      SmallString<128> Path(
680
0
          ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
681
0
      if (Path.empty() || llvm::sys::fs::is_directory(Path))
682
0
        llvm::sys::path::append(Path, "default.profdata");
683
0
      CmdArgs.push_back(
684
0
          Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
685
0
    }
686
0
  }
687
688
0
  bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
689
0
                                   options::OPT_fno_test_coverage, false) ||
690
0
                      Args.hasArg(options::OPT_coverage);
691
0
  bool EmitCovData = TC.needsGCovInstrumentation(Args);
692
693
0
  if (Args.hasFlag(options::OPT_fcoverage_mapping,
694
0
                   options::OPT_fno_coverage_mapping, false)) {
695
0
    if (!ProfileGenerateArg)
696
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
697
0
          << "-fcoverage-mapping"
698
0
          << "-fprofile-instr-generate";
699
700
0
    CmdArgs.push_back("-fcoverage-mapping");
701
0
  }
702
703
0
  if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
704
0
                   false)) {
705
0
    if (!Args.hasFlag(options::OPT_fcoverage_mapping,
706
0
                      options::OPT_fno_coverage_mapping, false))
707
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
708
0
          << "-fcoverage-mcdc"
709
0
          << "-fcoverage-mapping";
710
711
0
    CmdArgs.push_back("-fcoverage-mcdc");
712
0
  }
713
714
0
  if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
715
0
                               options::OPT_fcoverage_compilation_dir_EQ)) {
716
0
    if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
717
0
      CmdArgs.push_back(Args.MakeArgString(
718
0
          Twine("-fcoverage-compilation-dir=") + A->getValue()));
719
0
    else
720
0
      A->render(Args, CmdArgs);
721
0
  } else if (llvm::ErrorOr<std::string> CWD =
722
0
                 D.getVFS().getCurrentWorkingDirectory()) {
723
0
    CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
724
0
  }
725
726
0
  if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
727
0
    auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
728
0
    if (!Args.hasArg(options::OPT_coverage))
729
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
730
0
          << "-fprofile-exclude-files="
731
0
          << "--coverage";
732
733
0
    StringRef v = Arg->getValue();
734
0
    CmdArgs.push_back(
735
0
        Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
736
0
  }
737
738
0
  if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
739
0
    auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
740
0
    if (!Args.hasArg(options::OPT_coverage))
741
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
742
0
          << "-fprofile-filter-files="
743
0
          << "--coverage";
744
745
0
    StringRef v = Arg->getValue();
746
0
    CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
747
0
  }
748
749
0
  if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
750
0
    StringRef Val = A->getValue();
751
0
    if (Val == "atomic" || Val == "prefer-atomic")
752
0
      CmdArgs.push_back("-fprofile-update=atomic");
753
0
    else if (Val != "single")
754
0
      D.Diag(diag::err_drv_unsupported_option_argument)
755
0
          << A->getSpelling() << Val;
756
0
  }
757
758
0
  int FunctionGroups = 1;
759
0
  int SelectedFunctionGroup = 0;
760
0
  if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
761
0
    StringRef Val = A->getValue();
762
0
    if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
763
0
      D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
764
0
  }
765
0
  if (const auto *A =
766
0
          Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
767
0
    StringRef Val = A->getValue();
768
0
    if (Val.getAsInteger(0, SelectedFunctionGroup) ||
769
0
        SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
770
0
      D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
771
0
  }
772
0
  if (FunctionGroups != 1)
773
0
    CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
774
0
                                         Twine(FunctionGroups)));
775
0
  if (SelectedFunctionGroup != 0)
776
0
    CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
777
0
                                         Twine(SelectedFunctionGroup)));
778
779
  // Leave -fprofile-dir= an unused argument unless .gcda emission is
780
  // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
781
  // the flag used. There is no -fno-profile-dir, so the user has no
782
  // targeted way to suppress the warning.
783
0
  Arg *FProfileDir = nullptr;
784
0
  if (Args.hasArg(options::OPT_fprofile_arcs) ||
785
0
      Args.hasArg(options::OPT_coverage))
786
0
    FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
787
788
  // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
789
  // like we warn about -fsyntax-only -E.
790
0
  (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
791
792
  // Put the .gcno and .gcda files (if needed) next to the primary output file,
793
  // or fall back to a file in the current directory for `clang -c --coverage
794
  // d/a.c` in the absence of -o.
795
0
  if (EmitCovNotes || EmitCovData) {
796
0
    SmallString<128> CoverageFilename;
797
0
    if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
798
      // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
799
      // path separator.
800
0
      CoverageFilename = DumpDir->getValue();
801
0
      CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
802
0
    } else if (Arg *FinalOutput =
803
0
                   C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
804
0
      CoverageFilename = FinalOutput->getValue();
805
0
    } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
806
0
      CoverageFilename = FinalOutput->getValue();
807
0
    } else {
808
0
      CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
809
0
    }
810
0
    if (llvm::sys::path::is_relative(CoverageFilename))
811
0
      (void)D.getVFS().makeAbsolute(CoverageFilename);
812
0
    llvm::sys::path::replace_extension(CoverageFilename, "gcno");
813
0
    if (EmitCovNotes) {
814
0
      CmdArgs.push_back(
815
0
          Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
816
0
    }
817
818
0
    if (EmitCovData) {
819
0
      if (FProfileDir) {
820
0
        SmallString<128> Gcno = std::move(CoverageFilename);
821
0
        CoverageFilename = FProfileDir->getValue();
822
0
        llvm::sys::path::append(CoverageFilename, Gcno);
823
0
      }
824
0
      llvm::sys::path::replace_extension(CoverageFilename, "gcda");
825
0
      CmdArgs.push_back(
826
0
          Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
827
0
    }
828
0
  }
829
0
}
830
831
/// Check whether the given input tree contains any compilation actions.
832
0
static bool ContainsCompileAction(const Action *A) {
833
0
  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
834
0
    return true;
835
836
0
  return llvm::any_of(A->inputs(), ContainsCompileAction);
837
0
}
838
839
/// Check if -relax-all should be passed to the internal assembler.
840
/// This is done by default when compiling non-assembler source with -O0.
841
0
static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
842
0
  bool RelaxDefault = true;
843
844
0
  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
845
0
    RelaxDefault = A->getOption().matches(options::OPT_O0);
846
847
0
  if (RelaxDefault) {
848
0
    RelaxDefault = false;
849
0
    for (const auto &Act : C.getActions()) {
850
0
      if (ContainsCompileAction(Act)) {
851
0
        RelaxDefault = true;
852
0
        break;
853
0
      }
854
0
    }
855
0
  }
856
857
0
  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
858
0
                      RelaxDefault);
859
0
}
860
861
static void
862
RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
863
                        llvm::codegenoptions::DebugInfoKind DebugInfoKind,
864
                        unsigned DwarfVersion,
865
0
                        llvm::DebuggerKind DebuggerTuning) {
866
0
  addDebugInfoKind(CmdArgs, DebugInfoKind);
867
0
  if (DwarfVersion > 0)
868
0
    CmdArgs.push_back(
869
0
        Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
870
0
  switch (DebuggerTuning) {
871
0
  case llvm::DebuggerKind::GDB:
872
0
    CmdArgs.push_back("-debugger-tuning=gdb");
873
0
    break;
874
0
  case llvm::DebuggerKind::LLDB:
875
0
    CmdArgs.push_back("-debugger-tuning=lldb");
876
0
    break;
877
0
  case llvm::DebuggerKind::SCE:
878
0
    CmdArgs.push_back("-debugger-tuning=sce");
879
0
    break;
880
0
  case llvm::DebuggerKind::DBX:
881
0
    CmdArgs.push_back("-debugger-tuning=dbx");
882
0
    break;
883
0
  default:
884
0
    break;
885
0
  }
886
0
}
887
888
static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
889
0
                                 const Driver &D, const ToolChain &TC) {
890
0
  assert(A && "Expected non-nullptr argument.");
891
0
  if (TC.supportsDebugInfoOption(A))
892
0
    return true;
893
0
  D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
894
0
      << A->getAsString(Args) << TC.getTripleString();
895
0
  return false;
896
0
}
897
898
static void RenderDebugInfoCompressionArgs(const ArgList &Args,
899
                                           ArgStringList &CmdArgs,
900
                                           const Driver &D,
901
0
                                           const ToolChain &TC) {
902
0
  const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
903
0
  if (!A)
904
0
    return;
905
0
  if (checkDebugInfoOption(A, Args, D, TC)) {
906
0
    StringRef Value = A->getValue();
907
0
    if (Value == "none") {
908
0
      CmdArgs.push_back("--compress-debug-sections=none");
909
0
    } else if (Value == "zlib") {
910
0
      if (llvm::compression::zlib::isAvailable()) {
911
0
        CmdArgs.push_back(
912
0
            Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
913
0
      } else {
914
0
        D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
915
0
      }
916
0
    } else if (Value == "zstd") {
917
0
      if (llvm::compression::zstd::isAvailable()) {
918
0
        CmdArgs.push_back(
919
0
            Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
920
0
      } else {
921
0
        D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
922
0
      }
923
0
    } else {
924
0
      D.Diag(diag::err_drv_unsupported_option_argument)
925
0
          << A->getSpelling() << Value;
926
0
    }
927
0
  }
928
0
}
929
930
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
931
                                                 const ArgList &Args,
932
                                                 ArgStringList &CmdArgs,
933
0
                                                 bool IsCC1As = false) {
934
  // If no version was requested by the user, use the default value from the
935
  // back end. This is consistent with the value returned from
936
  // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
937
  // requiring the corresponding llvm to have the AMDGPU target enabled,
938
  // provided the user (e.g. front end tests) can use the default.
939
0
  if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
940
0
    unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
941
0
    CmdArgs.insert(CmdArgs.begin() + 1,
942
0
                   Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
943
0
                                      Twine(CodeObjVer)));
944
0
    CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
945
    // -cc1as does not accept -mcode-object-version option.
946
0
    if (!IsCC1As)
947
0
      CmdArgs.insert(CmdArgs.begin() + 1,
948
0
                     Args.MakeArgString(Twine("-mcode-object-version=") +
949
0
                                        Twine(CodeObjVer)));
950
0
  }
951
0
}
952
953
0
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
954
0
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
955
0
      D.getVFS().getBufferForFile(Path);
956
0
  if (!MemBuf)
957
0
    return false;
958
0
  llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
959
0
  if (Magic == llvm::file_magic::unknown)
960
0
    return false;
961
  // Return true for both raw Clang AST files and object files which may
962
  // contain a __clangast section.
963
0
  if (Magic == llvm::file_magic::clang_ast)
964
0
    return true;
965
0
  Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
966
0
      llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
967
0
  return !Obj.takeError();
968
0
}
969
970
0
static bool gchProbe(const Driver &D, StringRef Path) {
971
0
  llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
972
0
  if (!Status)
973
0
    return false;
974
975
0
  if (Status->isDirectory()) {
976
0
    std::error_code EC;
977
0
    for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
978
0
         !EC && DI != DE; DI = DI.increment(EC)) {
979
0
      if (maybeHasClangPchSignature(D, DI->path()))
980
0
        return true;
981
0
    }
982
0
    D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
983
0
    return false;
984
0
  }
985
986
0
  if (maybeHasClangPchSignature(D, Path))
987
0
    return true;
988
0
  D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
989
0
  return false;
990
0
}
991
992
void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
993
                                    const Driver &D, const ArgList &Args,
994
                                    ArgStringList &CmdArgs,
995
                                    const InputInfo &Output,
996
0
                                    const InputInfoList &Inputs) const {
997
0
  const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
998
999
0
  CheckPreprocessingOptions(D, Args);
1000
1001
0
  Args.AddLastArg(CmdArgs, options::OPT_C);
1002
0
  Args.AddLastArg(CmdArgs, options::OPT_CC);
1003
1004
  // Handle dependency file generation.
1005
0
  Arg *ArgM = Args.getLastArg(options::OPT_MM);
1006
0
  if (!ArgM)
1007
0
    ArgM = Args.getLastArg(options::OPT_M);
1008
0
  Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1009
0
  if (!ArgMD)
1010
0
    ArgMD = Args.getLastArg(options::OPT_MD);
1011
1012
  // -M and -MM imply -w.
1013
0
  if (ArgM)
1014
0
    CmdArgs.push_back("-w");
1015
0
  else
1016
0
    ArgM = ArgMD;
1017
1018
0
  if (ArgM) {
1019
    // Determine the output location.
1020
0
    const char *DepFile;
1021
0
    if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1022
0
      DepFile = MF->getValue();
1023
0
      C.addFailureResultFile(DepFile, &JA);
1024
0
    } else if (Output.getType() == types::TY_Dependencies) {
1025
0
      DepFile = Output.getFilename();
1026
0
    } else if (!ArgMD) {
1027
0
      DepFile = "-";
1028
0
    } else {
1029
0
      DepFile = getDependencyFileName(Args, Inputs);
1030
0
      C.addFailureResultFile(DepFile, &JA);
1031
0
    }
1032
0
    CmdArgs.push_back("-dependency-file");
1033
0
    CmdArgs.push_back(DepFile);
1034
1035
0
    bool HasTarget = false;
1036
0
    for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1037
0
      HasTarget = true;
1038
0
      A->claim();
1039
0
      if (A->getOption().matches(options::OPT_MT)) {
1040
0
        A->render(Args, CmdArgs);
1041
0
      } else {
1042
0
        CmdArgs.push_back("-MT");
1043
0
        SmallString<128> Quoted;
1044
0
        quoteMakeTarget(A->getValue(), Quoted);
1045
0
        CmdArgs.push_back(Args.MakeArgString(Quoted));
1046
0
      }
1047
0
    }
1048
1049
    // Add a default target if one wasn't specified.
1050
0
    if (!HasTarget) {
1051
0
      const char *DepTarget;
1052
1053
      // If user provided -o, that is the dependency target, except
1054
      // when we are only generating a dependency file.
1055
0
      Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1056
0
      if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1057
0
        DepTarget = OutputOpt->getValue();
1058
0
      } else {
1059
        // Otherwise derive from the base input.
1060
        //
1061
        // FIXME: This should use the computed output file location.
1062
0
        SmallString<128> P(Inputs[0].getBaseInput());
1063
0
        llvm::sys::path::replace_extension(P, "o");
1064
0
        DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1065
0
      }
1066
1067
0
      CmdArgs.push_back("-MT");
1068
0
      SmallString<128> Quoted;
1069
0
      quoteMakeTarget(DepTarget, Quoted);
1070
0
      CmdArgs.push_back(Args.MakeArgString(Quoted));
1071
0
    }
1072
1073
0
    if (ArgM->getOption().matches(options::OPT_M) ||
1074
0
        ArgM->getOption().matches(options::OPT_MD))
1075
0
      CmdArgs.push_back("-sys-header-deps");
1076
0
    if ((isa<PrecompileJobAction>(JA) &&
1077
0
         !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1078
0
        Args.hasArg(options::OPT_fmodule_file_deps))
1079
0
      CmdArgs.push_back("-module-file-deps");
1080
0
  }
1081
1082
0
  if (Args.hasArg(options::OPT_MG)) {
1083
0
    if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1084
0
        ArgM->getOption().matches(options::OPT_MMD))
1085
0
      D.Diag(diag::err_drv_mg_requires_m_or_mm);
1086
0
    CmdArgs.push_back("-MG");
1087
0
  }
1088
1089
0
  Args.AddLastArg(CmdArgs, options::OPT_MP);
1090
0
  Args.AddLastArg(CmdArgs, options::OPT_MV);
1091
1092
  // Add offload include arguments specific for CUDA/HIP.  This must happen
1093
  // before we -I or -include anything else, because we must pick up the
1094
  // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1095
  // from e.g. /usr/local/include.
1096
0
  if (JA.isOffloading(Action::OFK_Cuda))
1097
0
    getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1098
0
  if (JA.isOffloading(Action::OFK_HIP))
1099
0
    getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1100
1101
  // If we are compiling for a GPU target we want to override the system headers
1102
  // with ones created by the 'libc' project if present.
1103
0
  if (!Args.hasArg(options::OPT_nostdinc) &&
1104
0
      !Args.hasArg(options::OPT_nogpuinc) &&
1105
0
      !Args.hasArg(options::OPT_nobuiltininc)) {
1106
    // Without an offloading language we will include these headers directly.
1107
    // Offloading languages will instead only use the declarations stored in
1108
    // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1109
0
    if ((getToolChain().getTriple().isNVPTX() ||
1110
0
         getToolChain().getTriple().isAMDGCN()) &&
1111
0
        C.getActiveOffloadKinds() == Action::OFK_None) {
1112
0
      SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
1113
0
      llvm::sys::path::append(P, "include");
1114
0
      llvm::sys::path::append(P, "gpu-none-llvm");
1115
0
      CmdArgs.push_back("-c-isystem");
1116
0
      CmdArgs.push_back(Args.MakeArgString(P));
1117
0
    } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1118
      // TODO: CUDA / HIP include their own headers for some common functions
1119
      // implemented here. We'll need to clean those up so they do not conflict.
1120
0
      SmallString<128> P(D.ResourceDir);
1121
0
      llvm::sys::path::append(P, "include");
1122
0
      llvm::sys::path::append(P, "llvm_libc_wrappers");
1123
0
      CmdArgs.push_back("-internal-isystem");
1124
0
      CmdArgs.push_back(Args.MakeArgString(P));
1125
0
    }
1126
0
  }
1127
1128
  // If we are offloading to a target via OpenMP we need to include the
1129
  // openmp_wrappers folder which contains alternative system headers.
1130
0
  if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1131
0
      !Args.hasArg(options::OPT_nostdinc) &&
1132
0
      !Args.hasArg(options::OPT_nogpuinc) &&
1133
0
      (getToolChain().getTriple().isNVPTX() ||
1134
0
       getToolChain().getTriple().isAMDGCN())) {
1135
0
    if (!Args.hasArg(options::OPT_nobuiltininc)) {
1136
      // Add openmp_wrappers/* to our system include path.  This lets us wrap
1137
      // standard library headers.
1138
0
      SmallString<128> P(D.ResourceDir);
1139
0
      llvm::sys::path::append(P, "include");
1140
0
      llvm::sys::path::append(P, "openmp_wrappers");
1141
0
      CmdArgs.push_back("-internal-isystem");
1142
0
      CmdArgs.push_back(Args.MakeArgString(P));
1143
0
    }
1144
1145
0
    CmdArgs.push_back("-include");
1146
0
    CmdArgs.push_back("__clang_openmp_device_functions.h");
1147
0
  }
1148
1149
  // Add -i* options, and automatically translate to
1150
  // -include-pch/-include-pth for transparent PCH support. It's
1151
  // wonky, but we include looking for .gch so we can support seamless
1152
  // replacement into a build system already set up to be generating
1153
  // .gch files.
1154
1155
0
  if (getToolChain().getDriver().IsCLMode()) {
1156
0
    const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1157
0
    const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1158
0
    if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1159
0
        JA.getKind() <= Action::AssembleJobClass) {
1160
0
      CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1161
      // -fpch-instantiate-templates is the default when creating
1162
      // precomp using /Yc
1163
0
      if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1164
0
                       options::OPT_fno_pch_instantiate_templates, true))
1165
0
        CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1166
0
    }
1167
0
    if (YcArg || YuArg) {
1168
0
      StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1169
0
      if (!isa<PrecompileJobAction>(JA)) {
1170
0
        CmdArgs.push_back("-include-pch");
1171
0
        CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1172
0
            C, !ThroughHeader.empty()
1173
0
                   ? ThroughHeader
1174
0
                   : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1175
0
      }
1176
1177
0
      if (ThroughHeader.empty()) {
1178
0
        CmdArgs.push_back(Args.MakeArgString(
1179
0
            Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1180
0
      } else {
1181
0
        CmdArgs.push_back(
1182
0
            Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1183
0
      }
1184
0
    }
1185
0
  }
1186
1187
0
  bool RenderedImplicitInclude = false;
1188
0
  for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1189
0
    if (A->getOption().matches(options::OPT_include) &&
1190
0
        D.getProbePrecompiled()) {
1191
      // Handling of gcc-style gch precompiled headers.
1192
0
      bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1193
0
      RenderedImplicitInclude = true;
1194
1195
0
      bool FoundPCH = false;
1196
0
      SmallString<128> P(A->getValue());
1197
      // We want the files to have a name like foo.h.pch. Add a dummy extension
1198
      // so that replace_extension does the right thing.
1199
0
      P += ".dummy";
1200
0
      llvm::sys::path::replace_extension(P, "pch");
1201
0
      if (D.getVFS().exists(P))
1202
0
        FoundPCH = true;
1203
1204
0
      if (!FoundPCH) {
1205
        // For GCC compat, probe for a file or directory ending in .gch instead.
1206
0
        llvm::sys::path::replace_extension(P, "gch");
1207
0
        FoundPCH = gchProbe(D, P.str());
1208
0
      }
1209
1210
0
      if (FoundPCH) {
1211
0
        if (IsFirstImplicitInclude) {
1212
0
          A->claim();
1213
0
          CmdArgs.push_back("-include-pch");
1214
0
          CmdArgs.push_back(Args.MakeArgString(P));
1215
0
          continue;
1216
0
        } else {
1217
          // Ignore the PCH if not first on command line and emit warning.
1218
0
          D.Diag(diag::warn_drv_pch_not_first_include) << P
1219
0
                                                       << A->getAsString(Args);
1220
0
        }
1221
0
      }
1222
0
    } else if (A->getOption().matches(options::OPT_isystem_after)) {
1223
      // Handling of paths which must come late.  These entries are handled by
1224
      // the toolchain itself after the resource dir is inserted in the right
1225
      // search order.
1226
      // Do not claim the argument so that the use of the argument does not
1227
      // silently go unnoticed on toolchains which do not honour the option.
1228
0
      continue;
1229
0
    } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1230
      // Translated to -internal-isystem by the driver, no need to pass to cc1.
1231
0
      continue;
1232
0
    } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1233
      // This is used only by the driver. No need to pass to cc1.
1234
0
      continue;
1235
0
    }
1236
1237
    // Not translated, render as usual.
1238
0
    A->claim();
1239
0
    A->render(Args, CmdArgs);
1240
0
  }
1241
1242
0
  Args.addAllArgs(CmdArgs,
1243
0
                  {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1244
0
                   options::OPT_F, options::OPT_index_header_map});
1245
1246
  // Add -Wp, and -Xpreprocessor if using the preprocessor.
1247
1248
  // FIXME: There is a very unfortunate problem here, some troubled
1249
  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1250
  // really support that we would have to parse and then translate
1251
  // those options. :(
1252
0
  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1253
0
                       options::OPT_Xpreprocessor);
1254
1255
  // -I- is a deprecated GCC feature, reject it.
1256
0
  if (Arg *A = Args.getLastArg(options::OPT_I_))
1257
0
    D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1258
1259
  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1260
  // -isysroot to the CC1 invocation.
1261
0
  StringRef sysroot = C.getSysRoot();
1262
0
  if (sysroot != "") {
1263
0
    if (!Args.hasArg(options::OPT_isysroot)) {
1264
0
      CmdArgs.push_back("-isysroot");
1265
0
      CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1266
0
    }
1267
0
  }
1268
1269
  // Parse additional include paths from environment variables.
1270
  // FIXME: We should probably sink the logic for handling these from the
1271
  // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1272
  // CPATH - included following the user specified includes (but prior to
1273
  // builtin and standard includes).
1274
0
  addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1275
  // C_INCLUDE_PATH - system includes enabled when compiling C.
1276
0
  addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1277
  // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1278
0
  addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1279
  // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1280
0
  addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1281
  // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1282
0
  addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1283
1284
  // While adding the include arguments, we also attempt to retrieve the
1285
  // arguments of related offloading toolchains or arguments that are specific
1286
  // of an offloading programming model.
1287
1288
  // Add C++ include arguments, if needed.
1289
0
  if (types::isCXX(Inputs[0].getType())) {
1290
0
    bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1291
0
    forAllAssociatedToolChains(
1292
0
        C, JA, getToolChain(),
1293
0
        [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1294
0
          HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1295
0
                             : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1296
0
        });
1297
0
  }
1298
1299
  // Add system include arguments for all targets but IAMCU.
1300
0
  if (!IsIAMCU)
1301
0
    forAllAssociatedToolChains(C, JA, getToolChain(),
1302
0
                               [&Args, &CmdArgs](const ToolChain &TC) {
1303
0
                                 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1304
0
                               });
1305
0
  else {
1306
    // For IAMCU add special include arguments.
1307
0
    getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1308
0
  }
1309
1310
0
  addMacroPrefixMapArg(D, Args, CmdArgs);
1311
0
  addCoveragePrefixMapArg(D, Args, CmdArgs);
1312
1313
0
  Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1314
0
                  options::OPT_fno_file_reproducible);
1315
1316
0
  if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1317
0
    CmdArgs.push_back("-source-date-epoch");
1318
0
    CmdArgs.push_back(Args.MakeArgString(Epoch));
1319
0
  }
1320
1321
0
  Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1322
0
                    options::OPT_fno_define_target_os_macros);
1323
0
}
1324
1325
// FIXME: Move to target hook.
1326
0
static bool isSignedCharDefault(const llvm::Triple &Triple) {
1327
0
  switch (Triple.getArch()) {
1328
0
  default:
1329
0
    return true;
1330
1331
0
  case llvm::Triple::aarch64:
1332
0
  case llvm::Triple::aarch64_32:
1333
0
  case llvm::Triple::aarch64_be:
1334
0
  case llvm::Triple::arm:
1335
0
  case llvm::Triple::armeb:
1336
0
  case llvm::Triple::thumb:
1337
0
  case llvm::Triple::thumbeb:
1338
0
    if (Triple.isOSDarwin() || Triple.isOSWindows())
1339
0
      return true;
1340
0
    return false;
1341
1342
0
  case llvm::Triple::ppc:
1343
0
  case llvm::Triple::ppc64:
1344
0
    if (Triple.isOSDarwin())
1345
0
      return true;
1346
0
    return false;
1347
1348
0
  case llvm::Triple::hexagon:
1349
0
  case llvm::Triple::ppcle:
1350
0
  case llvm::Triple::ppc64le:
1351
0
  case llvm::Triple::riscv32:
1352
0
  case llvm::Triple::riscv64:
1353
0
  case llvm::Triple::systemz:
1354
0
  case llvm::Triple::xcore:
1355
0
    return false;
1356
0
  }
1357
0
}
1358
1359
static bool hasMultipleInvocations(const llvm::Triple &Triple,
1360
0
                                   const ArgList &Args) {
1361
  // Supported only on Darwin where we invoke the compiler multiple times
1362
  // followed by an invocation to lipo.
1363
0
  if (!Triple.isOSDarwin())
1364
0
    return false;
1365
  // If more than one "-arch <arch>" is specified, we're targeting multiple
1366
  // architectures resulting in a fat binary.
1367
0
  return Args.getAllArgValues(options::OPT_arch).size() > 1;
1368
0
}
1369
1370
static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1371
0
                                const llvm::Triple &Triple) {
1372
  // When enabling remarks, we need to error if:
1373
  // * The remark file is specified but we're targeting multiple architectures,
1374
  // which means more than one remark file is being generated.
1375
0
  bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1376
0
  bool hasExplicitOutputFile =
1377
0
      Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1378
0
  if (hasMultipleInvocations && hasExplicitOutputFile) {
1379
0
    D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1380
0
        << "-foptimization-record-file";
1381
0
    return false;
1382
0
  }
1383
0
  return true;
1384
0
}
1385
1386
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1387
                                 const llvm::Triple &Triple,
1388
                                 const InputInfo &Input,
1389
0
                                 const InputInfo &Output, const JobAction &JA) {
1390
0
  StringRef Format = "yaml";
1391
0
  if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1392
0
    Format = A->getValue();
1393
1394
0
  CmdArgs.push_back("-opt-record-file");
1395
1396
0
  const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1397
0
  if (A) {
1398
0
    CmdArgs.push_back(A->getValue());
1399
0
  } else {
1400
0
    bool hasMultipleArchs =
1401
0
        Triple.isOSDarwin() && // Only supported on Darwin platforms.
1402
0
        Args.getAllArgValues(options::OPT_arch).size() > 1;
1403
1404
0
    SmallString<128> F;
1405
1406
0
    if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1407
0
      if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1408
0
        F = FinalOutput->getValue();
1409
0
    } else {
1410
0
      if (Format != "yaml" && // For YAML, keep the original behavior.
1411
0
          Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1412
0
          Output.isFilename())
1413
0
        F = Output.getFilename();
1414
0
    }
1415
1416
0
    if (F.empty()) {
1417
      // Use the input filename.
1418
0
      F = llvm::sys::path::stem(Input.getBaseInput());
1419
1420
      // If we're compiling for an offload architecture (i.e. a CUDA device),
1421
      // we need to make the file name for the device compilation different
1422
      // from the host compilation.
1423
0
      if (!JA.isDeviceOffloading(Action::OFK_None) &&
1424
0
          !JA.isDeviceOffloading(Action::OFK_Host)) {
1425
0
        llvm::sys::path::replace_extension(F, "");
1426
0
        F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1427
0
                                                 Triple.normalize());
1428
0
        F += "-";
1429
0
        F += JA.getOffloadingArch();
1430
0
      }
1431
0
    }
1432
1433
    // If we're having more than one "-arch", we should name the files
1434
    // differently so that every cc1 invocation writes to a different file.
1435
    // We're doing that by appending "-<arch>" with "<arch>" being the arch
1436
    // name from the triple.
1437
0
    if (hasMultipleArchs) {
1438
      // First, remember the extension.
1439
0
      SmallString<64> OldExtension = llvm::sys::path::extension(F);
1440
      // then, remove it.
1441
0
      llvm::sys::path::replace_extension(F, "");
1442
      // attach -<arch> to it.
1443
0
      F += "-";
1444
0
      F += Triple.getArchName();
1445
      // put back the extension.
1446
0
      llvm::sys::path::replace_extension(F, OldExtension);
1447
0
    }
1448
1449
0
    SmallString<32> Extension;
1450
0
    Extension += "opt.";
1451
0
    Extension += Format;
1452
1453
0
    llvm::sys::path::replace_extension(F, Extension);
1454
0
    CmdArgs.push_back(Args.MakeArgString(F));
1455
0
  }
1456
1457
0
  if (const Arg *A =
1458
0
          Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1459
0
    CmdArgs.push_back("-opt-record-passes");
1460
0
    CmdArgs.push_back(A->getValue());
1461
0
  }
1462
1463
0
  if (!Format.empty()) {
1464
0
    CmdArgs.push_back("-opt-record-format");
1465
0
    CmdArgs.push_back(Format.data());
1466
0
  }
1467
0
}
1468
1469
0
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1470
0
  if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1471
0
                    options::OPT_fno_aapcs_bitfield_width, true))
1472
0
    CmdArgs.push_back("-fno-aapcs-bitfield-width");
1473
1474
0
  if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1475
0
    CmdArgs.push_back("-faapcs-bitfield-load");
1476
0
}
1477
1478
namespace {
1479
void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1480
0
                  const ArgList &Args, ArgStringList &CmdArgs) {
1481
  // Select the ABI to use.
1482
  // FIXME: Support -meabi.
1483
  // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1484
0
  const char *ABIName = nullptr;
1485
0
  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1486
0
    ABIName = A->getValue();
1487
0
  } else {
1488
0
    std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1489
0
    ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1490
0
  }
1491
1492
0
  CmdArgs.push_back("-target-abi");
1493
0
  CmdArgs.push_back(ABIName);
1494
0
}
1495
1496
0
void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1497
0
  auto StrictAlignIter =
1498
0
      llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1499
0
        return Arg == "+strict-align" || Arg == "-strict-align";
1500
0
      });
1501
0
  if (StrictAlignIter != CmdArgs.rend() &&
1502
0
      StringRef(*StrictAlignIter) == "+strict-align")
1503
0
    CmdArgs.push_back("-Wunaligned-access");
1504
0
}
1505
}
1506
1507
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1508
0
                                    ArgStringList &CmdArgs, bool isAArch64) {
1509
0
  const Arg *A = isAArch64
1510
0
                     ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1511
0
                                       options::OPT_mbranch_protection_EQ)
1512
0
                     : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1513
0
  if (!A)
1514
0
    return;
1515
1516
0
  const Driver &D = TC.getDriver();
1517
0
  const llvm::Triple &Triple = TC.getEffectiveTriple();
1518
0
  if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1519
0
    D.Diag(diag::warn_incompatible_branch_protection_option)
1520
0
        << Triple.getArchName();
1521
1522
0
  StringRef Scope, Key;
1523
0
  bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1524
1525
0
  if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1526
0
    Scope = A->getValue();
1527
0
    if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1528
0
      D.Diag(diag::err_drv_unsupported_option_argument)
1529
0
          << A->getSpelling() << Scope;
1530
0
    Key = "a_key";
1531
0
    IndirectBranches = false;
1532
0
    BranchProtectionPAuthLR = false;
1533
0
    GuardedControlStack = false;
1534
0
  } else {
1535
0
    StringRef DiagMsg;
1536
0
    llvm::ARM::ParsedBranchProtection PBP;
1537
0
    if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
1538
0
      D.Diag(diag::err_drv_unsupported_option_argument)
1539
0
          << A->getSpelling() << DiagMsg;
1540
0
    if (!isAArch64 && PBP.Key == "b_key")
1541
0
      D.Diag(diag::warn_unsupported_branch_protection)
1542
0
          << "b-key" << A->getAsString(Args);
1543
0
    Scope = PBP.Scope;
1544
0
    Key = PBP.Key;
1545
0
    BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1546
0
    IndirectBranches = PBP.BranchTargetEnforcement;
1547
0
    GuardedControlStack = PBP.GuardedControlStack;
1548
0
  }
1549
1550
0
  CmdArgs.push_back(
1551
0
      Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1552
0
  if (!Scope.equals("none"))
1553
0
    CmdArgs.push_back(
1554
0
        Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1555
0
  if (BranchProtectionPAuthLR)
1556
0
    CmdArgs.push_back(
1557
0
        Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1558
0
  if (IndirectBranches)
1559
0
    CmdArgs.push_back("-mbranch-target-enforce");
1560
0
  if (GuardedControlStack)
1561
0
    CmdArgs.push_back("-mguarded-control-stack");
1562
0
}
1563
1564
void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1565
0
                             ArgStringList &CmdArgs, bool KernelOrKext) const {
1566
0
  RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1567
1568
  // Determine floating point ABI from the options & target defaults.
1569
0
  arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1570
0
  if (ABI == arm::FloatABI::Soft) {
1571
    // Floating point operations and argument passing are soft.
1572
    // FIXME: This changes CPP defines, we need -target-soft-float.
1573
0
    CmdArgs.push_back("-msoft-float");
1574
0
    CmdArgs.push_back("-mfloat-abi");
1575
0
    CmdArgs.push_back("soft");
1576
0
  } else if (ABI == arm::FloatABI::SoftFP) {
1577
    // Floating point operations are hard, but argument passing is soft.
1578
0
    CmdArgs.push_back("-mfloat-abi");
1579
0
    CmdArgs.push_back("soft");
1580
0
  } else {
1581
    // Floating point operations and argument passing are hard.
1582
0
    assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1583
0
    CmdArgs.push_back("-mfloat-abi");
1584
0
    CmdArgs.push_back("hard");
1585
0
  }
1586
1587
  // Forward the -mglobal-merge option for explicit control over the pass.
1588
0
  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1589
0
                               options::OPT_mno_global_merge)) {
1590
0
    CmdArgs.push_back("-mllvm");
1591
0
    if (A->getOption().matches(options::OPT_mno_global_merge))
1592
0
      CmdArgs.push_back("-arm-global-merge=false");
1593
0
    else
1594
0
      CmdArgs.push_back("-arm-global-merge=true");
1595
0
  }
1596
1597
0
  if (!Args.hasFlag(options::OPT_mimplicit_float,
1598
0
                    options::OPT_mno_implicit_float, true))
1599
0
    CmdArgs.push_back("-no-implicit-float");
1600
1601
0
  if (Args.getLastArg(options::OPT_mcmse))
1602
0
    CmdArgs.push_back("-mcmse");
1603
1604
0
  AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1605
1606
  // Enable/disable return address signing and indirect branch targets.
1607
0
  CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1608
1609
0
  AddUnalignedAccessWarning(CmdArgs);
1610
0
}
1611
1612
void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1613
                                const ArgList &Args, bool KernelOrKext,
1614
0
                                ArgStringList &CmdArgs) const {
1615
0
  const ToolChain &TC = getToolChain();
1616
1617
  // Add the target features
1618
0
  getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1619
1620
  // Add target specific flags.
1621
0
  switch (TC.getArch()) {
1622
0
  default:
1623
0
    break;
1624
1625
0
  case llvm::Triple::arm:
1626
0
  case llvm::Triple::armeb:
1627
0
  case llvm::Triple::thumb:
1628
0
  case llvm::Triple::thumbeb:
1629
    // Use the effective triple, which takes into account the deployment target.
1630
0
    AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1631
0
    break;
1632
1633
0
  case llvm::Triple::aarch64:
1634
0
  case llvm::Triple::aarch64_32:
1635
0
  case llvm::Triple::aarch64_be:
1636
0
    AddAArch64TargetArgs(Args, CmdArgs);
1637
0
    break;
1638
1639
0
  case llvm::Triple::loongarch32:
1640
0
  case llvm::Triple::loongarch64:
1641
0
    AddLoongArchTargetArgs(Args, CmdArgs);
1642
0
    break;
1643
1644
0
  case llvm::Triple::mips:
1645
0
  case llvm::Triple::mipsel:
1646
0
  case llvm::Triple::mips64:
1647
0
  case llvm::Triple::mips64el:
1648
0
    AddMIPSTargetArgs(Args, CmdArgs);
1649
0
    break;
1650
1651
0
  case llvm::Triple::ppc:
1652
0
  case llvm::Triple::ppcle:
1653
0
  case llvm::Triple::ppc64:
1654
0
  case llvm::Triple::ppc64le:
1655
0
    AddPPCTargetArgs(Args, CmdArgs);
1656
0
    break;
1657
1658
0
  case llvm::Triple::riscv32:
1659
0
  case llvm::Triple::riscv64:
1660
0
    AddRISCVTargetArgs(Args, CmdArgs);
1661
0
    break;
1662
1663
0
  case llvm::Triple::sparc:
1664
0
  case llvm::Triple::sparcel:
1665
0
  case llvm::Triple::sparcv9:
1666
0
    AddSparcTargetArgs(Args, CmdArgs);
1667
0
    break;
1668
1669
0
  case llvm::Triple::systemz:
1670
0
    AddSystemZTargetArgs(Args, CmdArgs);
1671
0
    break;
1672
1673
0
  case llvm::Triple::x86:
1674
0
  case llvm::Triple::x86_64:
1675
0
    AddX86TargetArgs(Args, CmdArgs);
1676
0
    break;
1677
1678
0
  case llvm::Triple::lanai:
1679
0
    AddLanaiTargetArgs(Args, CmdArgs);
1680
0
    break;
1681
1682
0
  case llvm::Triple::hexagon:
1683
0
    AddHexagonTargetArgs(Args, CmdArgs);
1684
0
    break;
1685
1686
0
  case llvm::Triple::wasm32:
1687
0
  case llvm::Triple::wasm64:
1688
0
    AddWebAssemblyTargetArgs(Args, CmdArgs);
1689
0
    break;
1690
1691
0
  case llvm::Triple::ve:
1692
0
    AddVETargetArgs(Args, CmdArgs);
1693
0
    break;
1694
0
  }
1695
0
}
1696
1697
namespace {
1698
void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1699
0
                      ArgStringList &CmdArgs) {
1700
0
  const char *ABIName = nullptr;
1701
0
  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1702
0
    ABIName = A->getValue();
1703
0
  else if (Triple.isOSDarwin())
1704
0
    ABIName = "darwinpcs";
1705
0
  else
1706
0
    ABIName = "aapcs";
1707
1708
0
  CmdArgs.push_back("-target-abi");
1709
0
  CmdArgs.push_back(ABIName);
1710
0
}
1711
}
1712
1713
void Clang::AddAArch64TargetArgs(const ArgList &Args,
1714
0
                                 ArgStringList &CmdArgs) const {
1715
0
  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1716
1717
0
  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1718
0
      Args.hasArg(options::OPT_mkernel) ||
1719
0
      Args.hasArg(options::OPT_fapple_kext))
1720
0
    CmdArgs.push_back("-disable-red-zone");
1721
1722
0
  if (!Args.hasFlag(options::OPT_mimplicit_float,
1723
0
                    options::OPT_mno_implicit_float, true))
1724
0
    CmdArgs.push_back("-no-implicit-float");
1725
1726
0
  RenderAArch64ABI(Triple, Args, CmdArgs);
1727
1728
  // Forward the -mglobal-merge option for explicit control over the pass.
1729
0
  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1730
0
                               options::OPT_mno_global_merge)) {
1731
0
    CmdArgs.push_back("-mllvm");
1732
0
    if (A->getOption().matches(options::OPT_mno_global_merge))
1733
0
      CmdArgs.push_back("-aarch64-enable-global-merge=false");
1734
0
    else
1735
0
      CmdArgs.push_back("-aarch64-enable-global-merge=true");
1736
0
  }
1737
1738
  // Enable/disable return address signing and indirect branch targets.
1739
0
  CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1740
1741
  // Handle -msve_vector_bits=<bits>
1742
0
  if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1743
0
    StringRef Val = A->getValue();
1744
0
    const Driver &D = getToolChain().getDriver();
1745
0
    if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1746
0
        Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
1747
0
        Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
1748
0
        Val.equals("2048+")) {
1749
0
      unsigned Bits = 0;
1750
0
      if (Val.ends_with("+"))
1751
0
        Val = Val.substr(0, Val.size() - 1);
1752
0
      else {
1753
0
        bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1754
0
        assert(!Invalid && "Failed to parse value");
1755
0
        CmdArgs.push_back(
1756
0
            Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1757
0
      }
1758
1759
0
      bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1760
0
      assert(!Invalid && "Failed to parse value");
1761
0
      CmdArgs.push_back(
1762
0
          Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1763
    // Silently drop requests for vector-length agnostic code as it's implied.
1764
0
    } else if (!Val.equals("scalable"))
1765
      // Handle the unsupported values passed to msve-vector-bits.
1766
0
      D.Diag(diag::err_drv_unsupported_option_argument)
1767
0
          << A->getSpelling() << Val;
1768
0
  }
1769
1770
0
  AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1771
1772
0
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1773
0
    CmdArgs.push_back("-tune-cpu");
1774
0
    if (strcmp(A->getValue(), "native") == 0)
1775
0
      CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1776
0
    else
1777
0
      CmdArgs.push_back(A->getValue());
1778
0
  }
1779
1780
0
  AddUnalignedAccessWarning(CmdArgs);
1781
0
}
1782
1783
void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1784
0
                                   ArgStringList &CmdArgs) const {
1785
0
  const llvm::Triple &Triple = getToolChain().getTriple();
1786
1787
0
  CmdArgs.push_back("-target-abi");
1788
0
  CmdArgs.push_back(
1789
0
      loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1790
0
          .data());
1791
1792
  // Handle -mtune.
1793
0
  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1794
0
    std::string TuneCPU = A->getValue();
1795
0
    TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1796
0
    CmdArgs.push_back("-tune-cpu");
1797
0
    CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1798
0
  }
1799
0
}
1800
1801
void Clang::AddMIPSTargetArgs(const ArgList &Args,
1802
0
                              ArgStringList &CmdArgs) const {
1803
0
  const Driver &D = getToolChain().getDriver();
1804
0
  StringRef CPUName;
1805
0
  StringRef ABIName;
1806
0
  const llvm::Triple &Triple = getToolChain().getTriple();
1807
0
  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1808
1809
0
  CmdArgs.push_back("-target-abi");
1810
0
  CmdArgs.push_back(ABIName.data());
1811
1812
0
  mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1813
0
  if (ABI == mips::FloatABI::Soft) {
1814
    // Floating point operations and argument passing are soft.
1815
0
    CmdArgs.push_back("-msoft-float");
1816
0
    CmdArgs.push_back("-mfloat-abi");
1817
0
    CmdArgs.push_back("soft");
1818
0
  } else {
1819
    // Floating point operations and argument passing are hard.
1820
0
    assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1821
0
    CmdArgs.push_back("-mfloat-abi");
1822
0
    CmdArgs.push_back("hard");
1823
0
  }
1824
1825
0
  if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1826
0
                               options::OPT_mno_ldc1_sdc1)) {
1827
0
    if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1828
0
      CmdArgs.push_back("-mllvm");
1829
0
      CmdArgs.push_back("-mno-ldc1-sdc1");
1830
0
    }
1831
0
  }
1832
1833
0
  if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1834
0
                               options::OPT_mno_check_zero_division)) {
1835
0
    if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1836
0
      CmdArgs.push_back("-mllvm");
1837
0
      CmdArgs.push_back("-mno-check-zero-division");
1838
0
    }
1839
0
  }
1840
1841
0
  if (Args.getLastArg(options::OPT_mfix4300)) {
1842
0
    CmdArgs.push_back("-mllvm");
1843
0
    CmdArgs.push_back("-mfix4300");
1844
0
  }
1845
1846
0
  if (Arg *A = Args.getLastArg(options::OPT_G)) {
1847
0
    StringRef v = A->getValue();
1848
0
    CmdArgs.push_back("-mllvm");
1849
0
    CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1850
0
    A->claim();
1851
0
  }
1852
1853
0
  Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1854
0
  Arg *ABICalls =
1855
0
      Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1856
1857
  // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1858
  // -mgpopt is the default for static, -fno-pic environments but these two
1859
  // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1860
  // the only case where -mllvm -mgpopt is passed.
1861
  // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1862
  //       passed explicitly when compiling something with -mabicalls
1863
  //       (implictly) in affect. Currently the warning is in the backend.
1864
  //
1865
  // When the ABI in use is  N64, we also need to determine the PIC mode that
1866
  // is in use, as -fno-pic for N64 implies -mno-abicalls.
1867
0
  bool NoABICalls =
1868
0
      ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1869
1870
0
  llvm::Reloc::Model RelocationModel;
1871
0
  unsigned PICLevel;
1872
0
  bool IsPIE;
1873
0
  std::tie(RelocationModel, PICLevel, IsPIE) =
1874
0
      ParsePICArgs(getToolChain(), Args);
1875
1876
0
  NoABICalls = NoABICalls ||
1877
0
               (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1878
1879
0
  bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1880
  // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1881
0
  if (NoABICalls && (!GPOpt || WantGPOpt)) {
1882
0
    CmdArgs.push_back("-mllvm");
1883
0
    CmdArgs.push_back("-mgpopt");
1884
1885
0
    Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1886
0
                                      options::OPT_mno_local_sdata);
1887
0
    Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1888
0
                                       options::OPT_mno_extern_sdata);
1889
0
    Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1890
0
                                        options::OPT_mno_embedded_data);
1891
0
    if (LocalSData) {
1892
0
      CmdArgs.push_back("-mllvm");
1893
0
      if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1894
0
        CmdArgs.push_back("-mlocal-sdata=1");
1895
0
      } else {
1896
0
        CmdArgs.push_back("-mlocal-sdata=0");
1897
0
      }
1898
0
      LocalSData->claim();
1899
0
    }
1900
1901
0
    if (ExternSData) {
1902
0
      CmdArgs.push_back("-mllvm");
1903
0
      if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1904
0
        CmdArgs.push_back("-mextern-sdata=1");
1905
0
      } else {
1906
0
        CmdArgs.push_back("-mextern-sdata=0");
1907
0
      }
1908
0
      ExternSData->claim();
1909
0
    }
1910
1911
0
    if (EmbeddedData) {
1912
0
      CmdArgs.push_back("-mllvm");
1913
0
      if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1914
0
        CmdArgs.push_back("-membedded-data=1");
1915
0
      } else {
1916
0
        CmdArgs.push_back("-membedded-data=0");
1917
0
      }
1918
0
      EmbeddedData->claim();
1919
0
    }
1920
1921
0
  } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1922
0
    D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1923
1924
0
  if (GPOpt)
1925
0
    GPOpt->claim();
1926
1927
0
  if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1928
0
    StringRef Val = StringRef(A->getValue());
1929
0
    if (mips::hasCompactBranches(CPUName)) {
1930
0
      if (Val == "never" || Val == "always" || Val == "optimal") {
1931
0
        CmdArgs.push_back("-mllvm");
1932
0
        CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1933
0
      } else
1934
0
        D.Diag(diag::err_drv_unsupported_option_argument)
1935
0
            << A->getSpelling() << Val;
1936
0
    } else
1937
0
      D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1938
0
  }
1939
1940
0
  if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1941
0
                               options::OPT_mno_relax_pic_calls)) {
1942
0
    if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1943
0
      CmdArgs.push_back("-mllvm");
1944
0
      CmdArgs.push_back("-mips-jalr-reloc=0");
1945
0
    }
1946
0
  }
1947
0
}
1948
1949
void Clang::AddPPCTargetArgs(const ArgList &Args,
1950
0
                             ArgStringList &CmdArgs) const {
1951
0
  const Driver &D = getToolChain().getDriver();
1952
0
  const llvm::Triple &T = getToolChain().getTriple();
1953
0
  if (Args.getLastArg(options::OPT_mtune_EQ)) {
1954
0
    CmdArgs.push_back("-tune-cpu");
1955
0
    std::string CPU = ppc::getPPCTuneCPU(Args, T);
1956
0
    CmdArgs.push_back(Args.MakeArgString(CPU));
1957
0
  }
1958
1959
  // Select the ABI to use.
1960
0
  const char *ABIName = nullptr;
1961
0
  if (T.isOSBinFormatELF()) {
1962
0
    switch (getToolChain().getArch()) {
1963
0
    case llvm::Triple::ppc64: {
1964
0
      if (T.isPPC64ELFv2ABI())
1965
0
        ABIName = "elfv2";
1966
0
      else
1967
0
        ABIName = "elfv1";
1968
0
      break;
1969
0
    }
1970
0
    case llvm::Triple::ppc64le:
1971
0
      ABIName = "elfv2";
1972
0
      break;
1973
0
    default:
1974
0
      break;
1975
0
    }
1976
0
  }
1977
1978
0
  bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1979
0
  bool VecExtabi = false;
1980
0
  for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1981
0
    StringRef V = A->getValue();
1982
0
    if (V == "ieeelongdouble") {
1983
0
      IEEELongDouble = true;
1984
0
      A->claim();
1985
0
    } else if (V == "ibmlongdouble") {
1986
0
      IEEELongDouble = false;
1987
0
      A->claim();
1988
0
    } else if (V == "vec-default") {
1989
0
      VecExtabi = false;
1990
0
      A->claim();
1991
0
    } else if (V == "vec-extabi") {
1992
0
      VecExtabi = true;
1993
0
      A->claim();
1994
0
    } else if (V == "elfv1") {
1995
0
      ABIName = "elfv1";
1996
0
      A->claim();
1997
0
    } else if (V == "elfv2") {
1998
0
      ABIName = "elfv2";
1999
0
      A->claim();
2000
0
    } else if (V != "altivec")
2001
      // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2002
      // the option if given as we don't have backend support for any targets
2003
      // that don't use the altivec abi.
2004
0
      ABIName = A->getValue();
2005
0
  }
2006
0
  if (IEEELongDouble)
2007
0
    CmdArgs.push_back("-mabi=ieeelongdouble");
2008
0
  if (VecExtabi) {
2009
0
    if (!T.isOSAIX())
2010
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
2011
0
          << "-mabi=vec-extabi" << T.str();
2012
0
    CmdArgs.push_back("-mabi=vec-extabi");
2013
0
  }
2014
2015
0
  ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2016
0
  if (FloatABI == ppc::FloatABI::Soft) {
2017
    // Floating point operations and argument passing are soft.
2018
0
    CmdArgs.push_back("-msoft-float");
2019
0
    CmdArgs.push_back("-mfloat-abi");
2020
0
    CmdArgs.push_back("soft");
2021
0
  } else {
2022
    // Floating point operations and argument passing are hard.
2023
0
    assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2024
0
    CmdArgs.push_back("-mfloat-abi");
2025
0
    CmdArgs.push_back("hard");
2026
0
  }
2027
2028
0
  if (ABIName) {
2029
0
    CmdArgs.push_back("-target-abi");
2030
0
    CmdArgs.push_back(ABIName);
2031
0
  }
2032
0
}
2033
2034
static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2035
0
                                   ArgStringList &CmdArgs) {
2036
0
  const Driver &D = TC.getDriver();
2037
0
  const llvm::Triple &Triple = TC.getTriple();
2038
  // Default small data limitation is eight.
2039
0
  const char *SmallDataLimit = "8";
2040
  // Get small data limitation.
2041
0
  if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2042
0
                      options::OPT_fPIC)) {
2043
    // Not support linker relaxation for PIC.
2044
0
    SmallDataLimit = "0";
2045
0
    if (Args.hasArg(options::OPT_G)) {
2046
0
      D.Diag(diag::warn_drv_unsupported_sdata);
2047
0
    }
2048
0
  } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2049
0
                 .equals_insensitive("large") &&
2050
0
             (Triple.getArch() == llvm::Triple::riscv64)) {
2051
    // Not support linker relaxation for RV64 with large code model.
2052
0
    SmallDataLimit = "0";
2053
0
    if (Args.hasArg(options::OPT_G)) {
2054
0
      D.Diag(diag::warn_drv_unsupported_sdata);
2055
0
    }
2056
0
  } else if (Triple.isAndroid()) {
2057
    // GP relaxation is not supported on Android.
2058
0
    SmallDataLimit = "0";
2059
0
    if (Args.hasArg(options::OPT_G)) {
2060
0
      D.Diag(diag::warn_drv_unsupported_sdata);
2061
0
    }
2062
0
  } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2063
0
    SmallDataLimit = A->getValue();
2064
0
  }
2065
  // Forward the -msmall-data-limit= option.
2066
0
  CmdArgs.push_back("-msmall-data-limit");
2067
0
  CmdArgs.push_back(SmallDataLimit);
2068
0
}
2069
2070
void Clang::AddRISCVTargetArgs(const ArgList &Args,
2071
0
                               ArgStringList &CmdArgs) const {
2072
0
  const llvm::Triple &Triple = getToolChain().getTriple();
2073
0
  StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2074
2075
0
  CmdArgs.push_back("-target-abi");
2076
0
  CmdArgs.push_back(ABIName.data());
2077
2078
0
  SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2079
2080
0
  if (!Args.hasFlag(options::OPT_mimplicit_float,
2081
0
                    options::OPT_mno_implicit_float, true))
2082
0
    CmdArgs.push_back("-no-implicit-float");
2083
2084
0
  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2085
0
    CmdArgs.push_back("-tune-cpu");
2086
0
    if (strcmp(A->getValue(), "native") == 0)
2087
0
      CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2088
0
    else
2089
0
      CmdArgs.push_back(A->getValue());
2090
0
  }
2091
2092
  // Handle -mrvv-vector-bits=<bits>
2093
0
  if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2094
0
    StringRef Val = A->getValue();
2095
0
    const Driver &D = getToolChain().getDriver();
2096
2097
    // Get minimum VLen from march.
2098
0
    unsigned MinVLen = 0;
2099
0
    StringRef Arch = riscv::getRISCVArch(Args, Triple);
2100
0
    auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2101
0
        Arch, /*EnableExperimentalExtensions*/ true);
2102
    // Ignore parsing error.
2103
0
    if (!errorToBool(ISAInfo.takeError()))
2104
0
      MinVLen = (*ISAInfo)->getMinVLen();
2105
2106
    // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2107
    // as integer as long as we have a MinVLen.
2108
0
    unsigned Bits = 0;
2109
0
    if (Val.equals("zvl") && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2110
0
      Bits = MinVLen;
2111
0
    } else if (!Val.getAsInteger(10, Bits)) {
2112
      // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2113
      // at least MinVLen.
2114
0
      if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2115
0
          Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2116
0
        Bits = 0;
2117
0
    }
2118
2119
    // If we got a valid value try to use it.
2120
0
    if (Bits != 0) {
2121
0
      unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2122
0
      CmdArgs.push_back(
2123
0
          Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2124
0
      CmdArgs.push_back(
2125
0
          Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2126
0
    } else if (!Val.equals("scalable")) {
2127
      // Handle the unsupported values passed to mrvv-vector-bits.
2128
0
      D.Diag(diag::err_drv_unsupported_option_argument)
2129
0
          << A->getSpelling() << Val;
2130
0
    }
2131
0
  }
2132
0
}
2133
2134
void Clang::AddSparcTargetArgs(const ArgList &Args,
2135
0
                               ArgStringList &CmdArgs) const {
2136
0
  sparc::FloatABI FloatABI =
2137
0
      sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2138
2139
0
  if (FloatABI == sparc::FloatABI::Soft) {
2140
    // Floating point operations and argument passing are soft.
2141
0
    CmdArgs.push_back("-msoft-float");
2142
0
    CmdArgs.push_back("-mfloat-abi");
2143
0
    CmdArgs.push_back("soft");
2144
0
  } else {
2145
    // Floating point operations and argument passing are hard.
2146
0
    assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2147
0
    CmdArgs.push_back("-mfloat-abi");
2148
0
    CmdArgs.push_back("hard");
2149
0
  }
2150
2151
0
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2152
0
    StringRef Name = A->getValue();
2153
0
    std::string TuneCPU;
2154
0
    if (Name == "native")
2155
0
      TuneCPU = std::string(llvm::sys::getHostCPUName());
2156
0
    else
2157
0
      TuneCPU = std::string(Name);
2158
2159
0
    CmdArgs.push_back("-tune-cpu");
2160
0
    CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2161
0
  }
2162
0
}
2163
2164
void Clang::AddSystemZTargetArgs(const ArgList &Args,
2165
0
                                 ArgStringList &CmdArgs) const {
2166
0
  if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2167
0
    CmdArgs.push_back("-tune-cpu");
2168
0
    if (strcmp(A->getValue(), "native") == 0)
2169
0
      CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2170
0
    else
2171
0
      CmdArgs.push_back(A->getValue());
2172
0
  }
2173
2174
0
  bool HasBackchain =
2175
0
      Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2176
0
  bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2177
0
                                     options::OPT_mno_packed_stack, false);
2178
0
  systemz::FloatABI FloatABI =
2179
0
      systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2180
0
  bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2181
0
  if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2182
0
    const Driver &D = getToolChain().getDriver();
2183
0
    D.Diag(diag::err_drv_unsupported_opt)
2184
0
      << "-mpacked-stack -mbackchain -mhard-float";
2185
0
  }
2186
0
  if (HasBackchain)
2187
0
    CmdArgs.push_back("-mbackchain");
2188
0
  if (HasPackedStack)
2189
0
    CmdArgs.push_back("-mpacked-stack");
2190
0
  if (HasSoftFloat) {
2191
    // Floating point operations and argument passing are soft.
2192
0
    CmdArgs.push_back("-msoft-float");
2193
0
    CmdArgs.push_back("-mfloat-abi");
2194
0
    CmdArgs.push_back("soft");
2195
0
  }
2196
0
}
2197
2198
void Clang::AddX86TargetArgs(const ArgList &Args,
2199
0
                             ArgStringList &CmdArgs) const {
2200
0
  const Driver &D = getToolChain().getDriver();
2201
0
  addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2202
2203
0
  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2204
0
      Args.hasArg(options::OPT_mkernel) ||
2205
0
      Args.hasArg(options::OPT_fapple_kext))
2206
0
    CmdArgs.push_back("-disable-red-zone");
2207
2208
0
  if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2209
0
                    options::OPT_mno_tls_direct_seg_refs, true))
2210
0
    CmdArgs.push_back("-mno-tls-direct-seg-refs");
2211
2212
  // Default to avoid implicit floating-point for kernel/kext code, but allow
2213
  // that to be overridden with -mno-soft-float.
2214
0
  bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2215
0
                          Args.hasArg(options::OPT_fapple_kext));
2216
0
  if (Arg *A = Args.getLastArg(
2217
0
          options::OPT_msoft_float, options::OPT_mno_soft_float,
2218
0
          options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2219
0
    const Option &O = A->getOption();
2220
0
    NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2221
0
                       O.matches(options::OPT_msoft_float));
2222
0
  }
2223
0
  if (NoImplicitFloat)
2224
0
    CmdArgs.push_back("-no-implicit-float");
2225
2226
0
  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2227
0
    StringRef Value = A->getValue();
2228
0
    if (Value == "intel" || Value == "att") {
2229
0
      CmdArgs.push_back("-mllvm");
2230
0
      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2231
0
      CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2232
0
    } else {
2233
0
      D.Diag(diag::err_drv_unsupported_option_argument)
2234
0
          << A->getSpelling() << Value;
2235
0
    }
2236
0
  } else if (D.IsCLMode()) {
2237
0
    CmdArgs.push_back("-mllvm");
2238
0
    CmdArgs.push_back("-x86-asm-syntax=intel");
2239
0
  }
2240
2241
0
  if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2242
0
                               options::OPT_mno_skip_rax_setup))
2243
0
    if (A->getOption().matches(options::OPT_mskip_rax_setup))
2244
0
      CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2245
2246
  // Set flags to support MCU ABI.
2247
0
  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2248
0
    CmdArgs.push_back("-mfloat-abi");
2249
0
    CmdArgs.push_back("soft");
2250
0
    CmdArgs.push_back("-mstack-alignment=4");
2251
0
  }
2252
2253
  // Handle -mtune.
2254
2255
  // Default to "generic" unless -march is present or targetting the PS4/PS5.
2256
0
  std::string TuneCPU;
2257
0
  if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2258
0
      !getToolChain().getTriple().isPS())
2259
0
    TuneCPU = "generic";
2260
2261
  // Override based on -mtune.
2262
0
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2263
0
    StringRef Name = A->getValue();
2264
2265
0
    if (Name == "native") {
2266
0
      Name = llvm::sys::getHostCPUName();
2267
0
      if (!Name.empty())
2268
0
        TuneCPU = std::string(Name);
2269
0
    } else
2270
0
      TuneCPU = std::string(Name);
2271
0
  }
2272
2273
0
  if (!TuneCPU.empty()) {
2274
0
    CmdArgs.push_back("-tune-cpu");
2275
0
    CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2276
0
  }
2277
0
}
2278
2279
void Clang::AddHexagonTargetArgs(const ArgList &Args,
2280
0
                                 ArgStringList &CmdArgs) const {
2281
0
  CmdArgs.push_back("-mqdsp6-compat");
2282
0
  CmdArgs.push_back("-Wreturn-type");
2283
2284
0
  if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2285
0
    CmdArgs.push_back("-mllvm");
2286
0
    CmdArgs.push_back(
2287
0
        Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2288
0
  }
2289
2290
0
  if (!Args.hasArg(options::OPT_fno_short_enums))
2291
0
    CmdArgs.push_back("-fshort-enums");
2292
0
  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2293
0
    CmdArgs.push_back("-mllvm");
2294
0
    CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2295
0
  }
2296
0
  CmdArgs.push_back("-mllvm");
2297
0
  CmdArgs.push_back("-machine-sink-split=0");
2298
0
}
2299
2300
void Clang::AddLanaiTargetArgs(const ArgList &Args,
2301
0
                               ArgStringList &CmdArgs) const {
2302
0
  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2303
0
    StringRef CPUName = A->getValue();
2304
2305
0
    CmdArgs.push_back("-target-cpu");
2306
0
    CmdArgs.push_back(Args.MakeArgString(CPUName));
2307
0
  }
2308
0
  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2309
0
    StringRef Value = A->getValue();
2310
    // Only support mregparm=4 to support old usage. Report error for all other
2311
    // cases.
2312
0
    int Mregparm;
2313
0
    if (Value.getAsInteger(10, Mregparm)) {
2314
0
      if (Mregparm != 4) {
2315
0
        getToolChain().getDriver().Diag(
2316
0
            diag::err_drv_unsupported_option_argument)
2317
0
            << A->getSpelling() << Value;
2318
0
      }
2319
0
    }
2320
0
  }
2321
0
}
2322
2323
void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2324
0
                                     ArgStringList &CmdArgs) const {
2325
  // Default to "hidden" visibility.
2326
0
  if (!Args.hasArg(options::OPT_fvisibility_EQ,
2327
0
                   options::OPT_fvisibility_ms_compat))
2328
0
    CmdArgs.push_back("-fvisibility=hidden");
2329
0
}
2330
2331
0
void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2332
  // Floating point operations and argument passing are hard.
2333
0
  CmdArgs.push_back("-mfloat-abi");
2334
0
  CmdArgs.push_back("hard");
2335
0
}
2336
2337
void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2338
                                    StringRef Target, const InputInfo &Output,
2339
0
                                    const InputInfo &Input, const ArgList &Args) const {
2340
  // If this is a dry run, do not create the compilation database file.
2341
0
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2342
0
    return;
2343
2344
0
  using llvm::yaml::escape;
2345
0
  const Driver &D = getToolChain().getDriver();
2346
2347
0
  if (!CompilationDatabase) {
2348
0
    std::error_code EC;
2349
0
    auto File = std::make_unique<llvm::raw_fd_ostream>(
2350
0
        Filename, EC,
2351
0
        llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2352
0
    if (EC) {
2353
0
      D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2354
0
                                                       << EC.message();
2355
0
      return;
2356
0
    }
2357
0
    CompilationDatabase = std::move(File);
2358
0
  }
2359
0
  auto &CDB = *CompilationDatabase;
2360
0
  auto CWD = D.getVFS().getCurrentWorkingDirectory();
2361
0
  if (!CWD)
2362
0
    CWD = ".";
2363
0
  CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2364
0
  CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2365
0
  if (Output.isFilename())
2366
0
    CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2367
0
  CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2368
0
  SmallString<128> Buf;
2369
0
  Buf = "-x";
2370
0
  Buf += types::getTypeName(Input.getType());
2371
0
  CDB << ", \"" << escape(Buf) << "\"";
2372
0
  if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2373
0
    Buf = "--sysroot=";
2374
0
    Buf += D.SysRoot;
2375
0
    CDB << ", \"" << escape(Buf) << "\"";
2376
0
  }
2377
0
  CDB << ", \"" << escape(Input.getFilename()) << "\"";
2378
0
  if (Output.isFilename())
2379
0
    CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2380
0
  for (auto &A: Args) {
2381
0
    auto &O = A->getOption();
2382
    // Skip language selection, which is positional.
2383
0
    if (O.getID() == options::OPT_x)
2384
0
      continue;
2385
    // Skip writing dependency output and the compilation database itself.
2386
0
    if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2387
0
      continue;
2388
0
    if (O.getID() == options::OPT_gen_cdb_fragment_path)
2389
0
      continue;
2390
    // Skip inputs.
2391
0
    if (O.getKind() == Option::InputClass)
2392
0
      continue;
2393
    // Skip output.
2394
0
    if (O.getID() == options::OPT_o)
2395
0
      continue;
2396
    // All other arguments are quoted and appended.
2397
0
    ArgStringList ASL;
2398
0
    A->render(Args, ASL);
2399
0
    for (auto &it: ASL)
2400
0
      CDB << ", \"" << escape(it) << "\"";
2401
0
  }
2402
0
  Buf = "--target=";
2403
0
  Buf += Target;
2404
0
  CDB << ", \"" << escape(Buf) << "\"]},\n";
2405
0
}
2406
2407
void Clang::DumpCompilationDatabaseFragmentToDir(
2408
    StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2409
0
    const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2410
  // If this is a dry run, do not create the compilation database file.
2411
0
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2412
0
    return;
2413
2414
0
  if (CompilationDatabase)
2415
0
    DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2416
2417
0
  SmallString<256> Path = Dir;
2418
0
  const auto &Driver = C.getDriver();
2419
0
  Driver.getVFS().makeAbsolute(Path);
2420
0
  auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2421
0
  if (Err) {
2422
0
    Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2423
0
    return;
2424
0
  }
2425
2426
0
  llvm::sys::path::append(
2427
0
      Path,
2428
0
      Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2429
0
  int FD;
2430
0
  SmallString<256> TempPath;
2431
0
  Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2432
0
                                        llvm::sys::fs::OF_Text);
2433
0
  if (Err) {
2434
0
    Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2435
0
    return;
2436
0
  }
2437
0
  CompilationDatabase =
2438
0
      std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2439
0
  DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2440
0
}
2441
2442
0
static bool CheckARMImplicitITArg(StringRef Value) {
2443
0
  return Value == "always" || Value == "never" || Value == "arm" ||
2444
0
         Value == "thumb";
2445
0
}
2446
2447
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2448
0
                                 StringRef Value) {
2449
0
  CmdArgs.push_back("-mllvm");
2450
0
  CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2451
0
}
2452
2453
static void CollectArgsForIntegratedAssembler(Compilation &C,
2454
                                              const ArgList &Args,
2455
                                              ArgStringList &CmdArgs,
2456
0
                                              const Driver &D) {
2457
0
  if (UseRelaxAll(C, Args))
2458
0
    CmdArgs.push_back("-mrelax-all");
2459
2460
  // Only default to -mincremental-linker-compatible if we think we are
2461
  // targeting the MSVC linker.
2462
0
  bool DefaultIncrementalLinkerCompatible =
2463
0
      C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2464
0
  if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2465
0
                   options::OPT_mno_incremental_linker_compatible,
2466
0
                   DefaultIncrementalLinkerCompatible))
2467
0
    CmdArgs.push_back("-mincremental-linker-compatible");
2468
2469
0
  Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2470
2471
0
  Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2472
0
                    options::OPT_fno_emit_compact_unwind_non_canonical);
2473
2474
  // If you add more args here, also add them to the block below that
2475
  // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2476
2477
  // When passing -I arguments to the assembler we sometimes need to
2478
  // unconditionally take the next argument.  For example, when parsing
2479
  // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2480
  // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2481
  // arg after parsing the '-I' arg.
2482
0
  bool TakeNextArg = false;
2483
2484
0
  bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2485
0
  bool UseNoExecStack = false;
2486
0
  const char *MipsTargetFeature = nullptr;
2487
0
  StringRef ImplicitIt;
2488
0
  for (const Arg *A :
2489
0
       Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2490
0
                     options::OPT_mimplicit_it_EQ)) {
2491
0
    A->claim();
2492
2493
0
    if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2494
0
      switch (C.getDefaultToolChain().getArch()) {
2495
0
      case llvm::Triple::arm:
2496
0
      case llvm::Triple::armeb:
2497
0
      case llvm::Triple::thumb:
2498
0
      case llvm::Triple::thumbeb:
2499
        // Only store the value; the last value set takes effect.
2500
0
        ImplicitIt = A->getValue();
2501
0
        if (!CheckARMImplicitITArg(ImplicitIt))
2502
0
          D.Diag(diag::err_drv_unsupported_option_argument)
2503
0
              << A->getSpelling() << ImplicitIt;
2504
0
        continue;
2505
0
      default:
2506
0
        break;
2507
0
      }
2508
0
    }
2509
2510
0
    for (StringRef Value : A->getValues()) {
2511
0
      if (TakeNextArg) {
2512
0
        CmdArgs.push_back(Value.data());
2513
0
        TakeNextArg = false;
2514
0
        continue;
2515
0
      }
2516
2517
0
      if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2518
0
          Value == "-mbig-obj")
2519
0
        continue; // LLVM handles bigobj automatically
2520
2521
0
      switch (C.getDefaultToolChain().getArch()) {
2522
0
      default:
2523
0
        break;
2524
0
      case llvm::Triple::wasm32:
2525
0
      case llvm::Triple::wasm64:
2526
0
        if (Value == "--no-type-check") {
2527
0
          CmdArgs.push_back("-mno-type-check");
2528
0
          continue;
2529
0
        }
2530
0
        break;
2531
0
      case llvm::Triple::thumb:
2532
0
      case llvm::Triple::thumbeb:
2533
0
      case llvm::Triple::arm:
2534
0
      case llvm::Triple::armeb:
2535
0
        if (Value.starts_with("-mimplicit-it=")) {
2536
          // Only store the value; the last value set takes effect.
2537
0
          ImplicitIt = Value.split("=").second;
2538
0
          if (CheckARMImplicitITArg(ImplicitIt))
2539
0
            continue;
2540
0
        }
2541
0
        if (Value == "-mthumb")
2542
          // -mthumb has already been processed in ComputeLLVMTriple()
2543
          // recognize but skip over here.
2544
0
          continue;
2545
0
        break;
2546
0
      case llvm::Triple::mips:
2547
0
      case llvm::Triple::mipsel:
2548
0
      case llvm::Triple::mips64:
2549
0
      case llvm::Triple::mips64el:
2550
0
        if (Value == "--trap") {
2551
0
          CmdArgs.push_back("-target-feature");
2552
0
          CmdArgs.push_back("+use-tcc-in-div");
2553
0
          continue;
2554
0
        }
2555
0
        if (Value == "--break") {
2556
0
          CmdArgs.push_back("-target-feature");
2557
0
          CmdArgs.push_back("-use-tcc-in-div");
2558
0
          continue;
2559
0
        }
2560
0
        if (Value.starts_with("-msoft-float")) {
2561
0
          CmdArgs.push_back("-target-feature");
2562
0
          CmdArgs.push_back("+soft-float");
2563
0
          continue;
2564
0
        }
2565
0
        if (Value.starts_with("-mhard-float")) {
2566
0
          CmdArgs.push_back("-target-feature");
2567
0
          CmdArgs.push_back("-soft-float");
2568
0
          continue;
2569
0
        }
2570
2571
0
        MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2572
0
                                .Case("-mips1", "+mips1")
2573
0
                                .Case("-mips2", "+mips2")
2574
0
                                .Case("-mips3", "+mips3")
2575
0
                                .Case("-mips4", "+mips4")
2576
0
                                .Case("-mips5", "+mips5")
2577
0
                                .Case("-mips32", "+mips32")
2578
0
                                .Case("-mips32r2", "+mips32r2")
2579
0
                                .Case("-mips32r3", "+mips32r3")
2580
0
                                .Case("-mips32r5", "+mips32r5")
2581
0
                                .Case("-mips32r6", "+mips32r6")
2582
0
                                .Case("-mips64", "+mips64")
2583
0
                                .Case("-mips64r2", "+mips64r2")
2584
0
                                .Case("-mips64r3", "+mips64r3")
2585
0
                                .Case("-mips64r5", "+mips64r5")
2586
0
                                .Case("-mips64r6", "+mips64r6")
2587
0
                                .Default(nullptr);
2588
0
        if (MipsTargetFeature)
2589
0
          continue;
2590
0
      }
2591
2592
0
      if (Value == "-force_cpusubtype_ALL") {
2593
        // Do nothing, this is the default and we don't support anything else.
2594
0
      } else if (Value == "-L") {
2595
0
        CmdArgs.push_back("-msave-temp-labels");
2596
0
      } else if (Value == "--fatal-warnings") {
2597
0
        CmdArgs.push_back("-massembler-fatal-warnings");
2598
0
      } else if (Value == "--no-warn" || Value == "-W") {
2599
0
        CmdArgs.push_back("-massembler-no-warn");
2600
0
      } else if (Value == "--noexecstack") {
2601
0
        UseNoExecStack = true;
2602
0
      } else if (Value.starts_with("-compress-debug-sections") ||
2603
0
                 Value.starts_with("--compress-debug-sections") ||
2604
0
                 Value == "-nocompress-debug-sections" ||
2605
0
                 Value == "--nocompress-debug-sections") {
2606
0
        CmdArgs.push_back(Value.data());
2607
0
      } else if (Value == "-mrelax-relocations=yes" ||
2608
0
                 Value == "--mrelax-relocations=yes") {
2609
0
        UseRelaxRelocations = true;
2610
0
      } else if (Value == "-mrelax-relocations=no" ||
2611
0
                 Value == "--mrelax-relocations=no") {
2612
0
        UseRelaxRelocations = false;
2613
0
      } else if (Value.starts_with("-I")) {
2614
0
        CmdArgs.push_back(Value.data());
2615
        // We need to consume the next argument if the current arg is a plain
2616
        // -I. The next arg will be the include directory.
2617
0
        if (Value == "-I")
2618
0
          TakeNextArg = true;
2619
0
      } else if (Value.starts_with("-gdwarf-")) {
2620
        // "-gdwarf-N" options are not cc1as options.
2621
0
        unsigned DwarfVersion = DwarfVersionNum(Value);
2622
0
        if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2623
0
          CmdArgs.push_back(Value.data());
2624
0
        } else {
2625
0
          RenderDebugEnablingArgs(Args, CmdArgs,
2626
0
                                  llvm::codegenoptions::DebugInfoConstructor,
2627
0
                                  DwarfVersion, llvm::DebuggerKind::Default);
2628
0
        }
2629
0
      } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2630
0
                 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2631
        // Do nothing, we'll validate it later.
2632
0
      } else if (Value == "-defsym") {
2633
0
        if (A->getNumValues() != 2) {
2634
0
          D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2635
0
          break;
2636
0
        }
2637
0
        const char *S = A->getValue(1);
2638
0
        auto Pair = StringRef(S).split('=');
2639
0
        auto Sym = Pair.first;
2640
0
        auto SVal = Pair.second;
2641
2642
0
        if (Sym.empty() || SVal.empty()) {
2643
0
          D.Diag(diag::err_drv_defsym_invalid_format) << S;
2644
0
          break;
2645
0
        }
2646
0
        int64_t IVal;
2647
0
        if (SVal.getAsInteger(0, IVal)) {
2648
0
          D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2649
0
          break;
2650
0
        }
2651
0
        CmdArgs.push_back(Value.data());
2652
0
        TakeNextArg = true;
2653
0
      } else if (Value == "-fdebug-compilation-dir") {
2654
0
        CmdArgs.push_back("-fdebug-compilation-dir");
2655
0
        TakeNextArg = true;
2656
0
      } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2657
        // The flag is a -Wa / -Xassembler argument and Options doesn't
2658
        // parse the argument, so this isn't automatically aliased to
2659
        // -fdebug-compilation-dir (without '=') here.
2660
0
        CmdArgs.push_back("-fdebug-compilation-dir");
2661
0
        CmdArgs.push_back(Value.data());
2662
0
      } else if (Value == "--version") {
2663
0
        D.PrintVersion(C, llvm::outs());
2664
0
      } else {
2665
0
        D.Diag(diag::err_drv_unsupported_option_argument)
2666
0
            << A->getSpelling() << Value;
2667
0
      }
2668
0
    }
2669
0
  }
2670
0
  if (ImplicitIt.size())
2671
0
    AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2672
0
  if (!UseRelaxRelocations)
2673
0
    CmdArgs.push_back("-mrelax-relocations=no");
2674
0
  if (UseNoExecStack)
2675
0
    CmdArgs.push_back("-mnoexecstack");
2676
0
  if (MipsTargetFeature != nullptr) {
2677
0
    CmdArgs.push_back("-target-feature");
2678
0
    CmdArgs.push_back(MipsTargetFeature);
2679
0
  }
2680
2681
  // forward -fembed-bitcode to assmebler
2682
0
  if (C.getDriver().embedBitcodeEnabled() ||
2683
0
      C.getDriver().embedBitcodeMarkerOnly())
2684
0
    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2685
2686
0
  if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2687
0
    CmdArgs.push_back("-as-secure-log-file");
2688
0
    CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2689
0
  }
2690
0
}
2691
2692
0
static StringRef EnumComplexRangeToStr(LangOptions::ComplexRangeKind Range) {
2693
0
  StringRef RangeStr = "";
2694
0
  switch (Range) {
2695
0
  case LangOptions::ComplexRangeKind::CX_Limited:
2696
0
    return "-fcx-limited-range";
2697
0
    break;
2698
0
  case LangOptions::ComplexRangeKind::CX_Fortran:
2699
0
    return "-fcx-fortran-rules";
2700
0
    break;
2701
0
  default:
2702
0
    return RangeStr;
2703
0
    break;
2704
0
  }
2705
0
}
2706
2707
static void EmitComplexRangeDiag(const Driver &D,
2708
                                 LangOptions::ComplexRangeKind Range1,
2709
0
                                 LangOptions::ComplexRangeKind Range2) {
2710
0
  if (Range1 != LangOptions::ComplexRangeKind::CX_Full)
2711
0
    D.Diag(clang::diag::warn_drv_overriding_option)
2712
0
        << EnumComplexRangeToStr(Range1) << EnumComplexRangeToStr(Range2);
2713
0
}
2714
2715
0
static std::string RenderComplexRangeOption(std::string Range) {
2716
0
  std::string ComplexRangeStr = "-complex-range=";
2717
0
  ComplexRangeStr += Range;
2718
0
  return ComplexRangeStr;
2719
0
}
2720
2721
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2722
                                       bool OFastEnabled, const ArgList &Args,
2723
                                       ArgStringList &CmdArgs,
2724
0
                                       const JobAction &JA) {
2725
  // Handle various floating point optimization flags, mapping them to the
2726
  // appropriate LLVM code generation flags. This is complicated by several
2727
  // "umbrella" flags, so we do this by stepping through the flags incrementally
2728
  // adjusting what we think is enabled/disabled, then at the end setting the
2729
  // LLVM flags based on the final state.
2730
0
  bool HonorINFs = true;
2731
0
  bool HonorNaNs = true;
2732
0
  bool ApproxFunc = false;
2733
  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2734
0
  bool MathErrno = TC.IsMathErrnoDefault();
2735
0
  bool AssociativeMath = false;
2736
0
  bool ReciprocalMath = false;
2737
0
  bool SignedZeros = true;
2738
0
  bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2739
0
  bool TrappingMathPresent = false; // Is trapping-math in args, and not
2740
                                    // overriden by ffp-exception-behavior?
2741
0
  bool RoundingFPMath = false;
2742
0
  bool RoundingMathPresent = false; // Is rounding-math in args?
2743
  // -ffp-model values: strict, fast, precise
2744
0
  StringRef FPModel = "";
2745
  // -ffp-exception-behavior options: strict, maytrap, ignore
2746
0
  StringRef FPExceptionBehavior = "";
2747
  // -ffp-eval-method options: double, extended, source
2748
0
  StringRef FPEvalMethod = "";
2749
0
  const llvm::DenormalMode DefaultDenormalFPMath =
2750
0
      TC.getDefaultDenormalModeForType(Args, JA);
2751
0
  const llvm::DenormalMode DefaultDenormalFP32Math =
2752
0
      TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2753
2754
0
  llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2755
0
  llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2756
  // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2757
  // If one wasn't given by the user, don't pass it here.
2758
0
  StringRef FPContract;
2759
0
  StringRef LastSeenFfpContractOption;
2760
0
  bool SeenUnsafeMathModeOption = false;
2761
0
  if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2762
0
      !JA.isOffloading(Action::OFK_HIP))
2763
0
    FPContract = "on";
2764
0
  bool StrictFPModel = false;
2765
0
  StringRef Float16ExcessPrecision = "";
2766
0
  StringRef BFloat16ExcessPrecision = "";
2767
0
  LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_Full;
2768
2769
0
  if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2770
0
    CmdArgs.push_back("-mlimit-float-precision");
2771
0
    CmdArgs.push_back(A->getValue());
2772
0
  }
2773
2774
0
  for (const Arg *A : Args) {
2775
0
    auto optID = A->getOption().getID();
2776
0
    bool PreciseFPModel = false;
2777
0
    switch (optID) {
2778
0
    default:
2779
0
      break;
2780
0
    case options::OPT_fcx_limited_range: {
2781
0
      EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Limited);
2782
0
      Range = LangOptions::ComplexRangeKind::CX_Limited;
2783
0
      std::string ComplexRangeStr = RenderComplexRangeOption("limited");
2784
0
      if (!ComplexRangeStr.empty())
2785
0
        CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
2786
0
      break;
2787
0
    }
2788
0
    case options::OPT_fno_cx_limited_range:
2789
0
      Range = LangOptions::ComplexRangeKind::CX_Full;
2790
0
      break;
2791
0
    case options::OPT_fcx_fortran_rules: {
2792
0
      EmitComplexRangeDiag(D, Range, LangOptions::ComplexRangeKind::CX_Fortran);
2793
0
      Range = LangOptions::ComplexRangeKind::CX_Fortran;
2794
0
      std::string ComplexRangeStr = RenderComplexRangeOption("fortran");
2795
0
      if (!ComplexRangeStr.empty())
2796
0
        CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
2797
0
      break;
2798
0
    }
2799
0
    case options::OPT_fno_cx_fortran_rules:
2800
0
      Range = LangOptions::ComplexRangeKind::CX_Full;
2801
0
      break;
2802
0
    case options::OPT_ffp_model_EQ: {
2803
      // If -ffp-model= is seen, reset to fno-fast-math
2804
0
      HonorINFs = true;
2805
0
      HonorNaNs = true;
2806
0
      ApproxFunc = false;
2807
      // Turning *off* -ffast-math restores the toolchain default.
2808
0
      MathErrno = TC.IsMathErrnoDefault();
2809
0
      AssociativeMath = false;
2810
0
      ReciprocalMath = false;
2811
0
      SignedZeros = true;
2812
      // -fno_fast_math restores default denormal and fpcontract handling
2813
0
      FPContract = "on";
2814
0
      DenormalFPMath = llvm::DenormalMode::getIEEE();
2815
2816
      // FIXME: The target may have picked a non-IEEE default mode here based on
2817
      // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2818
0
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
2819
2820
0
      StringRef Val = A->getValue();
2821
0
      if (OFastEnabled && !Val.equals("fast")) {
2822
          // Only -ffp-model=fast is compatible with OFast, ignore.
2823
0
        D.Diag(clang::diag::warn_drv_overriding_option)
2824
0
            << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
2825
0
        break;
2826
0
      }
2827
0
      StrictFPModel = false;
2828
0
      PreciseFPModel = true;
2829
      // ffp-model= is a Driver option, it is entirely rewritten into more
2830
      // granular options before being passed into cc1.
2831
      // Use the gcc option in the switch below.
2832
0
      if (!FPModel.empty() && !FPModel.equals(Val))
2833
0
        D.Diag(clang::diag::warn_drv_overriding_option)
2834
0
            << Args.MakeArgString("-ffp-model=" + FPModel)
2835
0
            << Args.MakeArgString("-ffp-model=" + Val);
2836
0
      if (Val.equals("fast")) {
2837
0
        optID = options::OPT_ffast_math;
2838
0
        FPModel = Val;
2839
0
        FPContract = "fast";
2840
0
      } else if (Val.equals("precise")) {
2841
0
        optID = options::OPT_ffp_contract;
2842
0
        FPModel = Val;
2843
0
        FPContract = "on";
2844
0
        PreciseFPModel = true;
2845
0
      } else if (Val.equals("strict")) {
2846
0
        StrictFPModel = true;
2847
0
        optID = options::OPT_frounding_math;
2848
0
        FPExceptionBehavior = "strict";
2849
0
        FPModel = Val;
2850
0
        FPContract = "off";
2851
0
        TrappingMath = true;
2852
0
      } else
2853
0
        D.Diag(diag::err_drv_unsupported_option_argument)
2854
0
            << A->getSpelling() << Val;
2855
0
      break;
2856
0
    }
2857
0
    }
2858
2859
0
    switch (optID) {
2860
    // If this isn't an FP option skip the claim below
2861
0
    default: continue;
2862
2863
    // Options controlling individual features
2864
0
    case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2865
0
    case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2866
0
    case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2867
0
    case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2868
0
    case options::OPT_fapprox_func:         ApproxFunc = true;        break;
2869
0
    case options::OPT_fno_approx_func:      ApproxFunc = false;       break;
2870
0
    case options::OPT_fmath_errno:          MathErrno = true;         break;
2871
0
    case options::OPT_fno_math_errno:       MathErrno = false;        break;
2872
0
    case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2873
0
    case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2874
0
    case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2875
0
    case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2876
0
    case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2877
0
    case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2878
0
    case options::OPT_ftrapping_math:
2879
0
      if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2880
0
          !FPExceptionBehavior.equals("strict"))
2881
        // Warn that previous value of option is overridden.
2882
0
        D.Diag(clang::diag::warn_drv_overriding_option)
2883
0
            << Args.MakeArgString("-ffp-exception-behavior=" +
2884
0
                                  FPExceptionBehavior)
2885
0
            << "-ftrapping-math";
2886
0
      TrappingMath = true;
2887
0
      TrappingMathPresent = true;
2888
0
      FPExceptionBehavior = "strict";
2889
0
      break;
2890
0
    case options::OPT_fno_trapping_math:
2891
0
      if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2892
0
          !FPExceptionBehavior.equals("ignore"))
2893
        // Warn that previous value of option is overridden.
2894
0
        D.Diag(clang::diag::warn_drv_overriding_option)
2895
0
            << Args.MakeArgString("-ffp-exception-behavior=" +
2896
0
                                  FPExceptionBehavior)
2897
0
            << "-fno-trapping-math";
2898
0
      TrappingMath = false;
2899
0
      TrappingMathPresent = true;
2900
0
      FPExceptionBehavior = "ignore";
2901
0
      break;
2902
2903
0
    case options::OPT_frounding_math:
2904
0
      RoundingFPMath = true;
2905
0
      RoundingMathPresent = true;
2906
0
      break;
2907
2908
0
    case options::OPT_fno_rounding_math:
2909
0
      RoundingFPMath = false;
2910
0
      RoundingMathPresent = false;
2911
0
      break;
2912
2913
0
    case options::OPT_fdenormal_fp_math_EQ:
2914
0
      DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2915
0
      DenormalFP32Math = DenormalFPMath;
2916
0
      if (!DenormalFPMath.isValid()) {
2917
0
        D.Diag(diag::err_drv_invalid_value)
2918
0
            << A->getAsString(Args) << A->getValue();
2919
0
      }
2920
0
      break;
2921
2922
0
    case options::OPT_fdenormal_fp_math_f32_EQ:
2923
0
      DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2924
0
      if (!DenormalFP32Math.isValid()) {
2925
0
        D.Diag(diag::err_drv_invalid_value)
2926
0
            << A->getAsString(Args) << A->getValue();
2927
0
      }
2928
0
      break;
2929
2930
    // Validate and pass through -ffp-contract option.
2931
0
    case options::OPT_ffp_contract: {
2932
0
      StringRef Val = A->getValue();
2933
0
      if (PreciseFPModel) {
2934
        // -ffp-model=precise enables ffp-contract=on.
2935
        // -ffp-model=precise sets PreciseFPModel to on and Val to
2936
        // "precise". FPContract is set.
2937
0
        ;
2938
0
      } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off") ||
2939
0
                 Val.equals("fast-honor-pragmas")) {
2940
0
        FPContract = Val;
2941
0
        LastSeenFfpContractOption = Val;
2942
0
      } else
2943
0
        D.Diag(diag::err_drv_unsupported_option_argument)
2944
0
            << A->getSpelling() << Val;
2945
0
      break;
2946
0
    }
2947
2948
    // Validate and pass through -ffp-model option.
2949
0
    case options::OPT_ffp_model_EQ:
2950
      // This should only occur in the error case
2951
      // since the optID has been replaced by a more granular
2952
      // floating point option.
2953
0
      break;
2954
2955
    // Validate and pass through -ffp-exception-behavior option.
2956
0
    case options::OPT_ffp_exception_behavior_EQ: {
2957
0
      StringRef Val = A->getValue();
2958
0
      if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2959
0
          !FPExceptionBehavior.equals(Val))
2960
        // Warn that previous value of option is overridden.
2961
0
        D.Diag(clang::diag::warn_drv_overriding_option)
2962
0
            << Args.MakeArgString("-ffp-exception-behavior=" +
2963
0
                                  FPExceptionBehavior)
2964
0
            << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2965
0
      TrappingMath = TrappingMathPresent = false;
2966
0
      if (Val.equals("ignore") || Val.equals("maytrap"))
2967
0
        FPExceptionBehavior = Val;
2968
0
      else if (Val.equals("strict")) {
2969
0
        FPExceptionBehavior = Val;
2970
0
        TrappingMath = TrappingMathPresent = true;
2971
0
      } else
2972
0
        D.Diag(diag::err_drv_unsupported_option_argument)
2973
0
            << A->getSpelling() << Val;
2974
0
      break;
2975
0
    }
2976
2977
    // Validate and pass through -ffp-eval-method option.
2978
0
    case options::OPT_ffp_eval_method_EQ: {
2979
0
      StringRef Val = A->getValue();
2980
0
      if (Val.equals("double") || Val.equals("extended") ||
2981
0
          Val.equals("source"))
2982
0
        FPEvalMethod = Val;
2983
0
      else
2984
0
        D.Diag(diag::err_drv_unsupported_option_argument)
2985
0
            << A->getSpelling() << Val;
2986
0
      break;
2987
0
    }
2988
2989
0
    case options::OPT_fexcess_precision_EQ: {
2990
0
      StringRef Val = A->getValue();
2991
0
      const llvm::Triple::ArchType Arch = TC.getArch();
2992
0
      if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
2993
0
        if (Val.equals("standard") || Val.equals("fast"))
2994
0
          Float16ExcessPrecision = Val;
2995
        // To make it GCC compatible, allow the value of "16" which
2996
        // means disable excess precision, the same meaning than clang's
2997
        // equivalent value "none".
2998
0
        else if (Val.equals("16"))
2999
0
          Float16ExcessPrecision = "none";
3000
0
        else
3001
0
          D.Diag(diag::err_drv_unsupported_option_argument)
3002
0
              << A->getSpelling() << Val;
3003
0
      } else {
3004
0
        if (!(Val.equals("standard") || Val.equals("fast")))
3005
0
          D.Diag(diag::err_drv_unsupported_option_argument)
3006
0
              << A->getSpelling() << Val;
3007
0
      }
3008
0
      BFloat16ExcessPrecision = Float16ExcessPrecision;
3009
0
      break;
3010
0
    }
3011
0
    case options::OPT_ffinite_math_only:
3012
0
      HonorINFs = false;
3013
0
      HonorNaNs = false;
3014
0
      break;
3015
0
    case options::OPT_fno_finite_math_only:
3016
0
      HonorINFs = true;
3017
0
      HonorNaNs = true;
3018
0
      break;
3019
3020
0
    case options::OPT_funsafe_math_optimizations:
3021
0
      AssociativeMath = true;
3022
0
      ReciprocalMath = true;
3023
0
      SignedZeros = false;
3024
0
      ApproxFunc = true;
3025
0
      TrappingMath = false;
3026
0
      FPExceptionBehavior = "";
3027
0
      FPContract = "fast";
3028
0
      SeenUnsafeMathModeOption = true;
3029
0
      break;
3030
0
    case options::OPT_fno_unsafe_math_optimizations:
3031
0
      AssociativeMath = false;
3032
0
      ReciprocalMath = false;
3033
0
      SignedZeros = true;
3034
0
      ApproxFunc = false;
3035
0
      TrappingMath = true;
3036
0
      FPExceptionBehavior = "strict";
3037
3038
      // The target may have opted to flush by default, so force IEEE.
3039
0
      DenormalFPMath = llvm::DenormalMode::getIEEE();
3040
0
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
3041
0
      if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3042
0
          !JA.isOffloading(Action::OFK_HIP)) {
3043
0
        if (LastSeenFfpContractOption != "") {
3044
0
          FPContract = LastSeenFfpContractOption;
3045
0
        } else if (SeenUnsafeMathModeOption)
3046
0
          FPContract = "on";
3047
0
      }
3048
0
      break;
3049
3050
0
    case options::OPT_Ofast:
3051
      // If -Ofast is the optimization level, then -ffast-math should be enabled
3052
0
      if (!OFastEnabled)
3053
0
        continue;
3054
0
      [[fallthrough]];
3055
0
    case options::OPT_ffast_math: {
3056
0
      HonorINFs = false;
3057
0
      HonorNaNs = false;
3058
0
      MathErrno = false;
3059
0
      AssociativeMath = true;
3060
0
      ReciprocalMath = true;
3061
0
      ApproxFunc = true;
3062
0
      SignedZeros = false;
3063
0
      TrappingMath = false;
3064
0
      RoundingFPMath = false;
3065
0
      FPExceptionBehavior = "";
3066
      // If fast-math is set then set the fp-contract mode to fast.
3067
0
      FPContract = "fast";
3068
0
      SeenUnsafeMathModeOption = true;
3069
      // ffast-math enables fortran rules for complex multiplication and
3070
      // division.
3071
0
      std::string ComplexRangeStr = RenderComplexRangeOption("limited");
3072
0
      if (!ComplexRangeStr.empty())
3073
0
        CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3074
0
      break;
3075
0
    }
3076
0
    case options::OPT_fno_fast_math:
3077
0
      HonorINFs = true;
3078
0
      HonorNaNs = true;
3079
      // Turning on -ffast-math (with either flag) removes the need for
3080
      // MathErrno. However, turning *off* -ffast-math merely restores the
3081
      // toolchain default (which may be false).
3082
0
      MathErrno = TC.IsMathErrnoDefault();
3083
0
      AssociativeMath = false;
3084
0
      ReciprocalMath = false;
3085
0
      ApproxFunc = false;
3086
0
      SignedZeros = true;
3087
      // -fno_fast_math restores default denormal and fpcontract handling
3088
0
      DenormalFPMath = DefaultDenormalFPMath;
3089
0
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
3090
0
      if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3091
0
          !JA.isOffloading(Action::OFK_HIP)) {
3092
0
        if (LastSeenFfpContractOption != "") {
3093
0
          FPContract = LastSeenFfpContractOption;
3094
0
        } else if (SeenUnsafeMathModeOption)
3095
0
          FPContract = "on";
3096
0
      }
3097
0
      break;
3098
0
    }
3099
0
    if (StrictFPModel) {
3100
      // If -ffp-model=strict has been specified on command line but
3101
      // subsequent options conflict then emit warning diagnostic.
3102
0
      if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3103
0
          SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3104
0
          DenormalFPMath == llvm::DenormalMode::getIEEE() &&
3105
0
          DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
3106
0
          FPContract.equals("off"))
3107
        // OK: Current Arg doesn't conflict with -ffp-model=strict
3108
0
        ;
3109
0
      else {
3110
0
        StrictFPModel = false;
3111
0
        FPModel = "";
3112
0
        auto RHS = (A->getNumValues() == 0)
3113
0
                       ? A->getSpelling()
3114
0
                       : Args.MakeArgString(A->getSpelling() + A->getValue());
3115
0
        if (RHS != "-ffp-model=strict")
3116
0
          D.Diag(clang::diag::warn_drv_overriding_option)
3117
0
              << "-ffp-model=strict" << RHS;
3118
0
      }
3119
0
    }
3120
3121
    // If we handled this option claim it
3122
0
    A->claim();
3123
0
  }
3124
3125
0
  if (!HonorINFs)
3126
0
    CmdArgs.push_back("-menable-no-infs");
3127
3128
0
  if (!HonorNaNs)
3129
0
    CmdArgs.push_back("-menable-no-nans");
3130
3131
0
  if (ApproxFunc)
3132
0
    CmdArgs.push_back("-fapprox-func");
3133
3134
0
  if (MathErrno)
3135
0
    CmdArgs.push_back("-fmath-errno");
3136
3137
0
 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3138
0
     !TrappingMath)
3139
0
    CmdArgs.push_back("-funsafe-math-optimizations");
3140
3141
0
  if (!SignedZeros)
3142
0
    CmdArgs.push_back("-fno-signed-zeros");
3143
3144
0
  if (AssociativeMath && !SignedZeros && !TrappingMath)
3145
0
    CmdArgs.push_back("-mreassociate");
3146
3147
0
  if (ReciprocalMath)
3148
0
    CmdArgs.push_back("-freciprocal-math");
3149
3150
0
  if (TrappingMath) {
3151
    // FP Exception Behavior is also set to strict
3152
0
    assert(FPExceptionBehavior.equals("strict"));
3153
0
  }
3154
3155
  // The default is IEEE.
3156
0
  if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3157
0
    llvm::SmallString<64> DenormFlag;
3158
0
    llvm::raw_svector_ostream ArgStr(DenormFlag);
3159
0
    ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3160
0
    CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3161
0
  }
3162
3163
  // Add f32 specific denormal mode flag if it's different.
3164
0
  if (DenormalFP32Math != DenormalFPMath) {
3165
0
    llvm::SmallString<64> DenormFlag;
3166
0
    llvm::raw_svector_ostream ArgStr(DenormFlag);
3167
0
    ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3168
0
    CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3169
0
  }
3170
3171
0
  if (!FPContract.empty())
3172
0
    CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3173
3174
0
  if (!RoundingFPMath)
3175
0
    CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3176
3177
0
  if (RoundingFPMath && RoundingMathPresent)
3178
0
    CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3179
3180
0
  if (!FPExceptionBehavior.empty())
3181
0
    CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3182
0
                      FPExceptionBehavior));
3183
3184
0
  if (!FPEvalMethod.empty())
3185
0
    CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3186
3187
0
  if (!Float16ExcessPrecision.empty())
3188
0
    CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3189
0
                                         Float16ExcessPrecision));
3190
0
  if (!BFloat16ExcessPrecision.empty())
3191
0
    CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3192
0
                                         BFloat16ExcessPrecision));
3193
3194
0
  ParseMRecip(D, Args, CmdArgs);
3195
3196
  // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3197
  // individual features enabled by -ffast-math instead of the option itself as
3198
  // that's consistent with gcc's behaviour.
3199
0
  if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3200
0
      ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
3201
0
    CmdArgs.push_back("-ffast-math");
3202
0
    if (FPModel.equals("fast")) {
3203
0
      if (FPContract.equals("fast"))
3204
        // All set, do nothing.
3205
0
        ;
3206
0
      else if (FPContract.empty())
3207
        // Enable -ffp-contract=fast
3208
0
        CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3209
0
      else
3210
0
        D.Diag(clang::diag::warn_drv_overriding_option)
3211
0
            << "-ffp-model=fast"
3212
0
            << Args.MakeArgString("-ffp-contract=" + FPContract);
3213
0
    }
3214
0
  }
3215
3216
  // Handle __FINITE_MATH_ONLY__ similarly.
3217
0
  if (!HonorINFs && !HonorNaNs)
3218
0
    CmdArgs.push_back("-ffinite-math-only");
3219
3220
0
  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3221
0
    CmdArgs.push_back("-mfpmath");
3222
0
    CmdArgs.push_back(A->getValue());
3223
0
  }
3224
3225
  // Disable a codegen optimization for floating-point casts.
3226
0
  if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3227
0
                   options::OPT_fstrict_float_cast_overflow, false))
3228
0
    CmdArgs.push_back("-fno-strict-float-cast-overflow");
3229
3230
0
  if (Args.hasArg(options::OPT_fcx_limited_range))
3231
0
    CmdArgs.push_back("-fcx-limited-range");
3232
0
  if (Args.hasArg(options::OPT_fcx_fortran_rules))
3233
0
    CmdArgs.push_back("-fcx-fortran-rules");
3234
0
  if (Args.hasArg(options::OPT_fno_cx_limited_range))
3235
0
    CmdArgs.push_back("-fno-cx-limited-range");
3236
0
  if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3237
0
    CmdArgs.push_back("-fno-cx-fortran-rules");
3238
0
}
3239
3240
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3241
                                  const llvm::Triple &Triple,
3242
0
                                  const InputInfo &Input) {
3243
  // Add default argument set.
3244
0
  if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3245
0
    CmdArgs.push_back("-analyzer-checker=core");
3246
0
    CmdArgs.push_back("-analyzer-checker=apiModeling");
3247
3248
0
    if (!Triple.isWindowsMSVCEnvironment()) {
3249
0
      CmdArgs.push_back("-analyzer-checker=unix");
3250
0
    } else {
3251
      // Enable "unix" checkers that also work on Windows.
3252
0
      CmdArgs.push_back("-analyzer-checker=unix.API");
3253
0
      CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3254
0
      CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3255
0
      CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3256
0
      CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3257
0
      CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3258
0
    }
3259
3260
    // Disable some unix checkers for PS4/PS5.
3261
0
    if (Triple.isPS()) {
3262
0
      CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3263
0
      CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3264
0
    }
3265
3266
0
    if (Triple.isOSDarwin()) {
3267
0
      CmdArgs.push_back("-analyzer-checker=osx");
3268
0
      CmdArgs.push_back(
3269
0
          "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3270
0
    }
3271
0
    else if (Triple.isOSFuchsia())
3272
0
      CmdArgs.push_back("-analyzer-checker=fuchsia");
3273
3274
0
    CmdArgs.push_back("-analyzer-checker=deadcode");
3275
3276
0
    if (types::isCXX(Input.getType()))
3277
0
      CmdArgs.push_back("-analyzer-checker=cplusplus");
3278
3279
0
    if (!Triple.isPS()) {
3280
0
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3281
0
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3282
0
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3283
0
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3284
0
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3285
0
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3286
0
    }
3287
3288
    // Default nullability checks.
3289
0
    CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3290
0
    CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3291
0
  }
3292
3293
  // Set the output format. The default is plist, for (lame) historical reasons.
3294
0
  CmdArgs.push_back("-analyzer-output");
3295
0
  if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3296
0
    CmdArgs.push_back(A->getValue());
3297
0
  else
3298
0
    CmdArgs.push_back("plist");
3299
3300
  // Disable the presentation of standard compiler warnings when using
3301
  // --analyze.  We only want to show static analyzer diagnostics or frontend
3302
  // errors.
3303
0
  CmdArgs.push_back("-w");
3304
3305
  // Add -Xanalyzer arguments when running as analyzer.
3306
0
  Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3307
0
}
3308
3309
0
static bool isValidSymbolName(StringRef S) {
3310
0
  if (S.empty())
3311
0
    return false;
3312
3313
0
  if (std::isdigit(S[0]))
3314
0
    return false;
3315
3316
0
  return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3317
0
}
3318
3319
static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3320
                             const ArgList &Args, ArgStringList &CmdArgs,
3321
0
                             bool KernelOrKext) {
3322
0
  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3323
3324
  // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3325
  // doesn't even have a stack!
3326
0
  if (EffectiveTriple.isNVPTX())
3327
0
    return;
3328
3329
  // -stack-protector=0 is default.
3330
0
  LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3331
0
  LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3332
0
      TC.GetDefaultStackProtectorLevel(KernelOrKext);
3333
3334
0
  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3335
0
                               options::OPT_fstack_protector_all,
3336
0
                               options::OPT_fstack_protector_strong,
3337
0
                               options::OPT_fstack_protector)) {
3338
0
    if (A->getOption().matches(options::OPT_fstack_protector))
3339
0
      StackProtectorLevel =
3340
0
          std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3341
0
    else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3342
0
      StackProtectorLevel = LangOptions::SSPStrong;
3343
0
    else if (A->getOption().matches(options::OPT_fstack_protector_all))
3344
0
      StackProtectorLevel = LangOptions::SSPReq;
3345
3346
0
    if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3347
0
      D.Diag(diag::warn_drv_unsupported_option_for_target)
3348
0
          << A->getSpelling() << EffectiveTriple.getTriple();
3349
0
      StackProtectorLevel = DefaultStackProtectorLevel;
3350
0
    }
3351
0
  } else {
3352
0
    StackProtectorLevel = DefaultStackProtectorLevel;
3353
0
  }
3354
3355
0
  if (StackProtectorLevel) {
3356
0
    CmdArgs.push_back("-stack-protector");
3357
0
    CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3358
0
  }
3359
3360
  // --param ssp-buffer-size=
3361
0
  for (const Arg *A : Args.filtered(options::OPT__param)) {
3362
0
    StringRef Str(A->getValue());
3363
0
    if (Str.starts_with("ssp-buffer-size=")) {
3364
0
      if (StackProtectorLevel) {
3365
0
        CmdArgs.push_back("-stack-protector-buffer-size");
3366
        // FIXME: Verify the argument is a valid integer.
3367
0
        CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3368
0
      }
3369
0
      A->claim();
3370
0
    }
3371
0
  }
3372
3373
0
  const std::string &TripleStr = EffectiveTriple.getTriple();
3374
0
  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3375
0
    StringRef Value = A->getValue();
3376
0
    if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3377
0
        !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3378
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
3379
0
          << A->getAsString(Args) << TripleStr;
3380
0
    if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3381
0
         EffectiveTriple.isThumb()) &&
3382
0
        Value != "tls" && Value != "global") {
3383
0
      D.Diag(diag::err_drv_invalid_value_with_suggestion)
3384
0
          << A->getOption().getName() << Value << "tls global";
3385
0
      return;
3386
0
    }
3387
0
    if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3388
0
        Value == "tls") {
3389
0
      if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3390
0
        D.Diag(diag::err_drv_ssp_missing_offset_argument)
3391
0
            << A->getAsString(Args);
3392
0
        return;
3393
0
      }
3394
      // Check whether the target subarch supports the hardware TLS register
3395
0
      if (!arm::isHardTPSupported(EffectiveTriple)) {
3396
0
        D.Diag(diag::err_target_unsupported_tp_hard)
3397
0
            << EffectiveTriple.getArchName();
3398
0
        return;
3399
0
      }
3400
      // Check whether the user asked for something other than -mtp=cp15
3401
0
      if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3402
0
        StringRef Value = A->getValue();
3403
0
        if (Value != "cp15") {
3404
0
          D.Diag(diag::err_drv_argument_not_allowed_with)
3405
0
              << A->getAsString(Args) << "-mstack-protector-guard=tls";
3406
0
          return;
3407
0
        }
3408
0
      }
3409
0
      CmdArgs.push_back("-target-feature");
3410
0
      CmdArgs.push_back("+read-tp-tpidruro");
3411
0
    }
3412
0
    if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3413
0
      D.Diag(diag::err_drv_invalid_value_with_suggestion)
3414
0
          << A->getOption().getName() << Value << "sysreg global";
3415
0
      return;
3416
0
    }
3417
0
    A->render(Args, CmdArgs);
3418
0
  }
3419
3420
0
  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3421
0
    StringRef Value = A->getValue();
3422
0
    if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3423
0
        !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3424
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
3425
0
          << A->getAsString(Args) << TripleStr;
3426
0
    int Offset;
3427
0
    if (Value.getAsInteger(10, Offset)) {
3428
0
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3429
0
      return;
3430
0
    }
3431
0
    if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3432
0
        (Offset < 0 || Offset > 0xfffff)) {
3433
0
      D.Diag(diag::err_drv_invalid_int_value)
3434
0
          << A->getOption().getName() << Value;
3435
0
      return;
3436
0
    }
3437
0
    A->render(Args, CmdArgs);
3438
0
  }
3439
3440
0
  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3441
0
    StringRef Value = A->getValue();
3442
0
    if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3443
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
3444
0
          << A->getAsString(Args) << TripleStr;
3445
0
    if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3446
0
      D.Diag(diag::err_drv_invalid_value_with_suggestion)
3447
0
          << A->getOption().getName() << Value << "fs gs";
3448
0
      return;
3449
0
    }
3450
0
    if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3451
0
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3452
0
      return;
3453
0
    }
3454
0
    A->render(Args, CmdArgs);
3455
0
  }
3456
3457
0
  if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3458
0
    StringRef Value = A->getValue();
3459
0
    if (!isValidSymbolName(Value)) {
3460
0
      D.Diag(diag::err_drv_argument_only_allowed_with)
3461
0
          << A->getOption().getName() << "legal symbol name";
3462
0
      return;
3463
0
    }
3464
0
    A->render(Args, CmdArgs);
3465
0
  }
3466
0
}
3467
3468
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3469
0
                             ArgStringList &CmdArgs) {
3470
0
  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3471
3472
0
  if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3473
0
    return;
3474
3475
0
  if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3476
0
      !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
3477
0
    return;
3478
3479
0
  Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3480
0
                    options::OPT_fno_stack_clash_protection);
3481
0
}
3482
3483
static void RenderTrivialAutoVarInitOptions(const Driver &D,
3484
                                            const ToolChain &TC,
3485
                                            const ArgList &Args,
3486
0
                                            ArgStringList &CmdArgs) {
3487
0
  auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3488
0
  StringRef TrivialAutoVarInit = "";
3489
3490
0
  for (const Arg *A : Args) {
3491
0
    switch (A->getOption().getID()) {
3492
0
    default:
3493
0
      continue;
3494
0
    case options::OPT_ftrivial_auto_var_init: {
3495
0
      A->claim();
3496
0
      StringRef Val = A->getValue();
3497
0
      if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3498
0
        TrivialAutoVarInit = Val;
3499
0
      else
3500
0
        D.Diag(diag::err_drv_unsupported_option_argument)
3501
0
            << A->getSpelling() << Val;
3502
0
      break;
3503
0
    }
3504
0
    }
3505
0
  }
3506
3507
0
  if (TrivialAutoVarInit.empty())
3508
0
    switch (DefaultTrivialAutoVarInit) {
3509
0
    case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3510
0
      break;
3511
0
    case LangOptions::TrivialAutoVarInitKind::Pattern:
3512
0
      TrivialAutoVarInit = "pattern";
3513
0
      break;
3514
0
    case LangOptions::TrivialAutoVarInitKind::Zero:
3515
0
      TrivialAutoVarInit = "zero";
3516
0
      break;
3517
0
    }
3518
3519
0
  if (!TrivialAutoVarInit.empty()) {
3520
0
    CmdArgs.push_back(
3521
0
        Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3522
0
  }
3523
3524
0
  if (Arg *A =
3525
0
          Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3526
0
    if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3527
0
        StringRef(
3528
0
            Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3529
0
            "uninitialized")
3530
0
      D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3531
0
    A->claim();
3532
0
    StringRef Val = A->getValue();
3533
0
    if (std::stoi(Val.str()) <= 0)
3534
0
      D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3535
0
    CmdArgs.push_back(
3536
0
        Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3537
0
  }
3538
0
}
3539
3540
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3541
0
                                types::ID InputType) {
3542
  // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3543
  // for denormal flushing handling based on the target.
3544
0
  const unsigned ForwardedArguments[] = {
3545
0
      options::OPT_cl_opt_disable,
3546
0
      options::OPT_cl_strict_aliasing,
3547
0
      options::OPT_cl_single_precision_constant,
3548
0
      options::OPT_cl_finite_math_only,
3549
0
      options::OPT_cl_kernel_arg_info,
3550
0
      options::OPT_cl_unsafe_math_optimizations,
3551
0
      options::OPT_cl_fast_relaxed_math,
3552
0
      options::OPT_cl_mad_enable,
3553
0
      options::OPT_cl_no_signed_zeros,
3554
0
      options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3555
0
      options::OPT_cl_uniform_work_group_size
3556
0
  };
3557
3558
0
  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3559
0
    std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3560
0
    CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3561
0
  } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3562
0
    std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3563
0
    CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3564
0
  }
3565
3566
0
  for (const auto &Arg : ForwardedArguments)
3567
0
    if (const auto *A = Args.getLastArg(Arg))
3568
0
      CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3569
3570
  // Only add the default headers if we are compiling OpenCL sources.
3571
0
  if ((types::isOpenCL(InputType) ||
3572
0
       (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3573
0
      !Args.hasArg(options::OPT_cl_no_stdinc)) {
3574
0
    CmdArgs.push_back("-finclude-default-header");
3575
0
    CmdArgs.push_back("-fdeclare-opencl-builtins");
3576
0
  }
3577
0
}
3578
3579
static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3580
0
                              types::ID InputType) {
3581
0
  const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3582
0
                                         options::OPT_D,
3583
0
                                         options::OPT_I,
3584
0
                                         options::OPT_S,
3585
0
                                         options::OPT_O,
3586
0
                                         options::OPT_emit_llvm,
3587
0
                                         options::OPT_emit_obj,
3588
0
                                         options::OPT_disable_llvm_passes,
3589
0
                                         options::OPT_fnative_half_type,
3590
0
                                         options::OPT_hlsl_entrypoint};
3591
0
  if (!types::isHLSL(InputType))
3592
0
    return;
3593
0
  for (const auto &Arg : ForwardedArguments)
3594
0
    if (const auto *A = Args.getLastArg(Arg))
3595
0
      A->renderAsInput(Args, CmdArgs);
3596
  // Add the default headers if dxc_no_stdinc is not set.
3597
0
  if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3598
0
      !Args.hasArg(options::OPT_nostdinc))
3599
0
    CmdArgs.push_back("-finclude-default-header");
3600
0
}
3601
3602
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3603
0
                                 ArgStringList &CmdArgs, types::ID InputType) {
3604
0
  if (!Args.hasArg(options::OPT_fopenacc))
3605
0
    return;
3606
3607
0
  CmdArgs.push_back("-fopenacc");
3608
3609
0
  if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
3610
0
    StringRef Value = A->getValue();
3611
0
    int Version;
3612
0
    if (!Value.getAsInteger(10, Version))
3613
0
      A->renderAsInput(Args, CmdArgs);
3614
0
    else
3615
0
      D.Diag(diag::err_drv_clang_unsupported) << Value;
3616
0
  }
3617
0
}
3618
3619
static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3620
0
                                        ArgStringList &CmdArgs) {
3621
0
  bool ARCMTEnabled = false;
3622
0
  if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3623
0
    if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3624
0
                                       options::OPT_ccc_arcmt_modify,
3625
0
                                       options::OPT_ccc_arcmt_migrate)) {
3626
0
      ARCMTEnabled = true;
3627
0
      switch (A->getOption().getID()) {
3628
0
      default: llvm_unreachable("missed a case");
3629
0
      case options::OPT_ccc_arcmt_check:
3630
0
        CmdArgs.push_back("-arcmt-action=check");
3631
0
        break;
3632
0
      case options::OPT_ccc_arcmt_modify:
3633
0
        CmdArgs.push_back("-arcmt-action=modify");
3634
0
        break;
3635
0
      case options::OPT_ccc_arcmt_migrate:
3636
0
        CmdArgs.push_back("-arcmt-action=migrate");
3637
0
        CmdArgs.push_back("-mt-migrate-directory");
3638
0
        CmdArgs.push_back(A->getValue());
3639
3640
0
        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3641
0
        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3642
0
        break;
3643
0
      }
3644
0
    }
3645
0
  } else {
3646
0
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3647
0
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3648
0
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3649
0
  }
3650
3651
0
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3652
0
    if (ARCMTEnabled)
3653
0
      D.Diag(diag::err_drv_argument_not_allowed_with)
3654
0
          << A->getAsString(Args) << "-ccc-arcmt-migrate";
3655
3656
0
    CmdArgs.push_back("-mt-migrate-directory");
3657
0
    CmdArgs.push_back(A->getValue());
3658
3659
0
    if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3660
0
                     options::OPT_objcmt_migrate_subscripting,
3661
0
                     options::OPT_objcmt_migrate_property)) {
3662
      // None specified, means enable them all.
3663
0
      CmdArgs.push_back("-objcmt-migrate-literals");
3664
0
      CmdArgs.push_back("-objcmt-migrate-subscripting");
3665
0
      CmdArgs.push_back("-objcmt-migrate-property");
3666
0
    } else {
3667
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3668
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3669
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3670
0
    }
3671
0
  } else {
3672
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3673
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3674
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3675
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3676
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3677
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3678
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3679
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3680
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3681
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3682
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3683
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3684
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3685
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3686
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3687
0
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3688
0
  }
3689
0
}
3690
3691
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3692
0
                                 const ArgList &Args, ArgStringList &CmdArgs) {
3693
  // -fbuiltin is default unless -mkernel is used.
3694
0
  bool UseBuiltins =
3695
0
      Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3696
0
                   !Args.hasArg(options::OPT_mkernel));
3697
0
  if (!UseBuiltins)
3698
0
    CmdArgs.push_back("-fno-builtin");
3699
3700
  // -ffreestanding implies -fno-builtin.
3701
0
  if (Args.hasArg(options::OPT_ffreestanding))
3702
0
    UseBuiltins = false;
3703
3704
  // Process the -fno-builtin-* options.
3705
0
  for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3706
0
    A->claim();
3707
3708
    // If -fno-builtin is specified, then there's no need to pass the option to
3709
    // the frontend.
3710
0
    if (UseBuiltins)
3711
0
      A->render(Args, CmdArgs);
3712
0
  }
3713
3714
  // le32-specific flags:
3715
  //  -fno-math-builtin: clang should not convert math builtins to intrinsics
3716
  //                     by default.
3717
0
  if (TC.getArch() == llvm::Triple::le32)
3718
0
    CmdArgs.push_back("-fno-math-builtin");
3719
0
}
3720
3721
0
bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3722
0
  if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3723
0
    Twine Path{Str};
3724
0
    Path.toVector(Result);
3725
0
    return Path.getSingleStringRef() != "";
3726
0
  }
3727
0
  if (llvm::sys::path::cache_directory(Result)) {
3728
0
    llvm::sys::path::append(Result, "clang");
3729
0
    llvm::sys::path::append(Result, "ModuleCache");
3730
0
    return true;
3731
0
  }
3732
0
  return false;
3733
0
}
3734
3735
static bool RenderModulesOptions(Compilation &C, const Driver &D,
3736
                                 const ArgList &Args, const InputInfo &Input,
3737
                                 const InputInfo &Output, bool HaveStd20,
3738
0
                                 ArgStringList &CmdArgs) {
3739
0
  bool IsCXX = types::isCXX(Input.getType());
3740
0
  bool HaveStdCXXModules = IsCXX && HaveStd20;
3741
0
  bool HaveModules = HaveStdCXXModules;
3742
3743
  // -fmodules enables the use of precompiled modules (off by default).
3744
  // Users can pass -fno-cxx-modules to turn off modules support for
3745
  // C++/Objective-C++ programs.
3746
0
  bool HaveClangModules = false;
3747
0
  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3748
0
    bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3749
0
                                     options::OPT_fno_cxx_modules, true);
3750
0
    if (AllowedInCXX || !IsCXX) {
3751
0
      CmdArgs.push_back("-fmodules");
3752
0
      HaveClangModules = true;
3753
0
    }
3754
0
  }
3755
3756
0
  HaveModules |= HaveClangModules;
3757
3758
  // -fmodule-maps enables implicit reading of module map files. By default,
3759
  // this is enabled if we are using Clang's flavor of precompiled modules.
3760
0
  if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3761
0
                   options::OPT_fno_implicit_module_maps, HaveClangModules))
3762
0
    CmdArgs.push_back("-fimplicit-module-maps");
3763
3764
  // -fmodules-decluse checks that modules used are declared so (off by default)
3765
0
  Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3766
0
                    options::OPT_fno_modules_decluse);
3767
3768
  // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3769
  // all #included headers are part of modules.
3770
0
  if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3771
0
                   options::OPT_fno_modules_strict_decluse, false))
3772
0
    CmdArgs.push_back("-fmodules-strict-decluse");
3773
3774
  // -fno-implicit-modules turns off implicitly compiling modules on demand.
3775
0
  bool ImplicitModules = false;
3776
0
  if (!Args.hasFlag(options::OPT_fimplicit_modules,
3777
0
                    options::OPT_fno_implicit_modules, HaveClangModules)) {
3778
0
    if (HaveModules)
3779
0
      CmdArgs.push_back("-fno-implicit-modules");
3780
0
  } else if (HaveModules) {
3781
0
    ImplicitModules = true;
3782
    // -fmodule-cache-path specifies where our implicitly-built module files
3783
    // should be written.
3784
0
    SmallString<128> Path;
3785
0
    if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3786
0
      Path = A->getValue();
3787
3788
0
    bool HasPath = true;
3789
0
    if (C.isForDiagnostics()) {
3790
      // When generating crash reports, we want to emit the modules along with
3791
      // the reproduction sources, so we ignore any provided module path.
3792
0
      Path = Output.getFilename();
3793
0
      llvm::sys::path::replace_extension(Path, ".cache");
3794
0
      llvm::sys::path::append(Path, "modules");
3795
0
    } else if (Path.empty()) {
3796
      // No module path was provided: use the default.
3797
0
      HasPath = Driver::getDefaultModuleCachePath(Path);
3798
0
    }
3799
3800
    // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3801
    // That being said, that failure is unlikely and not caching is harmless.
3802
0
    if (HasPath) {
3803
0
      const char Arg[] = "-fmodules-cache-path=";
3804
0
      Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3805
0
      CmdArgs.push_back(Args.MakeArgString(Path));
3806
0
    }
3807
0
  }
3808
3809
0
  if (HaveModules) {
3810
0
    if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3811
0
                     options::OPT_fno_prebuilt_implicit_modules, false))
3812
0
      CmdArgs.push_back("-fprebuilt-implicit-modules");
3813
0
    if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3814
0
                     options::OPT_fno_modules_validate_input_files_content,
3815
0
                     false))
3816
0
      CmdArgs.push_back("-fvalidate-ast-input-files-content");
3817
0
  }
3818
3819
  // -fmodule-name specifies the module that is currently being built (or
3820
  // used for header checking by -fmodule-maps).
3821
0
  Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3822
3823
  // -fmodule-map-file can be used to specify files containing module
3824
  // definitions.
3825
0
  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3826
3827
  // -fbuiltin-module-map can be used to load the clang
3828
  // builtin headers modulemap file.
3829
0
  if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3830
0
    SmallString<128> BuiltinModuleMap(D.ResourceDir);
3831
0
    llvm::sys::path::append(BuiltinModuleMap, "include");
3832
0
    llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3833
0
    if (llvm::sys::fs::exists(BuiltinModuleMap))
3834
0
      CmdArgs.push_back(
3835
0
          Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3836
0
  }
3837
3838
  // The -fmodule-file=<name>=<file> form specifies the mapping of module
3839
  // names to precompiled module files (the module is loaded only if used).
3840
  // The -fmodule-file=<file> form can be used to unconditionally load
3841
  // precompiled module files (whether used or not).
3842
0
  if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3843
0
    Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3844
3845
    // -fprebuilt-module-path specifies where to load the prebuilt module files.
3846
0
    for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3847
0
      CmdArgs.push_back(Args.MakeArgString(
3848
0
          std::string("-fprebuilt-module-path=") + A->getValue()));
3849
0
      A->claim();
3850
0
    }
3851
0
  } else
3852
0
    Args.ClaimAllArgs(options::OPT_fmodule_file);
3853
3854
  // When building modules and generating crashdumps, we need to dump a module
3855
  // dependency VFS alongside the output.
3856
0
  if (HaveClangModules && C.isForDiagnostics()) {
3857
0
    SmallString<128> VFSDir(Output.getFilename());
3858
0
    llvm::sys::path::replace_extension(VFSDir, ".cache");
3859
    // Add the cache directory as a temp so the crash diagnostics pick it up.
3860
0
    C.addTempFile(Args.MakeArgString(VFSDir));
3861
3862
0
    llvm::sys::path::append(VFSDir, "vfs");
3863
0
    CmdArgs.push_back("-module-dependency-dir");
3864
0
    CmdArgs.push_back(Args.MakeArgString(VFSDir));
3865
0
  }
3866
3867
0
  if (HaveClangModules)
3868
0
    Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3869
3870
  // Pass through all -fmodules-ignore-macro arguments.
3871
0
  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3872
0
  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3873
0
  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3874
3875
0
  if (HaveClangModules) {
3876
0
    Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3877
3878
0
    if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3879
0
      if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3880
0
        D.Diag(diag::err_drv_argument_not_allowed_with)
3881
0
            << A->getAsString(Args) << "-fbuild-session-timestamp";
3882
3883
0
      llvm::sys::fs::file_status Status;
3884
0
      if (llvm::sys::fs::status(A->getValue(), Status))
3885
0
        D.Diag(diag::err_drv_no_such_file) << A->getValue();
3886
0
      CmdArgs.push_back(Args.MakeArgString(
3887
0
          "-fbuild-session-timestamp=" +
3888
0
          Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3889
0
                    Status.getLastModificationTime().time_since_epoch())
3890
0
                    .count())));
3891
0
    }
3892
3893
0
    if (Args.getLastArg(
3894
0
            options::OPT_fmodules_validate_once_per_build_session)) {
3895
0
      if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3896
0
                           options::OPT_fbuild_session_file))
3897
0
        D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3898
3899
0
      Args.AddLastArg(CmdArgs,
3900
0
                      options::OPT_fmodules_validate_once_per_build_session);
3901
0
    }
3902
3903
0
    if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3904
0
                     options::OPT_fno_modules_validate_system_headers,
3905
0
                     ImplicitModules))
3906
0
      CmdArgs.push_back("-fmodules-validate-system-headers");
3907
3908
0
    Args.AddLastArg(CmdArgs,
3909
0
                    options::OPT_fmodules_disable_diagnostic_validation);
3910
0
  } else {
3911
0
    Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
3912
0
    Args.ClaimAllArgs(options::OPT_fbuild_session_file);
3913
0
    Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
3914
0
    Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
3915
0
    Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
3916
0
    Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
3917
0
  }
3918
3919
  // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
3920
0
  Args.ClaimAllArgs(options::OPT_fmodule_output);
3921
0
  Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
3922
3923
0
  return HaveModules;
3924
0
}
3925
3926
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3927
0
                                   ArgStringList &CmdArgs) {
3928
  // -fsigned-char is default.
3929
0
  if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3930
0
                                     options::OPT_fno_signed_char,
3931
0
                                     options::OPT_funsigned_char,
3932
0
                                     options::OPT_fno_unsigned_char)) {
3933
0
    if (A->getOption().matches(options::OPT_funsigned_char) ||
3934
0
        A->getOption().matches(options::OPT_fno_signed_char)) {
3935
0
      CmdArgs.push_back("-fno-signed-char");
3936
0
    }
3937
0
  } else if (!isSignedCharDefault(T)) {
3938
0
    CmdArgs.push_back("-fno-signed-char");
3939
0
  }
3940
3941
  // The default depends on the language standard.
3942
0
  Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3943
3944
0
  if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3945
0
                                     options::OPT_fno_short_wchar)) {
3946
0
    if (A->getOption().matches(options::OPT_fshort_wchar)) {
3947
0
      CmdArgs.push_back("-fwchar-type=short");
3948
0
      CmdArgs.push_back("-fno-signed-wchar");
3949
0
    } else {
3950
0
      bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3951
0
      CmdArgs.push_back("-fwchar-type=int");
3952
0
      if (T.isOSzOS() ||
3953
0
          (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3954
0
        CmdArgs.push_back("-fno-signed-wchar");
3955
0
      else
3956
0
        CmdArgs.push_back("-fsigned-wchar");
3957
0
    }
3958
0
  } else if (T.isOSzOS())
3959
0
    CmdArgs.push_back("-fno-signed-wchar");
3960
0
}
3961
3962
static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3963
                              const llvm::Triple &T, const ArgList &Args,
3964
                              ObjCRuntime &Runtime, bool InferCovariantReturns,
3965
0
                              const InputInfo &Input, ArgStringList &CmdArgs) {
3966
0
  const llvm::Triple::ArchType Arch = TC.getArch();
3967
3968
  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3969
  // is the default. Except for deployment target of 10.5, next runtime is
3970
  // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3971
0
  if (Runtime.isNonFragile()) {
3972
0
    if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3973
0
                      options::OPT_fno_objc_legacy_dispatch,
3974
0
                      Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3975
0
      if (TC.UseObjCMixedDispatch())
3976
0
        CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3977
0
      else
3978
0
        CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3979
0
    }
3980
0
  }
3981
3982
  // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3983
  // to do Array/Dictionary subscripting by default.
3984
0
  if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
3985
0
      Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3986
0
    CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3987
3988
  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3989
  // NOTE: This logic is duplicated in ToolChains.cpp.
3990
0
  if (isObjCAutoRefCount(Args)) {
3991
0
    TC.CheckObjCARC();
3992
3993
0
    CmdArgs.push_back("-fobjc-arc");
3994
3995
    // FIXME: It seems like this entire block, and several around it should be
3996
    // wrapped in isObjC, but for now we just use it here as this is where it
3997
    // was being used previously.
3998
0
    if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3999
0
      if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4000
0
        CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4001
0
      else
4002
0
        CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4003
0
    }
4004
4005
    // Allow the user to enable full exceptions code emission.
4006
    // We default off for Objective-C, on for Objective-C++.
4007
0
    if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4008
0
                     options::OPT_fno_objc_arc_exceptions,
4009
0
                     /*Default=*/types::isCXX(Input.getType())))
4010
0
      CmdArgs.push_back("-fobjc-arc-exceptions");
4011
0
  }
4012
4013
  // Silence warning for full exception code emission options when explicitly
4014
  // set to use no ARC.
4015
0
  if (Args.hasArg(options::OPT_fno_objc_arc)) {
4016
0
    Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4017
0
    Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4018
0
  }
4019
4020
  // Allow the user to control whether messages can be converted to runtime
4021
  // functions.
4022
0
  if (types::isObjC(Input.getType())) {
4023
0
    auto *Arg = Args.getLastArg(
4024
0
        options::OPT_fobjc_convert_messages_to_runtime_calls,
4025
0
        options::OPT_fno_objc_convert_messages_to_runtime_calls);
4026
0
    if (Arg &&
4027
0
        Arg->getOption().matches(
4028
0
            options::OPT_fno_objc_convert_messages_to_runtime_calls))
4029
0
      CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4030
0
  }
4031
4032
  // -fobjc-infer-related-result-type is the default, except in the Objective-C
4033
  // rewriter.
4034
0
  if (InferCovariantReturns)
4035
0
    CmdArgs.push_back("-fno-objc-infer-related-result-type");
4036
4037
  // Pass down -fobjc-weak or -fno-objc-weak if present.
4038
0
  if (types::isObjC(Input.getType())) {
4039
0
    auto WeakArg =
4040
0
        Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4041
0
    if (!WeakArg) {
4042
      // nothing to do
4043
0
    } else if (!Runtime.allowsWeak()) {
4044
0
      if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4045
0
        D.Diag(diag::err_objc_weak_unsupported);
4046
0
    } else {
4047
0
      WeakArg->render(Args, CmdArgs);
4048
0
    }
4049
0
  }
4050
4051
0
  if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4052
0
    CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4053
0
}
4054
4055
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4056
0
                                     ArgStringList &CmdArgs) {
4057
0
  bool CaretDefault = true;
4058
0
  bool ColumnDefault = true;
4059
4060
0
  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4061
0
                                     options::OPT__SLASH_diagnostics_column,
4062
0
                                     options::OPT__SLASH_diagnostics_caret)) {
4063
0
    switch (A->getOption().getID()) {
4064
0
    case options::OPT__SLASH_diagnostics_caret:
4065
0
      CaretDefault = true;
4066
0
      ColumnDefault = true;
4067
0
      break;
4068
0
    case options::OPT__SLASH_diagnostics_column:
4069
0
      CaretDefault = false;
4070
0
      ColumnDefault = true;
4071
0
      break;
4072
0
    case options::OPT__SLASH_diagnostics_classic:
4073
0
      CaretDefault = false;
4074
0
      ColumnDefault = false;
4075
0
      break;
4076
0
    }
4077
0
  }
4078
4079
  // -fcaret-diagnostics is default.
4080
0
  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4081
0
                    options::OPT_fno_caret_diagnostics, CaretDefault))
4082
0
    CmdArgs.push_back("-fno-caret-diagnostics");
4083
4084
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4085
0
                     options::OPT_fno_diagnostics_fixit_info);
4086
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4087
0
                     options::OPT_fno_diagnostics_show_option);
4088
4089
0
  if (const Arg *A =
4090
0
          Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4091
0
    CmdArgs.push_back("-fdiagnostics-show-category");
4092
0
    CmdArgs.push_back(A->getValue());
4093
0
  }
4094
4095
0
  Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4096
0
                    options::OPT_fno_diagnostics_show_hotness);
4097
4098
0
  if (const Arg *A =
4099
0
          Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4100
0
    std::string Opt =
4101
0
        std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4102
0
    CmdArgs.push_back(Args.MakeArgString(Opt));
4103
0
  }
4104
4105
0
  if (const Arg *A =
4106
0
          Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4107
0
    std::string Opt =
4108
0
        std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4109
0
    CmdArgs.push_back(Args.MakeArgString(Opt));
4110
0
  }
4111
4112
0
  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4113
0
    CmdArgs.push_back("-fdiagnostics-format");
4114
0
    CmdArgs.push_back(A->getValue());
4115
0
    if (StringRef(A->getValue()) == "sarif" ||
4116
0
        StringRef(A->getValue()) == "SARIF")
4117
0
      D.Diag(diag::warn_drv_sarif_format_unstable);
4118
0
  }
4119
4120
0
  if (const Arg *A = Args.getLastArg(
4121
0
          options::OPT_fdiagnostics_show_note_include_stack,
4122
0
          options::OPT_fno_diagnostics_show_note_include_stack)) {
4123
0
    const Option &O = A->getOption();
4124
0
    if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4125
0
      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4126
0
    else
4127
0
      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4128
0
  }
4129
4130
  // Color diagnostics are parsed by the driver directly from argv and later
4131
  // re-parsed to construct this job; claim any possible color diagnostic here
4132
  // to avoid warn_drv_unused_argument and diagnose bad
4133
  // OPT_fdiagnostics_color_EQ values.
4134
0
  Args.getLastArg(options::OPT_fcolor_diagnostics,
4135
0
                  options::OPT_fno_color_diagnostics);
4136
0
  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4137
0
    StringRef Value(A->getValue());
4138
0
    if (Value != "always" && Value != "never" && Value != "auto")
4139
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
4140
0
          << Value << A->getOption().getName();
4141
0
  }
4142
4143
0
  if (D.getDiags().getDiagnosticOptions().ShowColors)
4144
0
    CmdArgs.push_back("-fcolor-diagnostics");
4145
4146
0
  if (Args.hasArg(options::OPT_fansi_escape_codes))
4147
0
    CmdArgs.push_back("-fansi-escape-codes");
4148
4149
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4150
0
                     options::OPT_fno_show_source_location);
4151
4152
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4153
0
                     options::OPT_fno_diagnostics_show_line_numbers);
4154
4155
0
  if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4156
0
    CmdArgs.push_back("-fdiagnostics-absolute-paths");
4157
4158
0
  if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4159
0
                    ColumnDefault))
4160
0
    CmdArgs.push_back("-fno-show-column");
4161
4162
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4163
0
                     options::OPT_fno_spell_checking);
4164
0
}
4165
4166
DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
4167
0
                                            const ArgList &Args, Arg *&Arg) {
4168
0
  Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4169
0
                        options::OPT_gno_split_dwarf);
4170
0
  if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4171
0
    return DwarfFissionKind::None;
4172
4173
0
  if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4174
0
    return DwarfFissionKind::Split;
4175
4176
0
  StringRef Value = Arg->getValue();
4177
0
  if (Value == "split")
4178
0
    return DwarfFissionKind::Split;
4179
0
  if (Value == "single")
4180
0
    return DwarfFissionKind::Single;
4181
4182
0
  D.Diag(diag::err_drv_unsupported_option_argument)
4183
0
      << Arg->getSpelling() << Arg->getValue();
4184
0
  return DwarfFissionKind::None;
4185
0
}
4186
4187
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4188
                              const ArgList &Args, ArgStringList &CmdArgs,
4189
0
                              unsigned DwarfVersion) {
4190
0
  auto *DwarfFormatArg =
4191
0
      Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4192
0
  if (!DwarfFormatArg)
4193
0
    return;
4194
4195
0
  if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4196
0
    if (DwarfVersion < 3)
4197
0
      D.Diag(diag::err_drv_argument_only_allowed_with)
4198
0
          << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4199
0
    else if (!T.isArch64Bit())
4200
0
      D.Diag(diag::err_drv_argument_only_allowed_with)
4201
0
          << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4202
0
    else if (!T.isOSBinFormatELF())
4203
0
      D.Diag(diag::err_drv_argument_only_allowed_with)
4204
0
          << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4205
0
  }
4206
4207
0
  DwarfFormatArg->render(Args, CmdArgs);
4208
0
}
4209
4210
static void
4211
renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4212
                   const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
4213
                   const InputInfo &Output,
4214
                   llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4215
0
                   DwarfFissionKind &DwarfFission) {
4216
0
  if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4217
0
                   options::OPT_fno_debug_info_for_profiling, false) &&
4218
0
      checkDebugInfoOption(
4219
0
          Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4220
0
    CmdArgs.push_back("-fdebug-info-for-profiling");
4221
4222
  // The 'g' groups options involve a somewhat intricate sequence of decisions
4223
  // about what to pass from the driver to the frontend, but by the time they
4224
  // reach cc1 they've been factored into three well-defined orthogonal choices:
4225
  //  * what level of debug info to generate
4226
  //  * what dwarf version to write
4227
  //  * what debugger tuning to use
4228
  // This avoids having to monkey around further in cc1 other than to disable
4229
  // codeview if not running in a Windows environment. Perhaps even that
4230
  // decision should be made in the driver as well though.
4231
0
  llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4232
4233
0
  bool SplitDWARFInlining =
4234
0
      Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4235
0
                   options::OPT_fno_split_dwarf_inlining, false);
4236
4237
  // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4238
  // object file generation and no IR generation, -gN should not be needed. So
4239
  // allow -gsplit-dwarf with either -gN or IR input.
4240
0
  if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4241
0
    Arg *SplitDWARFArg;
4242
0
    DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4243
0
    if (DwarfFission != DwarfFissionKind::None &&
4244
0
        !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4245
0
      DwarfFission = DwarfFissionKind::None;
4246
0
      SplitDWARFInlining = false;
4247
0
    }
4248
0
  }
4249
0
  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4250
0
    DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4251
4252
    // If the last option explicitly specified a debug-info level, use it.
4253
0
    if (checkDebugInfoOption(A, Args, D, TC) &&
4254
0
        A->getOption().matches(options::OPT_gN_Group)) {
4255
0
      DebugInfoKind = debugLevelToInfoKind(*A);
4256
      // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4257
      // complicated if you've disabled inline info in the skeleton CUs
4258
      // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4259
      // line-tables-only, so let those compose naturally in that case.
4260
0
      if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4261
0
          DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4262
0
          (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4263
0
           SplitDWARFInlining))
4264
0
        DwarfFission = DwarfFissionKind::None;
4265
0
    }
4266
0
  }
4267
4268
  // If a debugger tuning argument appeared, remember it.
4269
0
  bool HasDebuggerTuning = false;
4270
0
  if (const Arg *A =
4271
0
          Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4272
0
    HasDebuggerTuning = true;
4273
0
    if (checkDebugInfoOption(A, Args, D, TC)) {
4274
0
      if (A->getOption().matches(options::OPT_glldb))
4275
0
        DebuggerTuning = llvm::DebuggerKind::LLDB;
4276
0
      else if (A->getOption().matches(options::OPT_gsce))
4277
0
        DebuggerTuning = llvm::DebuggerKind::SCE;
4278
0
      else if (A->getOption().matches(options::OPT_gdbx))
4279
0
        DebuggerTuning = llvm::DebuggerKind::DBX;
4280
0
      else
4281
0
        DebuggerTuning = llvm::DebuggerKind::GDB;
4282
0
    }
4283
0
  }
4284
4285
  // If a -gdwarf argument appeared, remember it.
4286
0
  bool EmitDwarf = false;
4287
0
  if (const Arg *A = getDwarfNArg(Args))
4288
0
    EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4289
4290
0
  bool EmitCodeView = false;
4291
0
  if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4292
0
    EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4293
4294
  // If the user asked for debug info but did not explicitly specify -gcodeview
4295
  // or -gdwarf, ask the toolchain for the default format.
4296
0
  if (!EmitCodeView && !EmitDwarf &&
4297
0
      DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4298
0
    switch (TC.getDefaultDebugFormat()) {
4299
0
    case llvm::codegenoptions::DIF_CodeView:
4300
0
      EmitCodeView = true;
4301
0
      break;
4302
0
    case llvm::codegenoptions::DIF_DWARF:
4303
0
      EmitDwarf = true;
4304
0
      break;
4305
0
    }
4306
0
  }
4307
4308
0
  unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4309
0
  unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4310
                                      // be lower than what the user wanted.
4311
0
  if (EmitDwarf) {
4312
0
    RequestedDWARFVersion = getDwarfVersion(TC, Args);
4313
    // Clamp effective DWARF version to the max supported by the toolchain.
4314
0
    EffectiveDWARFVersion =
4315
0
        std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4316
0
  } else {
4317
0
    Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4318
0
  }
4319
4320
  // -gline-directives-only supported only for the DWARF debug info.
4321
0
  if (RequestedDWARFVersion == 0 &&
4322
0
      DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4323
0
    DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4324
4325
  // strict DWARF is set to false by default. But for DBX, we need it to be set
4326
  // as true by default.
4327
0
  if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4328
0
    (void)checkDebugInfoOption(A, Args, D, TC);
4329
0
  if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4330
0
                   DebuggerTuning == llvm::DebuggerKind::DBX))
4331
0
    CmdArgs.push_back("-gstrict-dwarf");
4332
4333
  // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4334
0
  Args.ClaimAllArgs(options::OPT_g_flags_Group);
4335
4336
  // Column info is included by default for everything except SCE and
4337
  // CodeView. Clang doesn't track end columns, just starting columns, which,
4338
  // in theory, is fine for CodeView (and PDB).  In practice, however, the
4339
  // Microsoft debuggers don't handle missing end columns well, and the AIX
4340
  // debugger DBX also doesn't handle the columns well, so it's better not to
4341
  // include any column info.
4342
0
  if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4343
0
    (void)checkDebugInfoOption(A, Args, D, TC);
4344
0
  if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4345
0
                    !EmitCodeView &&
4346
0
                        (DebuggerTuning != llvm::DebuggerKind::SCE &&
4347
0
                         DebuggerTuning != llvm::DebuggerKind::DBX)))
4348
0
    CmdArgs.push_back("-gno-column-info");
4349
4350
  // FIXME: Move backend command line options to the module.
4351
0
  if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4352
    // If -gline-tables-only or -gline-directives-only is the last option it
4353
    // wins.
4354
0
    if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4355
0
                             TC)) {
4356
0
      if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4357
0
          DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4358
0
        DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4359
0
        CmdArgs.push_back("-dwarf-ext-refs");
4360
0
        CmdArgs.push_back("-fmodule-format=obj");
4361
0
      }
4362
0
    }
4363
0
  }
4364
4365
0
  if (T.isOSBinFormatELF() && SplitDWARFInlining)
4366
0
    CmdArgs.push_back("-fsplit-dwarf-inlining");
4367
4368
  // After we've dealt with all combinations of things that could
4369
  // make DebugInfoKind be other than None or DebugLineTablesOnly,
4370
  // figure out if we need to "upgrade" it to standalone debug info.
4371
  // We parse these two '-f' options whether or not they will be used,
4372
  // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4373
0
  bool NeedFullDebug = Args.hasFlag(
4374
0
      options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4375
0
      DebuggerTuning == llvm::DebuggerKind::LLDB ||
4376
0
          TC.GetDefaultStandaloneDebug());
4377
0
  if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4378
0
    (void)checkDebugInfoOption(A, Args, D, TC);
4379
4380
0
  if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4381
0
      DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4382
0
    if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4383
0
                     options::OPT_feliminate_unused_debug_types, false))
4384
0
      DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4385
0
    else if (NeedFullDebug)
4386
0
      DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4387
0
  }
4388
4389
0
  if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4390
0
                   false)) {
4391
    // Source embedding is a vendor extension to DWARF v5. By now we have
4392
    // checked if a DWARF version was stated explicitly, and have otherwise
4393
    // fallen back to the target default, so if this is still not at least 5
4394
    // we emit an error.
4395
0
    const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4396
0
    if (RequestedDWARFVersion < 5)
4397
0
      D.Diag(diag::err_drv_argument_only_allowed_with)
4398
0
          << A->getAsString(Args) << "-gdwarf-5";
4399
0
    else if (EffectiveDWARFVersion < 5)
4400
      // The toolchain has reduced allowed dwarf version, so we can't enable
4401
      // -gembed-source.
4402
0
      D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4403
0
          << A->getAsString(Args) << TC.getTripleString() << 5
4404
0
          << EffectiveDWARFVersion;
4405
0
    else if (checkDebugInfoOption(A, Args, D, TC))
4406
0
      CmdArgs.push_back("-gembed-source");
4407
0
  }
4408
4409
0
  if (EmitCodeView) {
4410
0
    CmdArgs.push_back("-gcodeview");
4411
4412
0
    Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4413
0
                      options::OPT_gno_codeview_ghash);
4414
4415
0
    Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4416
0
                       options::OPT_gno_codeview_command_line);
4417
0
  }
4418
4419
0
  Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4420
0
                     options::OPT_gno_inline_line_tables);
4421
4422
  // When emitting remarks, we need at least debug lines in the output.
4423
0
  if (willEmitRemarks(Args) &&
4424
0
      DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4425
0
    DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4426
4427
  // Adjust the debug info kind for the given toolchain.
4428
0
  TC.adjustDebugInfoKind(DebugInfoKind, Args);
4429
4430
  // On AIX, the debugger tuning option can be omitted if it is not explicitly
4431
  // set.
4432
0
  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4433
0
                          T.isOSAIX() && !HasDebuggerTuning
4434
0
                              ? llvm::DebuggerKind::Default
4435
0
                              : DebuggerTuning);
4436
4437
  // -fdebug-macro turns on macro debug info generation.
4438
0
  if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4439
0
                   false))
4440
0
    if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4441
0
                             D, TC))
4442
0
      CmdArgs.push_back("-debug-info-macro");
4443
4444
  // -ggnu-pubnames turns on gnu style pubnames in the backend.
4445
0
  const auto *PubnamesArg =
4446
0
      Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4447
0
                      options::OPT_gpubnames, options::OPT_gno_pubnames);
4448
0
  if (DwarfFission != DwarfFissionKind::None ||
4449
0
      (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4450
0
    if (!PubnamesArg ||
4451
0
        (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4452
0
         !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4453
0
      CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4454
0
                                           options::OPT_gpubnames)
4455
0
                            ? "-gpubnames"
4456
0
                            : "-ggnu-pubnames");
4457
0
  const auto *SimpleTemplateNamesArg =
4458
0
      Args.getLastArg(options::OPT_gsimple_template_names,
4459
0
                      options::OPT_gno_simple_template_names);
4460
0
  bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4461
0
  if (SimpleTemplateNamesArg &&
4462
0
      checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4463
0
    const auto &Opt = SimpleTemplateNamesArg->getOption();
4464
0
    if (Opt.matches(options::OPT_gsimple_template_names)) {
4465
0
      ForwardTemplateParams = true;
4466
0
      CmdArgs.push_back("-gsimple-template-names=simple");
4467
0
    }
4468
0
  }
4469
4470
0
  if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4471
0
    StringRef v = A->getValue();
4472
0
    CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4473
0
  }
4474
4475
0
  Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4476
0
                    options::OPT_fno_debug_ranges_base_address);
4477
4478
  // -gdwarf-aranges turns on the emission of the aranges section in the
4479
  // backend.
4480
  // Always enabled for SCE tuning.
4481
0
  bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4482
0
  if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4483
0
    NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4484
0
  if (NeedAranges) {
4485
0
    CmdArgs.push_back("-mllvm");
4486
0
    CmdArgs.push_back("-generate-arange-section");
4487
0
  }
4488
4489
0
  Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4490
0
                    options::OPT_fno_force_dwarf_frame);
4491
4492
0
  if (Args.hasFlag(options::OPT_fdebug_types_section,
4493
0
                   options::OPT_fno_debug_types_section, false)) {
4494
0
    if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4495
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4496
0
          << Args.getLastArg(options::OPT_fdebug_types_section)
4497
0
                 ->getAsString(Args)
4498
0
          << T.getTriple();
4499
0
    } else if (checkDebugInfoOption(
4500
0
                   Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4501
0
                   TC)) {
4502
0
      CmdArgs.push_back("-mllvm");
4503
0
      CmdArgs.push_back("-generate-type-units");
4504
0
    }
4505
0
  }
4506
4507
  // To avoid join/split of directory+filename, the integrated assembler prefers
4508
  // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4509
  // form before DWARF v5.
4510
0
  if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4511
0
                    options::OPT_fno_dwarf_directory_asm,
4512
0
                    TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4513
0
    CmdArgs.push_back("-fno-dwarf-directory-asm");
4514
4515
  // Decide how to render forward declarations of template instantiations.
4516
  // SCE wants full descriptions, others just get them in the name.
4517
0
  if (ForwardTemplateParams)
4518
0
    CmdArgs.push_back("-debug-forward-template-params");
4519
4520
  // Do we need to explicitly import anonymous namespaces into the parent
4521
  // scope?
4522
0
  if (DebuggerTuning == llvm::DebuggerKind::SCE)
4523
0
    CmdArgs.push_back("-dwarf-explicit-import");
4524
4525
0
  renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4526
0
  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4527
4528
  // This controls whether or not we perform JustMyCode instrumentation.
4529
0
  if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4530
0
    if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
4531
0
      if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4532
0
        CmdArgs.push_back("-fjmc");
4533
0
      else if (D.IsCLMode())
4534
0
        D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4535
0
                                                             << "'/Zi', '/Z7'";
4536
0
      else
4537
0
        D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4538
0
                                                             << "-g";
4539
0
    } else {
4540
0
      D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4541
0
    }
4542
0
  }
4543
4544
  // Add in -fdebug-compilation-dir if necessary.
4545
0
  const char *DebugCompilationDir =
4546
0
      addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4547
4548
0
  addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4549
4550
  // Add the output path to the object file for CodeView debug infos.
4551
0
  if (EmitCodeView && Output.isFilename())
4552
0
    addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4553
0
                       Output.getFilename());
4554
0
}
4555
4556
static void ProcessVSRuntimeLibrary(const ArgList &Args,
4557
0
                                    ArgStringList &CmdArgs) {
4558
0
  unsigned RTOptionID = options::OPT__SLASH_MT;
4559
4560
0
  if (Args.hasArg(options::OPT__SLASH_LDd))
4561
    // The /LDd option implies /MTd. The dependent lib part can be overridden,
4562
    // but defining _DEBUG is sticky.
4563
0
    RTOptionID = options::OPT__SLASH_MTd;
4564
4565
0
  if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4566
0
    RTOptionID = A->getOption().getID();
4567
4568
0
  if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4569
0
    RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4570
0
                     .Case("static", options::OPT__SLASH_MT)
4571
0
                     .Case("static_dbg", options::OPT__SLASH_MTd)
4572
0
                     .Case("dll", options::OPT__SLASH_MD)
4573
0
                     .Case("dll_dbg", options::OPT__SLASH_MDd)
4574
0
                     .Default(options::OPT__SLASH_MT);
4575
0
  }
4576
4577
0
  StringRef FlagForCRT;
4578
0
  switch (RTOptionID) {
4579
0
  case options::OPT__SLASH_MD:
4580
0
    if (Args.hasArg(options::OPT__SLASH_LDd))
4581
0
      CmdArgs.push_back("-D_DEBUG");
4582
0
    CmdArgs.push_back("-D_MT");
4583
0
    CmdArgs.push_back("-D_DLL");
4584
0
    FlagForCRT = "--dependent-lib=msvcrt";
4585
0
    break;
4586
0
  case options::OPT__SLASH_MDd:
4587
0
    CmdArgs.push_back("-D_DEBUG");
4588
0
    CmdArgs.push_back("-D_MT");
4589
0
    CmdArgs.push_back("-D_DLL");
4590
0
    FlagForCRT = "--dependent-lib=msvcrtd";
4591
0
    break;
4592
0
  case options::OPT__SLASH_MT:
4593
0
    if (Args.hasArg(options::OPT__SLASH_LDd))
4594
0
      CmdArgs.push_back("-D_DEBUG");
4595
0
    CmdArgs.push_back("-D_MT");
4596
0
    CmdArgs.push_back("-flto-visibility-public-std");
4597
0
    FlagForCRT = "--dependent-lib=libcmt";
4598
0
    break;
4599
0
  case options::OPT__SLASH_MTd:
4600
0
    CmdArgs.push_back("-D_DEBUG");
4601
0
    CmdArgs.push_back("-D_MT");
4602
0
    CmdArgs.push_back("-flto-visibility-public-std");
4603
0
    FlagForCRT = "--dependent-lib=libcmtd";
4604
0
    break;
4605
0
  default:
4606
0
    llvm_unreachable("Unexpected option ID.");
4607
0
  }
4608
4609
0
  if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4610
0
    CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4611
0
  } else {
4612
0
    CmdArgs.push_back(FlagForCRT.data());
4613
4614
    // This provides POSIX compatibility (maps 'open' to '_open'), which most
4615
    // users want.  The /Za flag to cl.exe turns this off, but it's not
4616
    // implemented in clang.
4617
0
    CmdArgs.push_back("--dependent-lib=oldnames");
4618
0
  }
4619
0
}
4620
4621
void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4622
                         const InputInfo &Output, const InputInfoList &Inputs,
4623
0
                         const ArgList &Args, const char *LinkingOutput) const {
4624
0
  const auto &TC = getToolChain();
4625
0
  const llvm::Triple &RawTriple = TC.getTriple();
4626
0
  const llvm::Triple &Triple = TC.getEffectiveTriple();
4627
0
  const std::string &TripleStr = Triple.getTriple();
4628
4629
0
  bool KernelOrKext =
4630
0
      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4631
0
  const Driver &D = TC.getDriver();
4632
0
  ArgStringList CmdArgs;
4633
4634
0
  assert(Inputs.size() >= 1 && "Must have at least one input.");
4635
  // CUDA/HIP compilation may have multiple inputs (source file + results of
4636
  // device-side compilations). OpenMP device jobs also take the host IR as a
4637
  // second input. Module precompilation accepts a list of header files to
4638
  // include as part of the module. API extraction accepts a list of header
4639
  // files whose API information is emitted in the output. All other jobs are
4640
  // expected to have exactly one input.
4641
0
  bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4642
0
  bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4643
0
  bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4644
0
  bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4645
0
  bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4646
0
  bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4647
0
  bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4648
0
                                 JA.isDeviceOffloading(Action::OFK_Host));
4649
0
  bool IsHostOffloadingAction =
4650
0
      JA.isHostOffloading(Action::OFK_OpenMP) ||
4651
0
      (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4652
0
       Args.hasFlag(options::OPT_offload_new_driver,
4653
0
                    options::OPT_no_offload_new_driver, false));
4654
4655
0
  bool IsRDCMode =
4656
0
      Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4657
0
  bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4658
0
  auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4659
4660
  // Extract API doesn't have a main input file, so invent a fake one as a
4661
  // placeholder.
4662
0
  InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4663
0
                                       "extract-api");
4664
4665
0
  const InputInfo &Input =
4666
0
      IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4667
4668
0
  InputInfoList ExtractAPIInputs;
4669
0
  InputInfoList HostOffloadingInputs;
4670
0
  const InputInfo *CudaDeviceInput = nullptr;
4671
0
  const InputInfo *OpenMPDeviceInput = nullptr;
4672
0
  for (const InputInfo &I : Inputs) {
4673
0
    if (&I == &Input || I.getType() == types::TY_Nothing) {
4674
      // This is the primary input or contains nothing.
4675
0
    } else if (IsExtractAPI) {
4676
0
      auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4677
0
      if (I.getType() != ExpectedInputType) {
4678
0
        D.Diag(diag::err_drv_extract_api_wrong_kind)
4679
0
            << I.getFilename() << types::getTypeName(I.getType())
4680
0
            << types::getTypeName(ExpectedInputType);
4681
0
      }
4682
0
      ExtractAPIInputs.push_back(I);
4683
0
    } else if (IsHostOffloadingAction) {
4684
0
      HostOffloadingInputs.push_back(I);
4685
0
    } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4686
0
      CudaDeviceInput = &I;
4687
0
    } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4688
0
      OpenMPDeviceInput = &I;
4689
0
    } else {
4690
0
      llvm_unreachable("unexpectedly given multiple inputs");
4691
0
    }
4692
0
  }
4693
4694
0
  const llvm::Triple *AuxTriple =
4695
0
      (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4696
0
  bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4697
0
  bool IsIAMCU = RawTriple.isOSIAMCU();
4698
4699
  // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
4700
  // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4701
  // Windows), we need to pass Windows-specific flags to cc1.
4702
0
  if (IsCuda || IsHIP)
4703
0
    IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4704
4705
  // C++ is not supported for IAMCU.
4706
0
  if (IsIAMCU && types::isCXX(Input.getType()))
4707
0
    D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4708
4709
  // Invoke ourselves in -cc1 mode.
4710
  //
4711
  // FIXME: Implement custom jobs for internal actions.
4712
0
  CmdArgs.push_back("-cc1");
4713
4714
  // Add the "effective" target triple.
4715
0
  CmdArgs.push_back("-triple");
4716
0
  CmdArgs.push_back(Args.MakeArgString(TripleStr));
4717
4718
0
  if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4719
0
    DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4720
0
    Args.ClaimAllArgs(options::OPT_MJ);
4721
0
  } else if (const Arg *GenCDBFragment =
4722
0
                 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4723
0
    DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4724
0
                                         TripleStr, Output, Input, Args);
4725
0
    Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4726
0
  }
4727
4728
0
  if (IsCuda || IsHIP) {
4729
    // We have to pass the triple of the host if compiling for a CUDA/HIP device
4730
    // and vice-versa.
4731
0
    std::string NormalizedTriple;
4732
0
    if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4733
0
        JA.isDeviceOffloading(Action::OFK_HIP))
4734
0
      NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4735
0
                             ->getTriple()
4736
0
                             .normalize();
4737
0
    else {
4738
      // Host-side compilation.
4739
0
      NormalizedTriple =
4740
0
          (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4741
0
                  : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4742
0
              ->getTriple()
4743
0
              .normalize();
4744
0
      if (IsCuda) {
4745
        // We need to figure out which CUDA version we're compiling for, as that
4746
        // determines how we load and launch GPU kernels.
4747
0
        auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4748
0
            C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4749
0
        assert(CTC && "Expected valid CUDA Toolchain.");
4750
0
        if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4751
0
          CmdArgs.push_back(Args.MakeArgString(
4752
0
              Twine("-target-sdk-version=") +
4753
0
              CudaVersionToString(CTC->CudaInstallation.version())));
4754
        // Unsized function arguments used for variadics were introduced in
4755
        // CUDA-9.0. We still do not support generating code that actually uses
4756
        // variadic arguments yet, but we do need to allow parsing them as
4757
        // recent CUDA headers rely on that.
4758
        // https://github.com/llvm/llvm-project/issues/58410
4759
0
        if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
4760
0
          CmdArgs.push_back("-fcuda-allow-variadic-functions");
4761
0
      }
4762
0
    }
4763
0
    CmdArgs.push_back("-aux-triple");
4764
0
    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4765
4766
0
    if (JA.isDeviceOffloading(Action::OFK_HIP) &&
4767
0
        getToolChain().getTriple().isAMDGPU()) {
4768
      // Device side compilation printf
4769
0
      if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
4770
0
        CmdArgs.push_back(Args.MakeArgString(
4771
0
            "-mprintf-kind=" +
4772
0
            Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
4773
        // Force compiler error on invalid conversion specifiers
4774
0
        CmdArgs.push_back(
4775
0
            Args.MakeArgString("-Werror=format-invalid-specifier"));
4776
0
      }
4777
0
    }
4778
0
  }
4779
4780
  // Unconditionally claim the printf option now to avoid unused diagnostic.
4781
0
  if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
4782
0
    PF->claim();
4783
4784
0
  if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4785
0
    CmdArgs.push_back("-fsycl-is-device");
4786
4787
0
    if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4788
0
      A->render(Args, CmdArgs);
4789
0
    } else {
4790
      // Ensure the default version in SYCL mode is 2020.
4791
0
      CmdArgs.push_back("-sycl-std=2020");
4792
0
    }
4793
0
  }
4794
4795
0
  if (IsOpenMPDevice) {
4796
    // We have to pass the triple of the host if compiling for an OpenMP device.
4797
0
    std::string NormalizedTriple =
4798
0
        C.getSingleOffloadToolChain<Action::OFK_Host>()
4799
0
            ->getTriple()
4800
0
            .normalize();
4801
0
    CmdArgs.push_back("-aux-triple");
4802
0
    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4803
0
  }
4804
4805
0
  if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4806
0
                               Triple.getArch() == llvm::Triple::thumb)) {
4807
0
    unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4808
0
    unsigned Version = 0;
4809
0
    bool Failure =
4810
0
        Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4811
0
    if (Failure || Version < 7)
4812
0
      D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4813
0
                                                << TripleStr;
4814
0
  }
4815
4816
  // Push all default warning arguments that are specific to
4817
  // the given target.  These come before user provided warning options
4818
  // are provided.
4819
0
  TC.addClangWarningOptions(CmdArgs);
4820
4821
  // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4822
0
  if (Triple.isSPIR() || Triple.isSPIRV())
4823
0
    CmdArgs.push_back("-Wspir-compat");
4824
4825
  // Select the appropriate action.
4826
0
  RewriteKind rewriteKind = RK_None;
4827
4828
0
  bool UnifiedLTO = false;
4829
0
  if (IsUsingLTO) {
4830
0
    UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
4831
0
                              options::OPT_fno_unified_lto, Triple.isPS()) ||
4832
0
                 Args.hasFlag(options::OPT_ffat_lto_objects,
4833
0
                              options::OPT_fno_fat_lto_objects, false);
4834
0
    if (UnifiedLTO)
4835
0
      CmdArgs.push_back("-funified-lto");
4836
0
  }
4837
4838
  // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4839
  // it claims when not running an assembler. Otherwise, clang would emit
4840
  // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4841
  // flags while debugging something. That'd be somewhat inconvenient, and it's
4842
  // also inconsistent with most other flags -- we don't warn on
4843
  // -ffunction-sections not being used in -E mode either for example, even
4844
  // though it's not really used either.
4845
0
  if (!isa<AssembleJobAction>(JA)) {
4846
    // The args claimed here should match the args used in
4847
    // CollectArgsForIntegratedAssembler().
4848
0
    if (TC.useIntegratedAs()) {
4849
0
      Args.ClaimAllArgs(options::OPT_mrelax_all);
4850
0
      Args.ClaimAllArgs(options::OPT_mno_relax_all);
4851
0
      Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4852
0
      Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4853
0
      switch (C.getDefaultToolChain().getArch()) {
4854
0
      case llvm::Triple::arm:
4855
0
      case llvm::Triple::armeb:
4856
0
      case llvm::Triple::thumb:
4857
0
      case llvm::Triple::thumbeb:
4858
0
        Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4859
0
        break;
4860
0
      default:
4861
0
        break;
4862
0
      }
4863
0
    }
4864
0
    Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4865
0
    Args.ClaimAllArgs(options::OPT_Xassembler);
4866
0
    Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4867
0
  }
4868
4869
0
  if (isa<AnalyzeJobAction>(JA)) {
4870
0
    assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4871
0
    CmdArgs.push_back("-analyze");
4872
0
  } else if (isa<MigrateJobAction>(JA)) {
4873
0
    CmdArgs.push_back("-migrate");
4874
0
  } else if (isa<PreprocessJobAction>(JA)) {
4875
0
    if (Output.getType() == types::TY_Dependencies)
4876
0
      CmdArgs.push_back("-Eonly");
4877
0
    else {
4878
0
      CmdArgs.push_back("-E");
4879
0
      if (Args.hasArg(options::OPT_rewrite_objc) &&
4880
0
          !Args.hasArg(options::OPT_g_Group))
4881
0
        CmdArgs.push_back("-P");
4882
0
      else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
4883
0
        CmdArgs.push_back("-fdirectives-only");
4884
0
    }
4885
0
  } else if (isa<AssembleJobAction>(JA)) {
4886
0
    CmdArgs.push_back("-emit-obj");
4887
4888
0
    CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4889
4890
    // Also ignore explicit -force_cpusubtype_ALL option.
4891
0
    (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4892
0
  } else if (isa<PrecompileJobAction>(JA)) {
4893
0
    if (JA.getType() == types::TY_Nothing)
4894
0
      CmdArgs.push_back("-fsyntax-only");
4895
0
    else if (JA.getType() == types::TY_ModuleFile)
4896
0
      CmdArgs.push_back("-emit-module-interface");
4897
0
    else if (JA.getType() == types::TY_HeaderUnit)
4898
0
      CmdArgs.push_back("-emit-header-unit");
4899
0
    else
4900
0
      CmdArgs.push_back("-emit-pch");
4901
0
  } else if (isa<VerifyPCHJobAction>(JA)) {
4902
0
    CmdArgs.push_back("-verify-pch");
4903
0
  } else if (isa<ExtractAPIJobAction>(JA)) {
4904
0
    assert(JA.getType() == types::TY_API_INFO &&
4905
0
           "Extract API actions must generate a API information.");
4906
0
    CmdArgs.push_back("-extract-api");
4907
0
    if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
4908
0
      ProductNameArg->render(Args, CmdArgs);
4909
0
    if (Arg *ExtractAPIIgnoresFileArg =
4910
0
            Args.getLastArg(options::OPT_extract_api_ignores_EQ))
4911
0
      ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
4912
0
  } else {
4913
0
    assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4914
0
           "Invalid action for clang tool.");
4915
0
    if (JA.getType() == types::TY_Nothing) {
4916
0
      CmdArgs.push_back("-fsyntax-only");
4917
0
    } else if (JA.getType() == types::TY_LLVM_IR ||
4918
0
               JA.getType() == types::TY_LTO_IR) {
4919
0
      CmdArgs.push_back("-emit-llvm");
4920
0
    } else if (JA.getType() == types::TY_LLVM_BC ||
4921
0
               JA.getType() == types::TY_LTO_BC) {
4922
      // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4923
0
      if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4924
0
          Args.hasArg(options::OPT_emit_llvm)) {
4925
0
        CmdArgs.push_back("-emit-llvm");
4926
0
      } else {
4927
0
        CmdArgs.push_back("-emit-llvm-bc");
4928
0
      }
4929
0
    } else if (JA.getType() == types::TY_IFS ||
4930
0
               JA.getType() == types::TY_IFS_CPP) {
4931
0
      StringRef ArgStr =
4932
0
          Args.hasArg(options::OPT_interface_stub_version_EQ)
4933
0
              ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4934
0
              : "ifs-v1";
4935
0
      CmdArgs.push_back("-emit-interface-stubs");
4936
0
      CmdArgs.push_back(
4937
0
          Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4938
0
    } else if (JA.getType() == types::TY_PP_Asm) {
4939
0
      CmdArgs.push_back("-S");
4940
0
    } else if (JA.getType() == types::TY_AST) {
4941
0
      CmdArgs.push_back("-emit-pch");
4942
0
    } else if (JA.getType() == types::TY_ModuleFile) {
4943
0
      CmdArgs.push_back("-module-file-info");
4944
0
    } else if (JA.getType() == types::TY_RewrittenObjC) {
4945
0
      CmdArgs.push_back("-rewrite-objc");
4946
0
      rewriteKind = RK_NonFragile;
4947
0
    } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4948
0
      CmdArgs.push_back("-rewrite-objc");
4949
0
      rewriteKind = RK_Fragile;
4950
0
    } else {
4951
0
      assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4952
0
    }
4953
4954
    // Preserve use-list order by default when emitting bitcode, so that
4955
    // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4956
    // same result as running passes here.  For LTO, we don't need to preserve
4957
    // the use-list order, since serialization to bitcode is part of the flow.
4958
0
    if (JA.getType() == types::TY_LLVM_BC)
4959
0
      CmdArgs.push_back("-emit-llvm-uselists");
4960
4961
0
    if (IsUsingLTO) {
4962
0
      if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
4963
0
          !Args.hasFlag(options::OPT_offload_new_driver,
4964
0
                        options::OPT_no_offload_new_driver, false) &&
4965
0
          !Triple.isAMDGPU()) {
4966
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
4967
0
            << Args.getLastArg(options::OPT_foffload_lto,
4968
0
                               options::OPT_foffload_lto_EQ)
4969
0
                   ->getAsString(Args)
4970
0
            << Triple.getTriple();
4971
0
      } else if (Triple.isNVPTX() && !IsRDCMode &&
4972
0
                 JA.isDeviceOffloading(Action::OFK_Cuda)) {
4973
0
        D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
4974
0
            << Args.getLastArg(options::OPT_foffload_lto,
4975
0
                               options::OPT_foffload_lto_EQ)
4976
0
                   ->getAsString(Args)
4977
0
            << "-fno-gpu-rdc";
4978
0
      } else {
4979
0
        assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4980
0
        CmdArgs.push_back(Args.MakeArgString(
4981
0
            Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4982
        // PS4 uses the legacy LTO API, which does not support some of the
4983
        // features enabled by -flto-unit.
4984
0
        if (!RawTriple.isPS4() ||
4985
0
            (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
4986
0
          CmdArgs.push_back("-flto-unit");
4987
0
      }
4988
0
    }
4989
0
  }
4990
4991
0
  Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
4992
4993
0
  if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4994
0
    if (!types::isLLVMIR(Input.getType()))
4995
0
      D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4996
0
    Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4997
0
  }
4998
4999
0
  if (Triple.isPPC())
5000
0
    Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5001
0
                      options::OPT_mno_regnames);
5002
5003
0
  if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5004
0
    Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5005
5006
0
  if (Args.getLastArg(options::OPT_save_temps_EQ))
5007
0
    Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5008
5009
0
  auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5010
0
                                     options::OPT_fmemory_profile_EQ,
5011
0
                                     options::OPT_fno_memory_profile);
5012
0
  if (MemProfArg &&
5013
0
      !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5014
0
    MemProfArg->render(Args, CmdArgs);
5015
5016
0
  if (auto *MemProfUseArg =
5017
0
          Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5018
0
    if (MemProfArg)
5019
0
      D.Diag(diag::err_drv_argument_not_allowed_with)
5020
0
          << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5021
0
    if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5022
0
                                            options::OPT_fprofile_generate_EQ))
5023
0
      D.Diag(diag::err_drv_argument_not_allowed_with)
5024
0
          << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5025
0
    MemProfUseArg->render(Args, CmdArgs);
5026
0
  }
5027
5028
  // Embed-bitcode option.
5029
  // Only white-listed flags below are allowed to be embedded.
5030
0
  if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5031
0
      (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
5032
    // Add flags implied by -fembed-bitcode.
5033
0
    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5034
    // Disable all llvm IR level optimizations.
5035
0
    CmdArgs.push_back("-disable-llvm-passes");
5036
5037
    // Render target options.
5038
0
    TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5039
5040
    // reject options that shouldn't be supported in bitcode
5041
    // also reject kernel/kext
5042
0
    static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5043
0
        options::OPT_mkernel,
5044
0
        options::OPT_fapple_kext,
5045
0
        options::OPT_ffunction_sections,
5046
0
        options::OPT_fno_function_sections,
5047
0
        options::OPT_fdata_sections,
5048
0
        options::OPT_fno_data_sections,
5049
0
        options::OPT_fbasic_block_sections_EQ,
5050
0
        options::OPT_funique_internal_linkage_names,
5051
0
        options::OPT_fno_unique_internal_linkage_names,
5052
0
        options::OPT_funique_section_names,
5053
0
        options::OPT_fno_unique_section_names,
5054
0
        options::OPT_funique_basic_block_section_names,
5055
0
        options::OPT_fno_unique_basic_block_section_names,
5056
0
        options::OPT_mrestrict_it,
5057
0
        options::OPT_mno_restrict_it,
5058
0
        options::OPT_mstackrealign,
5059
0
        options::OPT_mno_stackrealign,
5060
0
        options::OPT_mstack_alignment,
5061
0
        options::OPT_mcmodel_EQ,
5062
0
        options::OPT_mlong_calls,
5063
0
        options::OPT_mno_long_calls,
5064
0
        options::OPT_ggnu_pubnames,
5065
0
        options::OPT_gdwarf_aranges,
5066
0
        options::OPT_fdebug_types_section,
5067
0
        options::OPT_fno_debug_types_section,
5068
0
        options::OPT_fdwarf_directory_asm,
5069
0
        options::OPT_fno_dwarf_directory_asm,
5070
0
        options::OPT_mrelax_all,
5071
0
        options::OPT_mno_relax_all,
5072
0
        options::OPT_ftrap_function_EQ,
5073
0
        options::OPT_ffixed_r9,
5074
0
        options::OPT_mfix_cortex_a53_835769,
5075
0
        options::OPT_mno_fix_cortex_a53_835769,
5076
0
        options::OPT_ffixed_x18,
5077
0
        options::OPT_mglobal_merge,
5078
0
        options::OPT_mno_global_merge,
5079
0
        options::OPT_mred_zone,
5080
0
        options::OPT_mno_red_zone,
5081
0
        options::OPT_Wa_COMMA,
5082
0
        options::OPT_Xassembler,
5083
0
        options::OPT_mllvm,
5084
0
    };
5085
0
    for (const auto &A : Args)
5086
0
      if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5087
0
        D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5088
5089
    // Render the CodeGen options that need to be passed.
5090
0
    Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5091
0
                       options::OPT_fno_optimize_sibling_calls);
5092
5093
0
    RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
5094
0
                               CmdArgs, JA);
5095
5096
    // Render ABI arguments
5097
0
    switch (TC.getArch()) {
5098
0
    default: break;
5099
0
    case llvm::Triple::arm:
5100
0
    case llvm::Triple::armeb:
5101
0
    case llvm::Triple::thumbeb:
5102
0
      RenderARMABI(D, Triple, Args, CmdArgs);
5103
0
      break;
5104
0
    case llvm::Triple::aarch64:
5105
0
    case llvm::Triple::aarch64_32:
5106
0
    case llvm::Triple::aarch64_be:
5107
0
      RenderAArch64ABI(Triple, Args, CmdArgs);
5108
0
      break;
5109
0
    }
5110
5111
    // Optimization level for CodeGen.
5112
0
    if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5113
0
      if (A->getOption().matches(options::OPT_O4)) {
5114
0
        CmdArgs.push_back("-O3");
5115
0
        D.Diag(diag::warn_O4_is_O3);
5116
0
      } else {
5117
0
        A->render(Args, CmdArgs);
5118
0
      }
5119
0
    }
5120
5121
    // Input/Output file.
5122
0
    if (Output.getType() == types::TY_Dependencies) {
5123
      // Handled with other dependency code.
5124
0
    } else if (Output.isFilename()) {
5125
0
      CmdArgs.push_back("-o");
5126
0
      CmdArgs.push_back(Output.getFilename());
5127
0
    } else {
5128
0
      assert(Output.isNothing() && "Input output.");
5129
0
    }
5130
5131
0
    for (const auto &II : Inputs) {
5132
0
      addDashXForInput(Args, II, CmdArgs);
5133
0
      if (II.isFilename())
5134
0
        CmdArgs.push_back(II.getFilename());
5135
0
      else
5136
0
        II.getInputArg().renderAsInput(Args, CmdArgs);
5137
0
    }
5138
5139
0
    C.addCommand(std::make_unique<Command>(
5140
0
        JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
5141
0
        CmdArgs, Inputs, Output, D.getPrependArg()));
5142
0
    return;
5143
0
  }
5144
5145
0
  if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5146
0
    CmdArgs.push_back("-fembed-bitcode=marker");
5147
5148
  // We normally speed up the clang process a bit by skipping destructors at
5149
  // exit, but when we're generating diagnostics we can rely on some of the
5150
  // cleanup.
5151
0
  if (!C.isForDiagnostics())
5152
0
    CmdArgs.push_back("-disable-free");
5153
0
  CmdArgs.push_back("-clear-ast-before-backend");
5154
5155
#ifdef NDEBUG
5156
  const bool IsAssertBuild = false;
5157
#else
5158
0
  const bool IsAssertBuild = true;
5159
0
#endif
5160
5161
  // Disable the verification pass in asserts builds unless otherwise specified.
5162
0
  if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5163
0
                   options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5164
0
    CmdArgs.push_back("-disable-llvm-verifier");
5165
0
  }
5166
5167
  // Discard value names in assert builds unless otherwise specified.
5168
0
  if (Args.hasFlag(options::OPT_fdiscard_value_names,
5169
0
                   options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5170
0
    if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5171
0
        llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5172
0
          return types::isLLVMIR(II.getType());
5173
0
        })) {
5174
0
      D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5175
0
    }
5176
0
    CmdArgs.push_back("-discard-value-names");
5177
0
  }
5178
5179
  // Set the main file name, so that debug info works even with
5180
  // -save-temps.
5181
0
  CmdArgs.push_back("-main-file-name");
5182
0
  CmdArgs.push_back(getBaseInputName(Args, Input));
5183
5184
  // Some flags which affect the language (via preprocessor
5185
  // defines).
5186
0
  if (Args.hasArg(options::OPT_static))
5187
0
    CmdArgs.push_back("-static-define");
5188
5189
0
  if (Args.hasArg(options::OPT_municode))
5190
0
    CmdArgs.push_back("-DUNICODE");
5191
5192
0
  if (isa<AnalyzeJobAction>(JA))
5193
0
    RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5194
5195
0
  if (isa<AnalyzeJobAction>(JA) ||
5196
0
      (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5197
0
    CmdArgs.push_back("-setup-static-analyzer");
5198
5199
  // Enable compatilibily mode to avoid analyzer-config related errors.
5200
  // Since we can't access frontend flags through hasArg, let's manually iterate
5201
  // through them.
5202
0
  bool FoundAnalyzerConfig = false;
5203
0
  for (auto *Arg : Args.filtered(options::OPT_Xclang))
5204
0
    if (StringRef(Arg->getValue()) == "-analyzer-config") {
5205
0
      FoundAnalyzerConfig = true;
5206
0
      break;
5207
0
    }
5208
0
  if (!FoundAnalyzerConfig)
5209
0
    for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5210
0
      if (StringRef(Arg->getValue()) == "-analyzer-config") {
5211
0
        FoundAnalyzerConfig = true;
5212
0
        break;
5213
0
      }
5214
0
  if (FoundAnalyzerConfig)
5215
0
    CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5216
5217
0
  CheckCodeGenerationOptions(D, Args);
5218
5219
0
  unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5220
0
  assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5221
0
  if (FunctionAlignment) {
5222
0
    CmdArgs.push_back("-function-alignment");
5223
0
    CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5224
0
  }
5225
5226
  // We support -falign-loops=N where N is a power of 2. GCC supports more
5227
  // forms.
5228
0
  if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5229
0
    unsigned Value = 0;
5230
0
    if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5231
0
      TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5232
0
          << A->getAsString(Args) << A->getValue();
5233
0
    else if (Value & (Value - 1))
5234
0
      TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5235
0
          << A->getAsString(Args) << A->getValue();
5236
    // Treat =0 as unspecified (use the target preference).
5237
0
    if (Value)
5238
0
      CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5239
0
                                           Twine(std::min(Value, 65536u))));
5240
0
  }
5241
5242
0
  if (Triple.isOSzOS()) {
5243
    // On z/OS some of the system header feature macros need to
5244
    // be defined to enable most cross platform projects to build
5245
    // successfully.  Ths include the libc++ library.  A
5246
    // complicating factor is that users can define these
5247
    // macros to the same or different values.  We need to add
5248
    // the definition for these macros to the compilation command
5249
    // if the user hasn't already defined them.
5250
5251
0
    auto findMacroDefinition = [&](const std::string &Macro) {
5252
0
      auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5253
0
      return llvm::any_of(MacroDefs, [&](const std::string &M) {
5254
0
        return M == Macro || M.find(Macro + '=') != std::string::npos;
5255
0
      });
5256
0
    };
5257
5258
    // _UNIX03_WITHDRAWN is required for libcxx & porting.
5259
0
    if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5260
0
      CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5261
    // _OPEN_DEFAULT is required for XL compat
5262
0
    if (!findMacroDefinition("_OPEN_DEFAULT"))
5263
0
      CmdArgs.push_back("-D_OPEN_DEFAULT");
5264
0
    if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5265
      // _XOPEN_SOURCE=600 is required for libcxx.
5266
0
      if (!findMacroDefinition("_XOPEN_SOURCE"))
5267
0
        CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5268
0
    }
5269
0
  }
5270
5271
0
  llvm::Reloc::Model RelocationModel;
5272
0
  unsigned PICLevel;
5273
0
  bool IsPIE;
5274
0
  std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5275
0
  Arg *LastPICDataRelArg =
5276
0
      Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5277
0
                      options::OPT_mpic_data_is_text_relative);
5278
0
  bool NoPICDataIsTextRelative = false;
5279
0
  if (LastPICDataRelArg) {
5280
0
    if (LastPICDataRelArg->getOption().matches(
5281
0
            options::OPT_mno_pic_data_is_text_relative)) {
5282
0
      NoPICDataIsTextRelative = true;
5283
0
      if (!PICLevel)
5284
0
        D.Diag(diag::err_drv_argument_only_allowed_with)
5285
0
            << "-mno-pic-data-is-text-relative"
5286
0
            << "-fpic/-fpie";
5287
0
    }
5288
0
    if (!Triple.isSystemZ())
5289
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5290
0
          << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5291
0
                                      : "-mpic-data-is-text-relative")
5292
0
          << RawTriple.str();
5293
0
  }
5294
5295
0
  bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5296
0
                RelocationModel == llvm::Reloc::ROPI_RWPI;
5297
0
  bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5298
0
                RelocationModel == llvm::Reloc::ROPI_RWPI;
5299
5300
0
  if (Args.hasArg(options::OPT_mcmse) &&
5301
0
      !Args.hasArg(options::OPT_fallow_unsupported)) {
5302
0
    if (IsROPI)
5303
0
      D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5304
0
    if (IsRWPI)
5305
0
      D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5306
0
  }
5307
5308
0
  if (IsROPI && types::isCXX(Input.getType()) &&
5309
0
      !Args.hasArg(options::OPT_fallow_unsupported))
5310
0
    D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5311
5312
0
  const char *RMName = RelocationModelName(RelocationModel);
5313
0
  if (RMName) {
5314
0
    CmdArgs.push_back("-mrelocation-model");
5315
0
    CmdArgs.push_back(RMName);
5316
0
  }
5317
0
  if (PICLevel > 0) {
5318
0
    CmdArgs.push_back("-pic-level");
5319
0
    CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5320
0
    if (IsPIE)
5321
0
      CmdArgs.push_back("-pic-is-pie");
5322
0
    if (NoPICDataIsTextRelative)
5323
0
      CmdArgs.push_back("-mcmodel=medium");
5324
0
  }
5325
5326
0
  if (RelocationModel == llvm::Reloc::ROPI ||
5327
0
      RelocationModel == llvm::Reloc::ROPI_RWPI)
5328
0
    CmdArgs.push_back("-fropi");
5329
0
  if (RelocationModel == llvm::Reloc::RWPI ||
5330
0
      RelocationModel == llvm::Reloc::ROPI_RWPI)
5331
0
    CmdArgs.push_back("-frwpi");
5332
5333
0
  if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5334
0
    CmdArgs.push_back("-meabi");
5335
0
    CmdArgs.push_back(A->getValue());
5336
0
  }
5337
5338
  // -fsemantic-interposition is forwarded to CC1: set the
5339
  // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5340
  // make default visibility external linkage definitions dso_preemptable.
5341
  //
5342
  // -fno-semantic-interposition: if the target supports .Lfoo$local local
5343
  // aliases (make default visibility external linkage definitions dso_local).
5344
  // This is the CC1 default for ELF to match COFF/Mach-O.
5345
  //
5346
  // Otherwise use Clang's traditional behavior: like
5347
  // -fno-semantic-interposition but local aliases are not used. So references
5348
  // can be interposed if not optimized out.
5349
0
  if (Triple.isOSBinFormatELF()) {
5350
0
    Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5351
0
                             options::OPT_fno_semantic_interposition);
5352
0
    if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5353
      // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5354
0
      bool SupportsLocalAlias =
5355
0
          Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5356
0
      if (!A)
5357
0
        CmdArgs.push_back("-fhalf-no-semantic-interposition");
5358
0
      else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5359
0
        A->render(Args, CmdArgs);
5360
0
      else if (!SupportsLocalAlias)
5361
0
        CmdArgs.push_back("-fhalf-no-semantic-interposition");
5362
0
    }
5363
0
  }
5364
5365
0
  {
5366
0
    std::string Model;
5367
0
    if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5368
0
      if (!TC.isThreadModelSupported(A->getValue()))
5369
0
        D.Diag(diag::err_drv_invalid_thread_model_for_target)
5370
0
            << A->getValue() << A->getAsString(Args);
5371
0
      Model = A->getValue();
5372
0
    } else
5373
0
      Model = TC.getThreadModel();
5374
0
    if (Model != "posix") {
5375
0
      CmdArgs.push_back("-mthread-model");
5376
0
      CmdArgs.push_back(Args.MakeArgString(Model));
5377
0
    }
5378
0
  }
5379
5380
0
  if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5381
0
    StringRef Name = A->getValue();
5382
0
    if (Name == "SVML") {
5383
0
      if (Triple.getArch() != llvm::Triple::x86 &&
5384
0
          Triple.getArch() != llvm::Triple::x86_64)
5385
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
5386
0
            << Name << Triple.getArchName();
5387
0
    } else if (Name == "LIBMVEC-X86") {
5388
0
      if (Triple.getArch() != llvm::Triple::x86 &&
5389
0
          Triple.getArch() != llvm::Triple::x86_64)
5390
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
5391
0
            << Name << Triple.getArchName();
5392
0
    } else if (Name == "SLEEF" || Name == "ArmPL") {
5393
0
      if (Triple.getArch() != llvm::Triple::aarch64 &&
5394
0
          Triple.getArch() != llvm::Triple::aarch64_be)
5395
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
5396
0
            << Name << Triple.getArchName();
5397
0
    }
5398
0
    A->render(Args, CmdArgs);
5399
0
  }
5400
5401
0
  if (Args.hasFlag(options::OPT_fmerge_all_constants,
5402
0
                   options::OPT_fno_merge_all_constants, false))
5403
0
    CmdArgs.push_back("-fmerge-all-constants");
5404
5405
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5406
0
                     options::OPT_fno_delete_null_pointer_checks);
5407
5408
  // LLVM Code Generator Options.
5409
5410
0
  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5411
0
    if (!Triple.isOSAIX() || Triple.isPPC32())
5412
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5413
0
        << A->getSpelling() << RawTriple.str();
5414
0
    CmdArgs.push_back("-mabi=quadword-atomics");
5415
0
  }
5416
5417
0
  if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5418
    // Emit the unsupported option error until the Clang's library integration
5419
    // support for 128-bit long double is available for AIX.
5420
0
    if (Triple.isOSAIX())
5421
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5422
0
          << A->getSpelling() << RawTriple.str();
5423
0
  }
5424
5425
0
  if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5426
0
    StringRef V = A->getValue(), V1 = V;
5427
0
    unsigned Size;
5428
0
    if (V1.consumeInteger(10, Size) || !V1.empty())
5429
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
5430
0
          << V << A->getOption().getName();
5431
0
    else
5432
0
      CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5433
0
  }
5434
5435
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5436
0
                     options::OPT_fno_jump_tables);
5437
0
  Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5438
0
                    options::OPT_fno_profile_sample_accurate);
5439
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5440
0
                     options::OPT_fno_preserve_as_comments);
5441
5442
0
  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5443
0
    CmdArgs.push_back("-mregparm");
5444
0
    CmdArgs.push_back(A->getValue());
5445
0
  }
5446
5447
0
  if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5448
0
                               options::OPT_msvr4_struct_return)) {
5449
0
    if (!TC.getTriple().isPPC32()) {
5450
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5451
0
          << A->getSpelling() << RawTriple.str();
5452
0
    } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5453
0
      CmdArgs.push_back("-maix-struct-return");
5454
0
    } else {
5455
0
      assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5456
0
      CmdArgs.push_back("-msvr4-struct-return");
5457
0
    }
5458
0
  }
5459
5460
0
  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5461
0
                               options::OPT_freg_struct_return)) {
5462
0
    if (TC.getArch() != llvm::Triple::x86) {
5463
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5464
0
          << A->getSpelling() << RawTriple.str();
5465
0
    } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5466
0
      CmdArgs.push_back("-fpcc-struct-return");
5467
0
    } else {
5468
0
      assert(A->getOption().matches(options::OPT_freg_struct_return));
5469
0
      CmdArgs.push_back("-freg-struct-return");
5470
0
    }
5471
0
  }
5472
5473
0
  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5474
0
    if (Triple.getArch() == llvm::Triple::m68k)
5475
0
      CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
5476
0
    else
5477
0
      CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5478
0
  }
5479
5480
0
  if (Args.hasArg(options::OPT_fenable_matrix)) {
5481
    // enable-matrix is needed by both the LangOpts and by LLVM.
5482
0
    CmdArgs.push_back("-fenable-matrix");
5483
0
    CmdArgs.push_back("-mllvm");
5484
0
    CmdArgs.push_back("-enable-matrix");
5485
0
  }
5486
5487
0
  CodeGenOptions::FramePointerKind FPKeepKind =
5488
0
                  getFramePointerKind(Args, RawTriple);
5489
0
  const char *FPKeepKindStr = nullptr;
5490
0
  switch (FPKeepKind) {
5491
0
  case CodeGenOptions::FramePointerKind::None:
5492
0
    FPKeepKindStr = "-mframe-pointer=none";
5493
0
    break;
5494
0
  case CodeGenOptions::FramePointerKind::NonLeaf:
5495
0
    FPKeepKindStr = "-mframe-pointer=non-leaf";
5496
0
    break;
5497
0
  case CodeGenOptions::FramePointerKind::All:
5498
0
    FPKeepKindStr = "-mframe-pointer=all";
5499
0
    break;
5500
0
  }
5501
0
  assert(FPKeepKindStr && "unknown FramePointerKind");
5502
0
  CmdArgs.push_back(FPKeepKindStr);
5503
5504
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5505
0
                     options::OPT_fno_zero_initialized_in_bss);
5506
5507
0
  bool OFastEnabled = isOptimizationLevelFast(Args);
5508
  // If -Ofast is the optimization level, then -fstrict-aliasing should be
5509
  // enabled.  This alias option is being used to simplify the hasFlag logic.
5510
0
  OptSpecifier StrictAliasingAliasOption =
5511
0
      OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5512
  // We turn strict aliasing off by default if we're in CL mode, since MSVC
5513
  // doesn't do any TBAA.
5514
0
  bool TBAAOnByDefault = !D.IsCLMode();
5515
0
  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5516
0
                    options::OPT_fno_strict_aliasing, TBAAOnByDefault))
5517
0
    CmdArgs.push_back("-relaxed-aliasing");
5518
0
  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5519
0
                    options::OPT_fno_struct_path_tbaa, true))
5520
0
    CmdArgs.push_back("-no-struct-path-tbaa");
5521
0
  Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5522
0
                    options::OPT_fno_strict_enums);
5523
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5524
0
                     options::OPT_fno_strict_return);
5525
0
  Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5526
0
                    options::OPT_fno_allow_editor_placeholders);
5527
0
  Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5528
0
                    options::OPT_fno_strict_vtable_pointers);
5529
0
  Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5530
0
                    options::OPT_fno_force_emit_vtables);
5531
0
  Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5532
0
                     options::OPT_fno_optimize_sibling_calls);
5533
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5534
0
                     options::OPT_fno_escaping_block_tail_calls);
5535
5536
0
  Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5537
0
                  options::OPT_fno_fine_grained_bitfield_accesses);
5538
5539
0
  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5540
0
                  options::OPT_fno_experimental_relative_cxx_abi_vtables);
5541
5542
0
  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
5543
0
                  options::OPT_fno_experimental_omit_vtable_rtti);
5544
5545
  // Handle segmented stacks.
5546
0
  Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5547
0
                    options::OPT_fno_split_stack);
5548
5549
  // -fprotect-parens=0 is default.
5550
0
  if (Args.hasFlag(options::OPT_fprotect_parens,
5551
0
                   options::OPT_fno_protect_parens, false))
5552
0
    CmdArgs.push_back("-fprotect-parens");
5553
5554
0
  RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5555
5556
0
  if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5557
0
    const llvm::Triple::ArchType Arch = TC.getArch();
5558
0
    if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5559
0
      StringRef V = A->getValue();
5560
0
      if (V == "64")
5561
0
        CmdArgs.push_back("-fextend-arguments=64");
5562
0
      else if (V != "32")
5563
0
        D.Diag(diag::err_drv_invalid_argument_to_option)
5564
0
            << A->getValue() << A->getOption().getName();
5565
0
    } else
5566
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5567
0
          << A->getOption().getName() << TripleStr;
5568
0
  }
5569
5570
0
  if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5571
0
    if (TC.getArch() == llvm::Triple::avr)
5572
0
      A->render(Args, CmdArgs);
5573
0
    else
5574
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5575
0
          << A->getAsString(Args) << TripleStr;
5576
0
  }
5577
5578
0
  if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5579
0
    if (TC.getTriple().isX86())
5580
0
      A->render(Args, CmdArgs);
5581
0
    else if (TC.getTriple().isPPC() &&
5582
0
             (A->getOption().getID() != options::OPT_mlong_double_80))
5583
0
      A->render(Args, CmdArgs);
5584
0
    else
5585
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5586
0
          << A->getAsString(Args) << TripleStr;
5587
0
  }
5588
5589
  // Decide whether to use verbose asm. Verbose assembly is the default on
5590
  // toolchains which have the integrated assembler on by default.
5591
0
  bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5592
0
  if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5593
0
                    IsIntegratedAssemblerDefault))
5594
0
    CmdArgs.push_back("-fno-verbose-asm");
5595
5596
  // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5597
  // use that to indicate the MC default in the backend.
5598
0
  if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5599
0
    StringRef V = A->getValue();
5600
0
    unsigned Num;
5601
0
    if (V == "none")
5602
0
      A->render(Args, CmdArgs);
5603
0
    else if (!V.consumeInteger(10, Num) && Num > 0 &&
5604
0
             (V.empty() || (V.consume_front(".") &&
5605
0
                            !V.consumeInteger(10, Num) && V.empty())))
5606
0
      A->render(Args, CmdArgs);
5607
0
    else
5608
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
5609
0
          << A->getValue() << A->getOption().getName();
5610
0
  }
5611
5612
  // If toolchain choose to use MCAsmParser for inline asm don't pass the
5613
  // option to disable integrated-as explictly.
5614
0
  if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5615
0
    CmdArgs.push_back("-no-integrated-as");
5616
5617
0
  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5618
0
    CmdArgs.push_back("-mdebug-pass");
5619
0
    CmdArgs.push_back("Structure");
5620
0
  }
5621
0
  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5622
0
    CmdArgs.push_back("-mdebug-pass");
5623
0
    CmdArgs.push_back("Arguments");
5624
0
  }
5625
5626
  // Enable -mconstructor-aliases except on darwin, where we have to work around
5627
  // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5628
  // code, where aliases aren't supported.
5629
0
  if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5630
0
    CmdArgs.push_back("-mconstructor-aliases");
5631
5632
  // Darwin's kernel doesn't support guard variables; just die if we
5633
  // try to use them.
5634
0
  if (KernelOrKext && RawTriple.isOSDarwin())
5635
0
    CmdArgs.push_back("-fforbid-guard-variables");
5636
5637
0
  if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5638
0
                   Triple.isWindowsGNUEnvironment())) {
5639
0
    CmdArgs.push_back("-mms-bitfields");
5640
0
  }
5641
5642
0
  if (Triple.isWindowsGNUEnvironment()) {
5643
0
    Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
5644
0
                       options::OPT_fno_auto_import);
5645
0
  }
5646
5647
0
  if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
5648
0
                   Triple.isX86() && D.IsCLMode()))
5649
0
    CmdArgs.push_back("-fms-volatile");
5650
5651
  // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5652
  // defaults to -fno-direct-access-external-data. Pass the option if different
5653
  // from the default.
5654
0
  if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5655
0
                               options::OPT_fno_direct_access_external_data)) {
5656
0
    if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5657
0
        (PICLevel == 0))
5658
0
      A->render(Args, CmdArgs);
5659
0
  } else if (PICLevel == 0 && Triple.isLoongArch()) {
5660
    // Some targets default to -fno-direct-access-external-data even for
5661
    // -fno-pic.
5662
0
    CmdArgs.push_back("-fno-direct-access-external-data");
5663
0
  }
5664
5665
0
  if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5666
0
    CmdArgs.push_back("-fno-plt");
5667
0
  }
5668
5669
  // -fhosted is default.
5670
  // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5671
  // use Freestanding.
5672
0
  bool Freestanding =
5673
0
      Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5674
0
      KernelOrKext;
5675
0
  if (Freestanding)
5676
0
    CmdArgs.push_back("-ffreestanding");
5677
5678
0
  Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
5679
5680
  // This is a coarse approximation of what llvm-gcc actually does, both
5681
  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5682
  // complicated ways.
5683
0
  auto SanitizeArgs = TC.getSanitizerArgs(Args);
5684
5685
0
  bool IsAsyncUnwindTablesDefault =
5686
0
      TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
5687
0
  bool IsSyncUnwindTablesDefault =
5688
0
      TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
5689
5690
0
  bool AsyncUnwindTables = Args.hasFlag(
5691
0
      options::OPT_fasynchronous_unwind_tables,
5692
0
      options::OPT_fno_asynchronous_unwind_tables,
5693
0
      (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
5694
0
          !Freestanding);
5695
0
  bool UnwindTables =
5696
0
      Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5697
0
                   IsSyncUnwindTablesDefault && !Freestanding);
5698
0
  if (AsyncUnwindTables)
5699
0
    CmdArgs.push_back("-funwind-tables=2");
5700
0
  else if (UnwindTables)
5701
0
     CmdArgs.push_back("-funwind-tables=1");
5702
5703
  // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5704
  // `--gpu-use-aux-triple-only` is specified.
5705
0
  if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5706
0
      (IsCudaDevice || IsHIPDevice)) {
5707
0
    const ArgList &HostArgs =
5708
0
        C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5709
0
    std::string HostCPU =
5710
0
        getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5711
0
    if (!HostCPU.empty()) {
5712
0
      CmdArgs.push_back("-aux-target-cpu");
5713
0
      CmdArgs.push_back(Args.MakeArgString(HostCPU));
5714
0
    }
5715
0
    getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5716
0
                      /*ForAS*/ false, /*IsAux*/ true);
5717
0
  }
5718
5719
0
  TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5720
5721
0
  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5722
0
    StringRef CM = A->getValue();
5723
0
    bool Ok = false;
5724
0
    if (Triple.isOSAIX() && CM == "medium")
5725
0
      CM = "large";
5726
0
    if (Triple.isAArch64(64)) {
5727
0
      Ok = CM == "tiny" || CM == "small" || CM == "large";
5728
0
      if (CM == "large" && RelocationModel != llvm::Reloc::Static)
5729
0
        D.Diag(diag::err_drv_argument_only_allowed_with)
5730
0
            << A->getAsString(Args) << "-fno-pic";
5731
0
    } else if (Triple.isLoongArch()) {
5732
0
      if (CM == "extreme" &&
5733
0
          Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false))
5734
0
        D.Diag(diag::err_drv_argument_not_allowed_with)
5735
0
            << A->getAsString(Args) << "-fplt";
5736
0
      Ok = CM == "normal" || CM == "medium" || CM == "extreme";
5737
      // Convert to LLVM recognizable names.
5738
0
      if (Ok)
5739
0
        CM = llvm::StringSwitch<StringRef>(CM)
5740
0
                 .Case("normal", "small")
5741
0
                 .Case("extreme", "large")
5742
0
                 .Default(CM);
5743
0
    } else if (Triple.isPPC64() || Triple.isOSAIX()) {
5744
0
      Ok = CM == "small" || CM == "medium" || CM == "large";
5745
0
    } else if (Triple.isRISCV()) {
5746
0
      if (CM == "medlow")
5747
0
        CM = "small";
5748
0
      else if (CM == "medany")
5749
0
        CM = "medium";
5750
0
      Ok = CM == "small" || CM == "medium";
5751
0
    } else if (Triple.getArch() == llvm::Triple::x86_64) {
5752
0
      Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"},
5753
0
                              CM);
5754
0
    } else if (Triple.isNVPTX() || Triple.isAMDGPU()) {
5755
      // NVPTX/AMDGPU does not care about the code model and will accept
5756
      // whatever works for the host.
5757
0
      Ok = true;
5758
0
    }
5759
0
    if (Ok) {
5760
0
      CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM));
5761
0
    } else {
5762
0
      D.Diag(diag::err_drv_unsupported_option_argument_for_target)
5763
0
          << A->getSpelling() << CM << TripleStr;
5764
0
    }
5765
0
  }
5766
5767
0
  if (Triple.getArch() == llvm::Triple::x86_64) {
5768
0
    bool IsMediumCM = false;
5769
0
    bool IsLargeCM = false;
5770
0
    if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5771
0
      IsMediumCM = StringRef(A->getValue()) == "medium";
5772
0
      IsLargeCM = StringRef(A->getValue()) == "large";
5773
0
    }
5774
0
    if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) {
5775
0
      if (!IsMediumCM && !IsLargeCM) {
5776
0
        D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model)
5777
0
            << A->getOption().getRenderName();
5778
0
      } else {
5779
0
        A->render(Args, CmdArgs);
5780
0
      }
5781
0
    } else if (IsMediumCM) {
5782
0
      CmdArgs.push_back("-mlarge-data-threshold=65536");
5783
0
    } else if (IsLargeCM) {
5784
0
      CmdArgs.push_back("-mlarge-data-threshold=0");
5785
0
    }
5786
0
  }
5787
5788
0
  if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5789
0
    StringRef Value = A->getValue();
5790
0
    unsigned TLSSize = 0;
5791
0
    Value.getAsInteger(10, TLSSize);
5792
0
    if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5793
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5794
0
          << A->getOption().getName() << TripleStr;
5795
0
    if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5796
0
      D.Diag(diag::err_drv_invalid_int_value)
5797
0
          << A->getOption().getName() << Value;
5798
0
    Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5799
0
  }
5800
5801
  // Add the target cpu
5802
0
  std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
5803
0
  if (!CPU.empty()) {
5804
0
    CmdArgs.push_back("-target-cpu");
5805
0
    CmdArgs.push_back(Args.MakeArgString(CPU));
5806
0
  }
5807
5808
0
  RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5809
5810
  // Add clang-cl arguments.
5811
0
  types::ID InputType = Input.getType();
5812
0
  if (D.IsCLMode())
5813
0
    AddClangCLArgs(Args, InputType, CmdArgs);
5814
5815
0
  llvm::codegenoptions::DebugInfoKind DebugInfoKind =
5816
0
      llvm::codegenoptions::NoDebugInfo;
5817
0
  DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5818
0
  renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
5819
0
                     CmdArgs, Output, DebugInfoKind, DwarfFission);
5820
5821
  // Add the split debug info name to the command lines here so we
5822
  // can propagate it to the backend.
5823
0
  bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5824
0
                    (TC.getTriple().isOSBinFormatELF() ||
5825
0
                     TC.getTriple().isOSBinFormatWasm() ||
5826
0
                     TC.getTriple().isOSBinFormatCOFF()) &&
5827
0
                    (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5828
0
                     isa<BackendJobAction>(JA));
5829
0
  if (SplitDWARF) {
5830
0
    const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5831
0
    CmdArgs.push_back("-split-dwarf-file");
5832
0
    CmdArgs.push_back(SplitDWARFOut);
5833
0
    if (DwarfFission == DwarfFissionKind::Split) {
5834
0
      CmdArgs.push_back("-split-dwarf-output");
5835
0
      CmdArgs.push_back(SplitDWARFOut);
5836
0
    }
5837
0
  }
5838
5839
  // Pass the linker version in use.
5840
0
  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5841
0
    CmdArgs.push_back("-target-linker-version");
5842
0
    CmdArgs.push_back(A->getValue());
5843
0
  }
5844
5845
  // Explicitly error on some things we know we don't support and can't just
5846
  // ignore.
5847
0
  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5848
0
    Arg *Unsupported;
5849
0
    if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5850
0
        TC.getArch() == llvm::Triple::x86) {
5851
0
      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5852
0
          (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5853
0
        D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5854
0
            << Unsupported->getOption().getName();
5855
0
    }
5856
    // The faltivec option has been superseded by the maltivec option.
5857
0
    if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5858
0
      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5859
0
          << Unsupported->getOption().getName()
5860
0
          << "please use -maltivec and include altivec.h explicitly";
5861
0
    if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5862
0
      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5863
0
          << Unsupported->getOption().getName() << "please use -mno-altivec";
5864
0
  }
5865
5866
0
  Args.AddAllArgs(CmdArgs, options::OPT_v);
5867
5868
0
  if (Args.getLastArg(options::OPT_H)) {
5869
0
    CmdArgs.push_back("-H");
5870
0
    CmdArgs.push_back("-sys-header-deps");
5871
0
  }
5872
0
  Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5873
5874
0
  if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
5875
0
    CmdArgs.push_back("-header-include-file");
5876
0
    CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5877
0
                          ? D.CCPrintHeadersFilename.c_str()
5878
0
                          : "-");
5879
0
    CmdArgs.push_back("-sys-header-deps");
5880
0
    CmdArgs.push_back(Args.MakeArgString(
5881
0
        "-header-include-format=" +
5882
0
        std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
5883
0
    CmdArgs.push_back(
5884
0
        Args.MakeArgString("-header-include-filtering=" +
5885
0
                           std::string(headerIncludeFilteringKindToString(
5886
0
                               D.CCPrintHeadersFiltering))));
5887
0
  }
5888
0
  Args.AddLastArg(CmdArgs, options::OPT_P);
5889
0
  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5890
5891
0
  if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5892
0
    CmdArgs.push_back("-diagnostic-log-file");
5893
0
    CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5894
0
                          ? D.CCLogDiagnosticsFilename.c_str()
5895
0
                          : "-");
5896
0
  }
5897
5898
  // Give the gen diagnostics more chances to succeed, by avoiding intentional
5899
  // crashes.
5900
0
  if (D.CCGenDiagnostics)
5901
0
    CmdArgs.push_back("-disable-pragma-debug-crash");
5902
5903
  // Allow backend to put its diagnostic files in the same place as frontend
5904
  // crash diagnostics files.
5905
0
  if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5906
0
    StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5907
0
    CmdArgs.push_back("-mllvm");
5908
0
    CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5909
0
  }
5910
5911
0
  bool UseSeparateSections = isUseSeparateSections(Triple);
5912
5913
0
  if (Args.hasFlag(options::OPT_ffunction_sections,
5914
0
                   options::OPT_fno_function_sections, UseSeparateSections)) {
5915
0
    CmdArgs.push_back("-ffunction-sections");
5916
0
  }
5917
5918
0
  if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5919
0
    StringRef Val = A->getValue();
5920
0
    if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5921
0
      if (Val != "all" && Val != "labels" && Val != "none" &&
5922
0
          !Val.starts_with("list="))
5923
0
        D.Diag(diag::err_drv_invalid_value)
5924
0
            << A->getAsString(Args) << A->getValue();
5925
0
      else
5926
0
        A->render(Args, CmdArgs);
5927
0
    } else if (Triple.isNVPTX()) {
5928
      // Do not pass the option to the GPU compilation. We still want it enabled
5929
      // for the host-side compilation, so seeing it here is not an error.
5930
0
    } else if (Val != "none") {
5931
      // =none is allowed everywhere. It's useful for overriding the option
5932
      // and is the same as not specifying the option.
5933
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
5934
0
          << A->getAsString(Args) << TripleStr;
5935
0
    }
5936
0
  }
5937
5938
0
  bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5939
0
  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5940
0
                   UseSeparateSections || HasDefaultDataSections)) {
5941
0
    CmdArgs.push_back("-fdata-sections");
5942
0
  }
5943
5944
0
  Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
5945
0
                     options::OPT_fno_unique_section_names);
5946
0
  Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
5947
0
                    options::OPT_fno_unique_internal_linkage_names);
5948
0
  Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
5949
0
                    options::OPT_fno_unique_basic_block_section_names);
5950
0
  Args.addOptInFlag(CmdArgs, options::OPT_fconvergent_functions,
5951
0
                    options::OPT_fno_convergent_functions);
5952
5953
0
  if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5954
0
                               options::OPT_fno_split_machine_functions)) {
5955
0
    if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
5956
      // This codegen pass is only available on x86 and AArch64 ELF targets.
5957
0
      if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
5958
0
        A->render(Args, CmdArgs);
5959
0
      else
5960
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
5961
0
            << A->getAsString(Args) << TripleStr;
5962
0
    }
5963
0
  }
5964
5965
0
  Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5966
0
                  options::OPT_finstrument_functions_after_inlining,
5967
0
                  options::OPT_finstrument_function_entry_bare);
5968
5969
  // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5970
  // for sampling, overhead of call arc collection is way too high and there's
5971
  // no way to collect the output.
5972
0
  if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5973
0
    addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
5974
5975
0
  Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5976
5977
0
  if (getLastProfileSampleUseArg(Args) &&
5978
0
      Args.hasArg(options::OPT_fsample_profile_use_profi)) {
5979
0
    CmdArgs.push_back("-mllvm");
5980
0
    CmdArgs.push_back("-sample-profile-use-profi");
5981
0
  }
5982
5983
  // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
5984
0
  if (RawTriple.isPS() &&
5985
0
      !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5986
0
    PScpu::addProfileRTArgs(TC, Args, CmdArgs);
5987
0
    PScpu::addSanitizerArgs(TC, Args, CmdArgs);
5988
0
  }
5989
5990
  // Pass options for controlling the default header search paths.
5991
0
  if (Args.hasArg(options::OPT_nostdinc)) {
5992
0
    CmdArgs.push_back("-nostdsysteminc");
5993
0
    CmdArgs.push_back("-nobuiltininc");
5994
0
  } else {
5995
0
    if (Args.hasArg(options::OPT_nostdlibinc))
5996
0
      CmdArgs.push_back("-nostdsysteminc");
5997
0
    Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5998
0
    Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5999
0
  }
6000
6001
  // Pass the path to compiler resource files.
6002
0
  CmdArgs.push_back("-resource-dir");
6003
0
  CmdArgs.push_back(D.ResourceDir.c_str());
6004
6005
0
  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6006
6007
0
  RenderARCMigrateToolOptions(D, Args, CmdArgs);
6008
6009
  // Add preprocessing options like -I, -D, etc. if we are using the
6010
  // preprocessor.
6011
  //
6012
  // FIXME: Support -fpreprocessed
6013
0
  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
6014
0
    AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6015
6016
  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6017
  // that "The compiler can only warn and ignore the option if not recognized".
6018
  // When building with ccache, it will pass -D options to clang even on
6019
  // preprocessed inputs and configure concludes that -fPIC is not supported.
6020
0
  Args.ClaimAllArgs(options::OPT_D);
6021
6022
  // Manually translate -O4 to -O3; let clang reject others.
6023
0
  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
6024
0
    if (A->getOption().matches(options::OPT_O4)) {
6025
0
      CmdArgs.push_back("-O3");
6026
0
      D.Diag(diag::warn_O4_is_O3);
6027
0
    } else {
6028
0
      A->render(Args, CmdArgs);
6029
0
    }
6030
0
  }
6031
6032
  // Warn about ignored options to clang.
6033
0
  for (const Arg *A :
6034
0
       Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6035
0
    D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6036
0
    A->claim();
6037
0
  }
6038
6039
0
  for (const Arg *A :
6040
0
       Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6041
0
    D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6042
0
    A->claim();
6043
0
  }
6044
6045
0
  claimNoWarnArgs(Args);
6046
6047
0
  Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6048
6049
0
  for (const Arg *A :
6050
0
       Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6051
0
    A->claim();
6052
0
    if (A->getOption().getID() == options::OPT__SLASH_wd) {
6053
0
      unsigned WarningNumber;
6054
0
      if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6055
0
        D.Diag(diag::err_drv_invalid_int_value)
6056
0
            << A->getAsString(Args) << A->getValue();
6057
0
        continue;
6058
0
      }
6059
6060
0
      if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6061
0
        CmdArgs.push_back(Args.MakeArgString(
6062
0
            "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6063
0
      }
6064
0
      continue;
6065
0
    }
6066
0
    A->render(Args, CmdArgs);
6067
0
  }
6068
6069
0
  Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6070
6071
0
  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6072
0
    CmdArgs.push_back("-pedantic");
6073
0
  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6074
0
  Args.AddLastArg(CmdArgs, options::OPT_w);
6075
6076
0
  Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6077
0
                    options::OPT_fno_fixed_point);
6078
6079
0
  if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6080
0
    A->render(Args, CmdArgs);
6081
6082
0
  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6083
0
                  options::OPT_fno_experimental_relative_cxx_abi_vtables);
6084
6085
0
  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6086
0
                  options::OPT_fno_experimental_omit_vtable_rtti);
6087
6088
0
  if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6089
0
    A->render(Args, CmdArgs);
6090
6091
  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6092
  // (-ansi is equivalent to -std=c89 or -std=c++98).
6093
  //
6094
  // If a std is supplied, only add -trigraphs if it follows the
6095
  // option.
6096
0
  bool ImplyVCPPCVer = false;
6097
0
  bool ImplyVCPPCXXVer = false;
6098
0
  const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6099
0
  if (Std) {
6100
0
    if (Std->getOption().matches(options::OPT_ansi))
6101
0
      if (types::isCXX(InputType))
6102
0
        CmdArgs.push_back("-std=c++98");
6103
0
      else
6104
0
        CmdArgs.push_back("-std=c89");
6105
0
    else
6106
0
      Std->render(Args, CmdArgs);
6107
6108
    // If -f(no-)trigraphs appears after the language standard flag, honor it.
6109
0
    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6110
0
                                 options::OPT_ftrigraphs,
6111
0
                                 options::OPT_fno_trigraphs))
6112
0
      if (A != Std)
6113
0
        A->render(Args, CmdArgs);
6114
0
  } else {
6115
    // Honor -std-default.
6116
    //
6117
    // FIXME: Clang doesn't correctly handle -std= when the input language
6118
    // doesn't match. For the time being just ignore this for C++ inputs;
6119
    // eventually we want to do all the standard defaulting here instead of
6120
    // splitting it between the driver and clang -cc1.
6121
0
    if (!types::isCXX(InputType)) {
6122
0
      if (!Args.hasArg(options::OPT__SLASH_std)) {
6123
0
        Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6124
0
                                  /*Joined=*/true);
6125
0
      } else
6126
0
        ImplyVCPPCVer = true;
6127
0
    }
6128
0
    else if (IsWindowsMSVC)
6129
0
      ImplyVCPPCXXVer = true;
6130
6131
0
    Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6132
0
                    options::OPT_fno_trigraphs);
6133
0
  }
6134
6135
  // GCC's behavior for -Wwrite-strings is a bit strange:
6136
  //  * In C, this "warning flag" changes the types of string literals from
6137
  //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6138
  //    for the discarded qualifier.
6139
  //  * In C++, this is just a normal warning flag.
6140
  //
6141
  // Implementing this warning correctly in C is hard, so we follow GCC's
6142
  // behavior for now. FIXME: Directly diagnose uses of a string literal as
6143
  // a non-const char* in C, rather than using this crude hack.
6144
0
  if (!types::isCXX(InputType)) {
6145
    // FIXME: This should behave just like a warning flag, and thus should also
6146
    // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6147
0
    Arg *WriteStrings =
6148
0
        Args.getLastArg(options::OPT_Wwrite_strings,
6149
0
                        options::OPT_Wno_write_strings, options::OPT_w);
6150
0
    if (WriteStrings &&
6151
0
        WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6152
0
      CmdArgs.push_back("-fconst-strings");
6153
0
  }
6154
6155
  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6156
  // during C++ compilation, which it is by default. GCC keeps this define even
6157
  // in the presence of '-w', match this behavior bug-for-bug.
6158
0
  if (types::isCXX(InputType) &&
6159
0
      Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6160
0
                   true)) {
6161
0
    CmdArgs.push_back("-fdeprecated-macro");
6162
0
  }
6163
6164
  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6165
0
  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6166
0
    if (Asm->getOption().matches(options::OPT_fasm))
6167
0
      CmdArgs.push_back("-fgnu-keywords");
6168
0
    else
6169
0
      CmdArgs.push_back("-fno-gnu-keywords");
6170
0
  }
6171
6172
0
  if (!ShouldEnableAutolink(Args, TC, JA))
6173
0
    CmdArgs.push_back("-fno-autolink");
6174
6175
0
  Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6176
0
  Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6177
0
  Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6178
0
  Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6179
6180
0
  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6181
6182
0
  if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6183
0
    CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6184
6185
0
  if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6186
0
    CmdArgs.push_back("-fbracket-depth");
6187
0
    CmdArgs.push_back(A->getValue());
6188
0
  }
6189
6190
0
  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6191
0
                               options::OPT_Wlarge_by_value_copy_def)) {
6192
0
    if (A->getNumValues()) {
6193
0
      StringRef bytes = A->getValue();
6194
0
      CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6195
0
    } else
6196
0
      CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6197
0
  }
6198
6199
0
  if (Args.hasArg(options::OPT_relocatable_pch))
6200
0
    CmdArgs.push_back("-relocatable-pch");
6201
6202
0
  if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6203
0
    static const char *kCFABIs[] = {
6204
0
      "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6205
0
    };
6206
6207
0
    if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6208
0
      D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6209
0
    else
6210
0
      A->render(Args, CmdArgs);
6211
0
  }
6212
6213
0
  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6214
0
    CmdArgs.push_back("-fconstant-string-class");
6215
0
    CmdArgs.push_back(A->getValue());
6216
0
  }
6217
6218
0
  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6219
0
    CmdArgs.push_back("-ftabstop");
6220
0
    CmdArgs.push_back(A->getValue());
6221
0
  }
6222
6223
0
  Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6224
0
                    options::OPT_fno_stack_size_section);
6225
6226
0
  if (Args.hasArg(options::OPT_fstack_usage)) {
6227
0
    CmdArgs.push_back("-stack-usage-file");
6228
6229
0
    if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6230
0
      SmallString<128> OutputFilename(OutputOpt->getValue());
6231
0
      llvm::sys::path::replace_extension(OutputFilename, "su");
6232
0
      CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6233
0
    } else
6234
0
      CmdArgs.push_back(
6235
0
          Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6236
0
  }
6237
6238
0
  CmdArgs.push_back("-ferror-limit");
6239
0
  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6240
0
    CmdArgs.push_back(A->getValue());
6241
0
  else
6242
0
    CmdArgs.push_back("19");
6243
6244
0
  Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6245
0
  Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6246
0
  Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6247
0
  Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6248
0
  Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6249
6250
  // Pass -fmessage-length=.
6251
0
  unsigned MessageLength = 0;
6252
0
  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6253
0
    StringRef V(A->getValue());
6254
0
    if (V.getAsInteger(0, MessageLength))
6255
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
6256
0
          << V << A->getOption().getName();
6257
0
  } else {
6258
    // If -fmessage-length=N was not specified, determine whether this is a
6259
    // terminal and, if so, implicitly define -fmessage-length appropriately.
6260
0
    MessageLength = llvm::sys::Process::StandardErrColumns();
6261
0
  }
6262
0
  if (MessageLength != 0)
6263
0
    CmdArgs.push_back(
6264
0
        Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6265
6266
0
  if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6267
0
    CmdArgs.push_back(
6268
0
        Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6269
6270
0
  if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6271
0
    CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6272
0
                                         Twine(A->getValue(0))));
6273
6274
  // -fvisibility= and -fvisibility-ms-compat are of a piece.
6275
0
  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6276
0
                                     options::OPT_fvisibility_ms_compat)) {
6277
0
    if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6278
0
      A->render(Args, CmdArgs);
6279
0
    } else {
6280
0
      assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6281
0
      CmdArgs.push_back("-fvisibility=hidden");
6282
0
      CmdArgs.push_back("-ftype-visibility=default");
6283
0
    }
6284
0
  } else if (IsOpenMPDevice) {
6285
    // When compiling for the OpenMP device we want protected visibility by
6286
    // default. This prevents the device from accidentally preempting code on
6287
    // the host, makes the system more robust, and improves performance.
6288
0
    CmdArgs.push_back("-fvisibility=protected");
6289
0
  }
6290
6291
  // PS4/PS5 process these options in addClangTargetOptions.
6292
0
  if (!RawTriple.isPS()) {
6293
0
    if (const Arg *A =
6294
0
            Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6295
0
                            options::OPT_fno_visibility_from_dllstorageclass)) {
6296
0
      if (A->getOption().matches(
6297
0
              options::OPT_fvisibility_from_dllstorageclass)) {
6298
0
        CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6299
0
        Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6300
0
        Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6301
0
        Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6302
0
        Args.AddLastArg(CmdArgs,
6303
0
                        options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6304
0
      }
6305
0
    }
6306
0
  }
6307
6308
0
  if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6309
0
                    options::OPT_fno_visibility_inlines_hidden, false))
6310
0
    CmdArgs.push_back("-fvisibility-inlines-hidden");
6311
6312
0
  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6313
0
                           options::OPT_fno_visibility_inlines_hidden_static_local_var);
6314
0
  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
6315
0
  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6316
6317
0
  if (Args.hasFlag(options::OPT_fnew_infallible,
6318
0
                   options::OPT_fno_new_infallible, false))
6319
0
    CmdArgs.push_back("-fnew-infallible");
6320
6321
0
  if (Args.hasFlag(options::OPT_fno_operator_names,
6322
0
                   options::OPT_foperator_names, false))
6323
0
    CmdArgs.push_back("-fno-operator-names");
6324
6325
  // Forward -f (flag) options which we can pass directly.
6326
0
  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6327
0
  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6328
0
  Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6329
0
  Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6330
6331
0
  if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6332
0
                   Triple.hasDefaultEmulatedTLS()))
6333
0
    CmdArgs.push_back("-femulated-tls");
6334
6335
0
  Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6336
0
                    options::OPT_fno_check_new);
6337
6338
0
  if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6339
    // FIXME: There's no reason for this to be restricted to X86. The backend
6340
    // code needs to be changed to include the appropriate function calls
6341
    // automatically.
6342
0
    if (!Triple.isX86() && !Triple.isAArch64())
6343
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
6344
0
          << A->getAsString(Args) << TripleStr;
6345
0
  }
6346
6347
  // AltiVec-like language extensions aren't relevant for assembling.
6348
0
  if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6349
0
    Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6350
6351
0
  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6352
0
  Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6353
6354
  // Forward flags for OpenMP. We don't do this if the current action is an
6355
  // device offloading action other than OpenMP.
6356
0
  if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6357
0
                   options::OPT_fno_openmp, false) &&
6358
0
      (JA.isDeviceOffloading(Action::OFK_None) ||
6359
0
       JA.isDeviceOffloading(Action::OFK_OpenMP))) {
6360
0
    switch (D.getOpenMPRuntime(Args)) {
6361
0
    case Driver::OMPRT_OMP:
6362
0
    case Driver::OMPRT_IOMP5:
6363
      // Clang can generate useful OpenMP code for these two runtime libraries.
6364
0
      CmdArgs.push_back("-fopenmp");
6365
6366
      // If no option regarding the use of TLS in OpenMP codegeneration is
6367
      // given, decide a default based on the target. Otherwise rely on the
6368
      // options and pass the right information to the frontend.
6369
0
      if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6370
0
                        options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6371
0
        CmdArgs.push_back("-fnoopenmp-use-tls");
6372
0
      Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6373
0
                      options::OPT_fno_openmp_simd);
6374
0
      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6375
0
      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6376
0
      if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6377
0
                        options::OPT_fno_openmp_extensions, /*Default=*/true))
6378
0
        CmdArgs.push_back("-fno-openmp-extensions");
6379
0
      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6380
0
      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6381
0
      Args.AddAllArgs(CmdArgs,
6382
0
                      options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6383
0
      if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6384
0
                       options::OPT_fno_openmp_optimistic_collapse,
6385
0
                       /*Default=*/false))
6386
0
        CmdArgs.push_back("-fopenmp-optimistic-collapse");
6387
6388
      // When in OpenMP offloading mode with NVPTX target, forward
6389
      // cuda-mode flag
6390
0
      if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6391
0
                       options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6392
0
        CmdArgs.push_back("-fopenmp-cuda-mode");
6393
6394
      // When in OpenMP offloading mode, enable debugging on the device.
6395
0
      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6396
0
      if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6397
0
                       options::OPT_fno_openmp_target_debug, /*Default=*/false))
6398
0
        CmdArgs.push_back("-fopenmp-target-debug");
6399
6400
      // When in OpenMP offloading mode, forward assumptions information about
6401
      // thread and team counts in the device.
6402
0
      if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6403
0
                       options::OPT_fno_openmp_assume_teams_oversubscription,
6404
0
                       /*Default=*/false))
6405
0
        CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6406
0
      if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6407
0
                       options::OPT_fno_openmp_assume_threads_oversubscription,
6408
0
                       /*Default=*/false))
6409
0
        CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6410
0
      if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6411
0
        CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6412
0
      if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6413
0
        CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6414
0
      if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6415
0
        CmdArgs.push_back("-fopenmp-offload-mandatory");
6416
0
      break;
6417
0
    default:
6418
      // By default, if Clang doesn't know how to generate useful OpenMP code
6419
      // for a specific runtime library, we just don't pass the '-fopenmp' flag
6420
      // down to the actual compilation.
6421
      // FIXME: It would be better to have a mode which *only* omits IR
6422
      // generation based on the OpenMP support so that we get consistent
6423
      // semantic analysis, etc.
6424
0
      break;
6425
0
    }
6426
0
  } else {
6427
0
    Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6428
0
                    options::OPT_fno_openmp_simd);
6429
0
    Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6430
0
    Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6431
0
                       options::OPT_fno_openmp_extensions);
6432
0
  }
6433
6434
  // Forward the new driver to change offloading code generation.
6435
0
  if (Args.hasFlag(options::OPT_offload_new_driver,
6436
0
                   options::OPT_no_offload_new_driver, false))
6437
0
    CmdArgs.push_back("--offload-new-driver");
6438
6439
0
  SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
6440
6441
0
  const XRayArgs &XRay = TC.getXRayArgs();
6442
0
  XRay.addArgs(TC, Args, CmdArgs, InputType);
6443
6444
0
  for (const auto &Filename :
6445
0
       Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6446
0
    if (D.getVFS().exists(Filename))
6447
0
      CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6448
0
    else
6449
0
      D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6450
0
  }
6451
6452
0
  if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6453
0
    StringRef S0 = A->getValue(), S = S0;
6454
0
    unsigned Size, Offset = 0;
6455
0
    if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6456
0
        !Triple.isX86())
6457
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
6458
0
          << A->getAsString(Args) << TripleStr;
6459
0
    else if (S.consumeInteger(10, Size) ||
6460
0
             (!S.empty() && (!S.consume_front(",") ||
6461
0
                             S.consumeInteger(10, Offset) || !S.empty())))
6462
0
      D.Diag(diag::err_drv_invalid_argument_to_option)
6463
0
          << S0 << A->getOption().getName();
6464
0
    else if (Size < Offset)
6465
0
      D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6466
0
    else {
6467
0
      CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6468
0
      CmdArgs.push_back(Args.MakeArgString(
6469
0
          "-fpatchable-function-entry-offset=" + Twine(Offset)));
6470
0
    }
6471
0
  }
6472
6473
0
  Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6474
6475
0
  if (TC.SupportsProfiling()) {
6476
0
    Args.AddLastArg(CmdArgs, options::OPT_pg);
6477
6478
0
    llvm::Triple::ArchType Arch = TC.getArch();
6479
0
    if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6480
0
      if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6481
0
        A->render(Args, CmdArgs);
6482
0
      else
6483
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
6484
0
            << A->getAsString(Args) << TripleStr;
6485
0
    }
6486
0
    if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6487
0
      if (Arch == llvm::Triple::systemz)
6488
0
        A->render(Args, CmdArgs);
6489
0
      else
6490
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
6491
0
            << A->getAsString(Args) << TripleStr;
6492
0
    }
6493
0
    if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6494
0
      if (Arch == llvm::Triple::systemz)
6495
0
        A->render(Args, CmdArgs);
6496
0
      else
6497
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
6498
0
            << A->getAsString(Args) << TripleStr;
6499
0
    }
6500
0
  }
6501
6502
0
  if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
6503
0
    if (TC.getTriple().isOSzOS()) {
6504
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
6505
0
          << A->getAsString(Args) << TripleStr;
6506
0
    }
6507
0
  }
6508
0
  if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
6509
0
    if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6510
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
6511
0
          << A->getAsString(Args) << TripleStr;
6512
0
    }
6513
0
  }
6514
0
  if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
6515
0
    if (A->getOption().matches(options::OPT_p)) {
6516
0
      A->claim();
6517
0
      if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
6518
0
        CmdArgs.push_back("-pg");
6519
0
    }
6520
0
  }
6521
6522
  // Reject AIX-specific link options on other targets.
6523
0
  if (!TC.getTriple().isOSAIX()) {
6524
0
    for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
6525
0
                                      options::OPT_mxcoff_build_id_EQ)) {
6526
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
6527
0
          << A->getSpelling() << TripleStr;
6528
0
    }
6529
0
  }
6530
6531
0
  if (Args.getLastArg(options::OPT_fapple_kext) ||
6532
0
      (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6533
0
    CmdArgs.push_back("-fapple-kext");
6534
6535
0
  Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6536
0
  Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6537
0
  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6538
0
  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6539
0
  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6540
0
  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6541
0
  Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6542
0
  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6543
0
  Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6544
0
  Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6545
6546
0
  if (const char *Name = C.getTimeTraceFile(&JA)) {
6547
0
    CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
6548
0
    Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
6549
0
  }
6550
6551
0
  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6552
0
    CmdArgs.push_back("-ftrapv-handler");
6553
0
    CmdArgs.push_back(A->getValue());
6554
0
  }
6555
6556
0
  Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6557
6558
  // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
6559
  // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
6560
0
  if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
6561
0
    if (A->getOption().matches(options::OPT_fwrapv))
6562
0
      CmdArgs.push_back("-fwrapv");
6563
0
  } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
6564
0
                                      options::OPT_fno_strict_overflow)) {
6565
0
    if (A->getOption().matches(options::OPT_fno_strict_overflow))
6566
0
      CmdArgs.push_back("-fwrapv");
6567
0
  }
6568
6569
0
  if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
6570
0
                               options::OPT_fno_reroll_loops))
6571
0
    if (A->getOption().matches(options::OPT_freroll_loops))
6572
0
      CmdArgs.push_back("-freroll-loops");
6573
6574
0
  Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6575
0
                  options::OPT_fno_finite_loops);
6576
6577
0
  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6578
0
  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6579
0
                  options::OPT_fno_unroll_loops);
6580
6581
0
  Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6582
6583
0
  Args.AddLastArg(CmdArgs, options::OPT_pthread);
6584
6585
0
  Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6586
0
                    options::OPT_mno_speculative_load_hardening);
6587
6588
0
  RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6589
0
  RenderSCPOptions(TC, Args, CmdArgs);
6590
0
  RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6591
6592
0
  Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6593
6594
0
  Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6595
0
                    options::OPT_mno_stackrealign);
6596
6597
0
  if (Args.hasArg(options::OPT_mstack_alignment)) {
6598
0
    StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
6599
0
    CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
6600
0
  }
6601
6602
0
  if (Args.hasArg(options::OPT_mstack_probe_size)) {
6603
0
    StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6604
6605
0
    if (!Size.empty())
6606
0
      CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
6607
0
    else
6608
0
      CmdArgs.push_back("-mstack-probe-size=0");
6609
0
  }
6610
6611
0
  Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
6612
0
                     options::OPT_mno_stack_arg_probe);
6613
6614
0
  if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6615
0
                               options::OPT_mno_restrict_it)) {
6616
0
    if (A->getOption().matches(options::OPT_mrestrict_it)) {
6617
0
      CmdArgs.push_back("-mllvm");
6618
0
      CmdArgs.push_back("-arm-restrict-it");
6619
0
    } else {
6620
0
      CmdArgs.push_back("-mllvm");
6621
0
      CmdArgs.push_back("-arm-default-it");
6622
0
    }
6623
0
  }
6624
6625
  // Forward -cl options to -cc1
6626
0
  RenderOpenCLOptions(Args, CmdArgs, InputType);
6627
6628
  // Forward hlsl options to -cc1
6629
0
  RenderHLSLOptions(Args, CmdArgs, InputType);
6630
6631
  // Forward OpenACC options to -cc1
6632
0
  RenderOpenACCOptions(D, Args, CmdArgs, InputType);
6633
6634
0
  if (IsHIP) {
6635
0
    if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6636
0
                     options::OPT_fno_hip_new_launch_api, true))
6637
0
      CmdArgs.push_back("-fhip-new-launch-api");
6638
0
    Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
6639
0
                      options::OPT_fno_gpu_allow_device_init);
6640
0
    Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
6641
0
    Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
6642
0
    Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
6643
0
                      options::OPT_fno_hip_kernel_arg_name);
6644
0
  }
6645
6646
0
  if (IsCuda || IsHIP) {
6647
0
    if (IsRDCMode)
6648
0
      CmdArgs.push_back("-fgpu-rdc");
6649
0
    Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
6650
0
                      options::OPT_fno_gpu_defer_diag);
6651
0
    if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6652
0
                     options::OPT_fno_gpu_exclude_wrong_side_overloads,
6653
0
                     false)) {
6654
0
      CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6655
0
      CmdArgs.push_back("-fgpu-defer-diag");
6656
0
    }
6657
0
  }
6658
6659
  // Forward -nogpulib to -cc1.
6660
0
  if (Args.hasArg(options::OPT_nogpulib))
6661
0
    CmdArgs.push_back("-nogpulib");
6662
6663
0
  if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6664
0
    CmdArgs.push_back(
6665
0
        Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
6666
0
  }
6667
6668
0
  if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6669
0
    CmdArgs.push_back(
6670
0
        Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6671
6672
0
  Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6673
6674
  // Forward -f options with positive and negative forms; we translate these by
6675
  // hand.  Do not propagate PGO options to the GPU-side compilations as the
6676
  // profile info is for the host-side compilation only.
6677
0
  if (!(IsCudaDevice || IsHIPDevice)) {
6678
0
    if (Arg *A = getLastProfileSampleUseArg(Args)) {
6679
0
      auto *PGOArg = Args.getLastArg(
6680
0
          options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6681
0
          options::OPT_fcs_profile_generate,
6682
0
          options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6683
0
          options::OPT_fprofile_use_EQ);
6684
0
      if (PGOArg)
6685
0
        D.Diag(diag::err_drv_argument_not_allowed_with)
6686
0
            << "SampleUse with PGO options";
6687
6688
0
      StringRef fname = A->getValue();
6689
0
      if (!llvm::sys::fs::exists(fname))
6690
0
        D.Diag(diag::err_drv_no_such_file) << fname;
6691
0
      else
6692
0
        A->render(Args, CmdArgs);
6693
0
    }
6694
0
    Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
6695
6696
0
    if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6697
0
                     options::OPT_fno_pseudo_probe_for_profiling, false)) {
6698
0
      CmdArgs.push_back("-fpseudo-probe-for-profiling");
6699
      // Enforce -funique-internal-linkage-names if it's not explicitly turned
6700
      // off.
6701
0
      if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6702
0
                       options::OPT_fno_unique_internal_linkage_names, true))
6703
0
        CmdArgs.push_back("-funique-internal-linkage-names");
6704
0
    }
6705
0
  }
6706
0
  RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
6707
6708
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6709
0
                     options::OPT_fno_assume_sane_operator_new);
6710
6711
0
  if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
6712
0
    CmdArgs.push_back("-fapinotes");
6713
0
  if (Args.hasFlag(options::OPT_fapinotes_modules,
6714
0
                   options::OPT_fno_apinotes_modules, false))
6715
0
    CmdArgs.push_back("-fapinotes-modules");
6716
0
  Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
6717
6718
  // -fblocks=0 is default.
6719
0
  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
6720
0
                   TC.IsBlocksDefault()) ||
6721
0
      (Args.hasArg(options::OPT_fgnu_runtime) &&
6722
0
       Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
6723
0
       !Args.hasArg(options::OPT_fno_blocks))) {
6724
0
    CmdArgs.push_back("-fblocks");
6725
6726
0
    if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
6727
0
      CmdArgs.push_back("-fblocks-runtime-optional");
6728
0
  }
6729
6730
  // -fencode-extended-block-signature=1 is default.
6731
0
  if (TC.IsEncodeExtendedBlockSignatureDefault())
6732
0
    CmdArgs.push_back("-fencode-extended-block-signature");
6733
6734
0
  if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
6735
0
                   options::OPT_fno_coro_aligned_allocation, false) &&
6736
0
      types::isCXX(InputType))
6737
0
    CmdArgs.push_back("-fcoro-aligned-allocation");
6738
6739
0
  Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
6740
0
                  options::OPT_fno_double_square_bracket_attributes);
6741
6742
0
  Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
6743
0
                     options::OPT_fno_access_control);
6744
0
  Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
6745
0
                     options::OPT_fno_elide_constructors);
6746
6747
0
  ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
6748
6749
0
  if (KernelOrKext || (types::isCXX(InputType) &&
6750
0
                       (RTTIMode == ToolChain::RM_Disabled)))
6751
0
    CmdArgs.push_back("-fno-rtti");
6752
6753
  // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
6754
0
  if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6755
0
                   TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
6756
0
    CmdArgs.push_back("-fshort-enums");
6757
6758
0
  RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6759
6760
  // -fuse-cxa-atexit is default.
6761
0
  if (!Args.hasFlag(
6762
0
          options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6763
0
          !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6764
0
              ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6765
0
               RawTriple.hasEnvironment())) ||
6766
0
      KernelOrKext)
6767
0
    CmdArgs.push_back("-fno-use-cxa-atexit");
6768
6769
0
  if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6770
0
                   options::OPT_fno_register_global_dtors_with_atexit,
6771
0
                   RawTriple.isOSDarwin() && !KernelOrKext))
6772
0
    CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6773
6774
0
  Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
6775
0
                    options::OPT_fno_use_line_directives);
6776
6777
  // -fno-minimize-whitespace is default.
6778
0
  if (Args.hasFlag(options::OPT_fminimize_whitespace,
6779
0
                   options::OPT_fno_minimize_whitespace, false)) {
6780
0
    types::ID InputType = Inputs[0].getType();
6781
0
    if (!isDerivedFromC(InputType))
6782
0
      D.Diag(diag::err_drv_opt_unsupported_input_type)
6783
0
          << "-fminimize-whitespace" << types::getTypeName(InputType);
6784
0
    CmdArgs.push_back("-fminimize-whitespace");
6785
0
  }
6786
6787
  // -fno-keep-system-includes is default.
6788
0
  if (Args.hasFlag(options::OPT_fkeep_system_includes,
6789
0
                   options::OPT_fno_keep_system_includes, false)) {
6790
0
    types::ID InputType = Inputs[0].getType();
6791
0
    if (!isDerivedFromC(InputType))
6792
0
      D.Diag(diag::err_drv_opt_unsupported_input_type)
6793
0
          << "-fkeep-system-includes" << types::getTypeName(InputType);
6794
0
    CmdArgs.push_back("-fkeep-system-includes");
6795
0
  }
6796
6797
  // -fms-extensions=0 is default.
6798
0
  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6799
0
                   IsWindowsMSVC))
6800
0
    CmdArgs.push_back("-fms-extensions");
6801
6802
  // -fms-compatibility=0 is default.
6803
0
  bool IsMSVCCompat = Args.hasFlag(
6804
0
      options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6805
0
      (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6806
0
                                     options::OPT_fno_ms_extensions, true)));
6807
0
  if (IsMSVCCompat)
6808
0
    CmdArgs.push_back("-fms-compatibility");
6809
6810
0
  if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
6811
0
      Args.hasArg(options::OPT_fms_runtime_lib_EQ))
6812
0
    ProcessVSRuntimeLibrary(Args, CmdArgs);
6813
6814
  // Handle -fgcc-version, if present.
6815
0
  VersionTuple GNUCVer;
6816
0
  if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6817
    // Check that the version has 1 to 3 components and the minor and patch
6818
    // versions fit in two decimal digits.
6819
0
    StringRef Val = A->getValue();
6820
0
    Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6821
0
    bool Invalid = GNUCVer.tryParse(Val);
6822
0
    unsigned Minor = GNUCVer.getMinor().value_or(0);
6823
0
    unsigned Patch = GNUCVer.getSubminor().value_or(0);
6824
0
    if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6825
0
      D.Diag(diag::err_drv_invalid_value)
6826
0
          << A->getAsString(Args) << A->getValue();
6827
0
    }
6828
0
  } else if (!IsMSVCCompat) {
6829
    // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6830
0
    GNUCVer = VersionTuple(4, 2, 1);
6831
0
  }
6832
0
  if (!GNUCVer.empty()) {
6833
0
    CmdArgs.push_back(
6834
0
        Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6835
0
  }
6836
6837
0
  VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6838
0
  if (!MSVT.empty())
6839
0
    CmdArgs.push_back(
6840
0
        Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6841
6842
0
  bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6843
0
  if (ImplyVCPPCVer) {
6844
0
    StringRef LanguageStandard;
6845
0
    if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6846
0
      Std = StdArg;
6847
0
      LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6848
0
                             .Case("c11", "-std=c11")
6849
0
                             .Case("c17", "-std=c17")
6850
0
                             .Default("");
6851
0
      if (LanguageStandard.empty())
6852
0
        D.Diag(clang::diag::warn_drv_unused_argument)
6853
0
            << StdArg->getAsString(Args);
6854
0
    }
6855
0
    CmdArgs.push_back(LanguageStandard.data());
6856
0
  }
6857
0
  if (ImplyVCPPCXXVer) {
6858
0
    StringRef LanguageStandard;
6859
0
    if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6860
0
      Std = StdArg;
6861
0
      LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6862
0
                             .Case("c++14", "-std=c++14")
6863
0
                             .Case("c++17", "-std=c++17")
6864
0
                             .Case("c++20", "-std=c++20")
6865
                             // TODO add c++23 and c++26 when MSVC supports it.
6866
0
                             .Case("c++latest", "-std=c++26")
6867
0
                             .Default("");
6868
0
      if (LanguageStandard.empty())
6869
0
        D.Diag(clang::diag::warn_drv_unused_argument)
6870
0
            << StdArg->getAsString(Args);
6871
0
    }
6872
6873
0
    if (LanguageStandard.empty()) {
6874
0
      if (IsMSVC2015Compatible)
6875
0
        LanguageStandard = "-std=c++14";
6876
0
      else
6877
0
        LanguageStandard = "-std=c++11";
6878
0
    }
6879
6880
0
    CmdArgs.push_back(LanguageStandard.data());
6881
0
  }
6882
6883
0
  Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
6884
0
                    options::OPT_fno_borland_extensions);
6885
6886
  // -fno-declspec is default, except for PS4/PS5.
6887
0
  if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
6888
0
                   RawTriple.isPS()))
6889
0
    CmdArgs.push_back("-fdeclspec");
6890
0
  else if (Args.hasArg(options::OPT_fno_declspec))
6891
0
    CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6892
6893
  // -fthreadsafe-static is default, except for MSVC compatibility versions less
6894
  // than 19.
6895
0
  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6896
0
                    options::OPT_fno_threadsafe_statics,
6897
0
                    !types::isOpenCL(InputType) &&
6898
0
                        (!IsWindowsMSVC || IsMSVC2015Compatible)))
6899
0
    CmdArgs.push_back("-fno-threadsafe-statics");
6900
6901
  // -fgnu-keywords default varies depending on language; only pass if
6902
  // specified.
6903
0
  Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6904
0
                  options::OPT_fno_gnu_keywords);
6905
6906
0
  Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
6907
0
                    options::OPT_fno_gnu89_inline);
6908
6909
0
  const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
6910
0
                                         options::OPT_finline_hint_functions,
6911
0
                                         options::OPT_fno_inline_functions);
6912
0
  if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
6913
0
    if (A->getOption().matches(options::OPT_fno_inline))
6914
0
      A->render(Args, CmdArgs);
6915
0
  } else if (InlineArg) {
6916
0
    InlineArg->render(Args, CmdArgs);
6917
0
  }
6918
6919
0
  Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
6920
6921
  // FIXME: Find a better way to determine whether we are in C++20.
6922
0
  bool HaveCxx20 =
6923
0
      Std &&
6924
0
      (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
6925
0
       Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
6926
0
       Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
6927
0
       Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
6928
0
       Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
6929
0
       Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
6930
0
       Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
6931
0
  bool HaveModules =
6932
0
      RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
6933
6934
  // -fdelayed-template-parsing is default when targeting MSVC.
6935
  // Many old Windows SDK versions require this to parse.
6936
  //
6937
  // According to
6938
  // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
6939
  // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
6940
  // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
6941
  // not enable -fdelayed-template-parsing by default after C++20.
6942
  //
6943
  // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
6944
  // able to disable this by default at some point.
6945
0
  if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6946
0
                   options::OPT_fno_delayed_template_parsing,
6947
0
                   IsWindowsMSVC && !HaveCxx20)) {
6948
0
    if (HaveCxx20)
6949
0
      D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
6950
6951
0
    CmdArgs.push_back("-fdelayed-template-parsing");
6952
0
  }
6953
6954
0
  if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6955
0
                   options::OPT_fno_pch_validate_input_files_content, false))
6956
0
    CmdArgs.push_back("-fvalidate-ast-input-files-content");
6957
0
  if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6958
0
                   options::OPT_fno_pch_instantiate_templates, false))
6959
0
    CmdArgs.push_back("-fpch-instantiate-templates");
6960
0
  if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6961
0
                   false))
6962
0
    CmdArgs.push_back("-fmodules-codegen");
6963
0
  if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6964
0
                   false))
6965
0
    CmdArgs.push_back("-fmodules-debuginfo");
6966
6967
0
  ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6968
0
  RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6969
0
                    Input, CmdArgs);
6970
6971
0
  if (types::isObjC(Input.getType()) &&
6972
0
      Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6973
0
                   options::OPT_fno_objc_encode_cxx_class_template_spec,
6974
0
                   !Runtime.isNeXTFamily()))
6975
0
    CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6976
6977
0
  if (Args.hasFlag(options::OPT_fapplication_extension,
6978
0
                   options::OPT_fno_application_extension, false))
6979
0
    CmdArgs.push_back("-fapplication-extension");
6980
6981
  // Handle GCC-style exception args.
6982
0
  bool EH = false;
6983
0
  if (!C.getDriver().IsCLMode())
6984
0
    EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6985
6986
  // Handle exception personalities
6987
0
  Arg *A = Args.getLastArg(
6988
0
      options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6989
0
      options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6990
0
  if (A) {
6991
0
    const Option &Opt = A->getOption();
6992
0
    if (Opt.matches(options::OPT_fsjlj_exceptions))
6993
0
      CmdArgs.push_back("-exception-model=sjlj");
6994
0
    if (Opt.matches(options::OPT_fseh_exceptions))
6995
0
      CmdArgs.push_back("-exception-model=seh");
6996
0
    if (Opt.matches(options::OPT_fdwarf_exceptions))
6997
0
      CmdArgs.push_back("-exception-model=dwarf");
6998
0
    if (Opt.matches(options::OPT_fwasm_exceptions))
6999
0
      CmdArgs.push_back("-exception-model=wasm");
7000
0
  } else {
7001
0
    switch (TC.GetExceptionModel(Args)) {
7002
0
    default:
7003
0
      break;
7004
0
    case llvm::ExceptionHandling::DwarfCFI:
7005
0
      CmdArgs.push_back("-exception-model=dwarf");
7006
0
      break;
7007
0
    case llvm::ExceptionHandling::SjLj:
7008
0
      CmdArgs.push_back("-exception-model=sjlj");
7009
0
      break;
7010
0
    case llvm::ExceptionHandling::WinEH:
7011
0
      CmdArgs.push_back("-exception-model=seh");
7012
0
      break;
7013
0
    }
7014
0
  }
7015
7016
  // C++ "sane" operator new.
7017
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7018
0
                     options::OPT_fno_assume_sane_operator_new);
7019
7020
  // -fassume-unique-vtables is on by default.
7021
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7022
0
                     options::OPT_fno_assume_unique_vtables);
7023
7024
  // -frelaxed-template-template-args is off by default, as it is a severe
7025
  // breaking change until a corresponding change to template partial ordering
7026
  // is provided.
7027
0
  Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
7028
0
                    options::OPT_fno_relaxed_template_template_args);
7029
7030
  // -fsized-deallocation is off by default, as it is an ABI-breaking change for
7031
  // most platforms.
7032
0
  Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
7033
0
                    options::OPT_fno_sized_deallocation);
7034
7035
  // -faligned-allocation is on by default in C++17 onwards and otherwise off
7036
  // by default.
7037
0
  if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7038
0
                               options::OPT_fno_aligned_allocation,
7039
0
                               options::OPT_faligned_new_EQ)) {
7040
0
    if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7041
0
      CmdArgs.push_back("-fno-aligned-allocation");
7042
0
    else
7043
0
      CmdArgs.push_back("-faligned-allocation");
7044
0
  }
7045
7046
  // The default new alignment can be specified using a dedicated option or via
7047
  // a GCC-compatible option that also turns on aligned allocation.
7048
0
  if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7049
0
                               options::OPT_faligned_new_EQ))
7050
0
    CmdArgs.push_back(
7051
0
        Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7052
7053
  // -fconstant-cfstrings is default, and may be subject to argument translation
7054
  // on Darwin.
7055
0
  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7056
0
                    options::OPT_fno_constant_cfstrings, true) ||
7057
0
      !Args.hasFlag(options::OPT_mconstant_cfstrings,
7058
0
                    options::OPT_mno_constant_cfstrings, true))
7059
0
    CmdArgs.push_back("-fno-constant-cfstrings");
7060
7061
0
  Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7062
0
                    options::OPT_fno_pascal_strings);
7063
7064
  // Honor -fpack-struct= and -fpack-struct, if given. Note that
7065
  // -fno-pack-struct doesn't apply to -fpack-struct=.
7066
0
  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7067
0
    std::string PackStructStr = "-fpack-struct=";
7068
0
    PackStructStr += A->getValue();
7069
0
    CmdArgs.push_back(Args.MakeArgString(PackStructStr));
7070
0
  } else if (Args.hasFlag(options::OPT_fpack_struct,
7071
0
                          options::OPT_fno_pack_struct, false)) {
7072
0
    CmdArgs.push_back("-fpack-struct=1");
7073
0
  }
7074
7075
  // Handle -fmax-type-align=N and -fno-type-align
7076
0
  bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7077
0
  if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7078
0
    if (!SkipMaxTypeAlign) {
7079
0
      std::string MaxTypeAlignStr = "-fmax-type-align=";
7080
0
      MaxTypeAlignStr += A->getValue();
7081
0
      CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7082
0
    }
7083
0
  } else if (RawTriple.isOSDarwin()) {
7084
0
    if (!SkipMaxTypeAlign) {
7085
0
      std::string MaxTypeAlignStr = "-fmax-type-align=16";
7086
0
      CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7087
0
    }
7088
0
  }
7089
7090
0
  if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7091
0
    CmdArgs.push_back("-Qn");
7092
7093
  // -fno-common is the default, set -fcommon only when that flag is set.
7094
0
  Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7095
7096
  // -fsigned-bitfields is default, and clang doesn't yet support
7097
  // -funsigned-bitfields.
7098
0
  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7099
0
                    options::OPT_funsigned_bitfields, true))
7100
0
    D.Diag(diag::warn_drv_clang_unsupported)
7101
0
        << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7102
7103
  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7104
0
  if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7105
0
    D.Diag(diag::err_drv_clang_unsupported)
7106
0
        << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7107
7108
  // -finput_charset=UTF-8 is default. Reject others
7109
0
  if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7110
0
    StringRef value = inputCharset->getValue();
7111
0
    if (!value.equals_insensitive("utf-8"))
7112
0
      D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7113
0
                                          << value;
7114
0
  }
7115
7116
  // -fexec_charset=UTF-8 is default. Reject others
7117
0
  if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
7118
0
    StringRef value = execCharset->getValue();
7119
0
    if (!value.equals_insensitive("utf-8"))
7120
0
      D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7121
0
                                          << value;
7122
0
  }
7123
7124
0
  RenderDiagnosticsOptions(D, Args, CmdArgs);
7125
7126
0
  Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
7127
0
                    options::OPT_fno_asm_blocks);
7128
7129
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7130
0
                     options::OPT_fno_gnu_inline_asm);
7131
7132
  // Enable vectorization per default according to the optimization level
7133
  // selected. For optimization levels that want vectorization we use the alias
7134
  // option to simplify the hasFlag logic.
7135
0
  bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
7136
0
  OptSpecifier VectorizeAliasOption =
7137
0
      EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
7138
0
  if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
7139
0
                   options::OPT_fno_vectorize, EnableVec))
7140
0
    CmdArgs.push_back("-vectorize-loops");
7141
7142
  // -fslp-vectorize is enabled based on the optimization level selected.
7143
0
  bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
7144
0
  OptSpecifier SLPVectAliasOption =
7145
0
      EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
7146
0
  if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
7147
0
                   options::OPT_fno_slp_vectorize, EnableSLPVec))
7148
0
    CmdArgs.push_back("-vectorize-slp");
7149
7150
0
  ParseMPreferVectorWidth(D, Args, CmdArgs);
7151
7152
0
  Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7153
0
  Args.AddLastArg(CmdArgs,
7154
0
                  options::OPT_fsanitize_undefined_strip_path_components_EQ);
7155
7156
  // -fdollars-in-identifiers default varies depending on platform and
7157
  // language; only pass if specified.
7158
0
  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7159
0
                               options::OPT_fno_dollars_in_identifiers)) {
7160
0
    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7161
0
      CmdArgs.push_back("-fdollars-in-identifiers");
7162
0
    else
7163
0
      CmdArgs.push_back("-fno-dollars-in-identifiers");
7164
0
  }
7165
7166
0
  Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7167
0
                    options::OPT_fno_apple_pragma_pack);
7168
7169
  // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7170
0
  if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7171
0
    renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7172
7173
0
  bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7174
0
                                     options::OPT_fno_rewrite_imports, false);
7175
0
  if (RewriteImports)
7176
0
    CmdArgs.push_back("-frewrite-imports");
7177
7178
0
  Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7179
0
                    options::OPT_fno_directives_only);
7180
7181
  // Enable rewrite includes if the user's asked for it or if we're generating
7182
  // diagnostics.
7183
  // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7184
  // nice to enable this when doing a crashdump for modules as well.
7185
0
  if (Args.hasFlag(options::OPT_frewrite_includes,
7186
0
                   options::OPT_fno_rewrite_includes, false) ||
7187
0
      (C.isForDiagnostics() && !HaveModules))
7188
0
    CmdArgs.push_back("-frewrite-includes");
7189
7190
  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7191
0
  if (Arg *A = Args.getLastArg(options::OPT_traditional,
7192
0
                               options::OPT_traditional_cpp)) {
7193
0
    if (isa<PreprocessJobAction>(JA))
7194
0
      CmdArgs.push_back("-traditional-cpp");
7195
0
    else
7196
0
      D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7197
0
  }
7198
7199
0
  Args.AddLastArg(CmdArgs, options::OPT_dM);
7200
0
  Args.AddLastArg(CmdArgs, options::OPT_dD);
7201
0
  Args.AddLastArg(CmdArgs, options::OPT_dI);
7202
7203
0
  Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7204
7205
  // Handle serialized diagnostics.
7206
0
  if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7207
0
    CmdArgs.push_back("-serialize-diagnostic-file");
7208
0
    CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7209
0
  }
7210
7211
0
  if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7212
0
    CmdArgs.push_back("-fretain-comments-from-system-headers");
7213
7214
  // Forward -fcomment-block-commands to -cc1.
7215
0
  Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7216
  // Forward -fparse-all-comments to -cc1.
7217
0
  Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7218
7219
  // Turn -fplugin=name.so into -load name.so
7220
0
  for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7221
0
    CmdArgs.push_back("-load");
7222
0
    CmdArgs.push_back(A->getValue());
7223
0
    A->claim();
7224
0
  }
7225
7226
  // Turn -fplugin-arg-pluginname-key=value into
7227
  // -plugin-arg-pluginname key=value
7228
  // GCC has an actual plugin_argument struct with key/value pairs that it
7229
  // passes to its plugins, but we don't, so just pass it on as-is.
7230
  //
7231
  // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7232
  // argument key are allowed to contain dashes. GCC therefore only
7233
  // allows dashes in the key. We do the same.
7234
0
  for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7235
0
    auto ArgValue = StringRef(A->getValue());
7236
0
    auto FirstDashIndex = ArgValue.find('-');
7237
0
    StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7238
0
    StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7239
7240
0
    A->claim();
7241
0
    if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7242
0
      if (PluginName.empty()) {
7243
0
        D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7244
0
      } else {
7245
0
        D.Diag(diag::warn_drv_missing_plugin_arg)
7246
0
            << PluginName << A->getAsString(Args);
7247
0
      }
7248
0
      continue;
7249
0
    }
7250
7251
0
    CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7252
0
    CmdArgs.push_back(Args.MakeArgString(Arg));
7253
0
  }
7254
7255
  // Forward -fpass-plugin=name.so to -cc1.
7256
0
  for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7257
0
    CmdArgs.push_back(
7258
0
        Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7259
0
    A->claim();
7260
0
  }
7261
7262
  // Forward --vfsoverlay to -cc1.
7263
0
  for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7264
0
    CmdArgs.push_back("--vfsoverlay");
7265
0
    CmdArgs.push_back(A->getValue());
7266
0
    A->claim();
7267
0
  }
7268
7269
0
  Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7270
0
                    options::OPT_fno_safe_buffer_usage_suggestions);
7271
7272
  // Setup statistics file output.
7273
0
  SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7274
0
  if (!StatsFile.empty()) {
7275
0
    CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
7276
0
    if (D.CCPrintInternalStats)
7277
0
      CmdArgs.push_back("-stats-file-append");
7278
0
  }
7279
7280
  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7281
  // parser.
7282
0
  for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7283
0
    Arg->claim();
7284
    // -finclude-default-header flag is for preprocessor,
7285
    // do not pass it to other cc1 commands when save-temps is enabled
7286
0
    if (C.getDriver().isSaveTempsEnabled() &&
7287
0
        !isa<PreprocessJobAction>(JA)) {
7288
0
      if (StringRef(Arg->getValue()) == "-finclude-default-header")
7289
0
        continue;
7290
0
    }
7291
0
    CmdArgs.push_back(Arg->getValue());
7292
0
  }
7293
0
  for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7294
0
    A->claim();
7295
7296
    // We translate this by hand to the -cc1 argument, since nightly test uses
7297
    // it and developers have been trained to spell it with -mllvm. Both
7298
    // spellings are now deprecated and should be removed.
7299
0
    if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7300
0
      CmdArgs.push_back("-disable-llvm-optzns");
7301
0
    } else {
7302
0
      A->render(Args, CmdArgs);
7303
0
    }
7304
0
  }
7305
7306
  // With -save-temps, we want to save the unoptimized bitcode output from the
7307
  // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7308
  // by the frontend.
7309
  // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7310
  // has slightly different breakdown between stages.
7311
  // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7312
  // pristine IR generated by the frontend. Ideally, a new compile action should
7313
  // be added so both IR can be captured.
7314
0
  if ((C.getDriver().isSaveTempsEnabled() ||
7315
0
       JA.isHostOffloading(Action::OFK_OpenMP)) &&
7316
0
      !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7317
0
      isa<CompileJobAction>(JA))
7318
0
    CmdArgs.push_back("-disable-llvm-passes");
7319
7320
0
  Args.AddAllArgs(CmdArgs, options::OPT_undef);
7321
7322
0
  const char *Exec = D.getClangProgramPath();
7323
7324
  // Optionally embed the -cc1 level arguments into the debug info or a
7325
  // section, for build analysis.
7326
  // Also record command line arguments into the debug info if
7327
  // -grecord-gcc-switches options is set on.
7328
  // By default, -gno-record-gcc-switches is set on and no recording.
7329
0
  auto GRecordSwitches =
7330
0
      Args.hasFlag(options::OPT_grecord_command_line,
7331
0
                   options::OPT_gno_record_command_line, false);
7332
0
  auto FRecordSwitches =
7333
0
      Args.hasFlag(options::OPT_frecord_command_line,
7334
0
                   options::OPT_fno_record_command_line, false);
7335
0
  if (FRecordSwitches && !Triple.isOSBinFormatELF() &&
7336
0
      !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
7337
0
    D.Diag(diag::err_drv_unsupported_opt_for_target)
7338
0
        << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
7339
0
        << TripleStr;
7340
0
  if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
7341
0
    ArgStringList OriginalArgs;
7342
0
    for (const auto &Arg : Args)
7343
0
      Arg->render(Args, OriginalArgs);
7344
7345
0
    SmallString<256> Flags;
7346
0
    EscapeSpacesAndBackslashes(Exec, Flags);
7347
0
    for (const char *OriginalArg : OriginalArgs) {
7348
0
      SmallString<128> EscapedArg;
7349
0
      EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7350
0
      Flags += " ";
7351
0
      Flags += EscapedArg;
7352
0
    }
7353
0
    auto FlagsArgString = Args.MakeArgString(Flags);
7354
0
    if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7355
0
      CmdArgs.push_back("-dwarf-debug-flags");
7356
0
      CmdArgs.push_back(FlagsArgString);
7357
0
    }
7358
0
    if (FRecordSwitches) {
7359
0
      CmdArgs.push_back("-record-command-line");
7360
0
      CmdArgs.push_back(FlagsArgString);
7361
0
    }
7362
0
  }
7363
7364
  // Host-side offloading compilation receives all device-side outputs. Include
7365
  // them in the host compilation depending on the target. If the host inputs
7366
  // are not empty we use the new-driver scheme, otherwise use the old scheme.
7367
0
  if ((IsCuda || IsHIP) && CudaDeviceInput) {
7368
0
    CmdArgs.push_back("-fcuda-include-gpubinary");
7369
0
    CmdArgs.push_back(CudaDeviceInput->getFilename());
7370
0
  } else if (!HostOffloadingInputs.empty()) {
7371
0
    if ((IsCuda || IsHIP) && !IsRDCMode) {
7372
0
      assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7373
0
      CmdArgs.push_back("-fcuda-include-gpubinary");
7374
0
      CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7375
0
    } else {
7376
0
      for (const InputInfo Input : HostOffloadingInputs)
7377
0
        CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7378
0
                                             TC.getInputFilename(Input)));
7379
0
    }
7380
0
  }
7381
7382
0
  if (IsCuda) {
7383
0
    if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7384
0
                     options::OPT_fno_cuda_short_ptr, false))
7385
0
      CmdArgs.push_back("-fcuda-short-ptr");
7386
0
  }
7387
7388
0
  if (IsCuda || IsHIP) {
7389
    // Determine the original source input.
7390
0
    const Action *SourceAction = &JA;
7391
0
    while (SourceAction->getKind() != Action::InputClass) {
7392
0
      assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7393
0
      SourceAction = SourceAction->getInputs()[0];
7394
0
    }
7395
0
    auto CUID = cast<InputAction>(SourceAction)->getId();
7396
0
    if (!CUID.empty())
7397
0
      CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
7398
7399
    // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7400
    // be overriden by -fno-gpu-approx-transcendentals.
7401
0
    bool UseApproxTranscendentals = Args.hasFlag(
7402
0
        options::OPT_ffast_math, options::OPT_fno_fast_math, false);
7403
0
    if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
7404
0
                     options::OPT_fno_gpu_approx_transcendentals,
7405
0
                     UseApproxTranscendentals))
7406
0
      CmdArgs.push_back("-fgpu-approx-transcendentals");
7407
0
  } else {
7408
0
    Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
7409
0
                      options::OPT_fno_gpu_approx_transcendentals);
7410
0
  }
7411
7412
0
  if (IsHIP) {
7413
0
    CmdArgs.push_back("-fcuda-allow-variadic-functions");
7414
0
    Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
7415
0
  }
7416
7417
0
  Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
7418
0
                  options::OPT_fno_offload_uniform_block);
7419
7420
0
  Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
7421
0
                  options::OPT_fno_offload_implicit_host_device_templates);
7422
7423
0
  if (IsCudaDevice || IsHIPDevice) {
7424
0
    StringRef InlineThresh =
7425
0
        Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7426
0
    if (!InlineThresh.empty()) {
7427
0
      std::string ArgStr =
7428
0
          std::string("-inline-threshold=") + InlineThresh.str();
7429
0
      CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7430
0
    }
7431
0
  }
7432
7433
0
  if (IsHIPDevice)
7434
0
    Args.addOptOutFlag(CmdArgs,
7435
0
                       options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7436
0
                       options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7437
7438
  // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7439
  // to specify the result of the compile phase on the host, so the meaningful
7440
  // device declarations can be identified. Also, -fopenmp-is-target-device is
7441
  // passed along to tell the frontend that it is generating code for a device,
7442
  // so that only the relevant declarations are emitted.
7443
0
  if (IsOpenMPDevice) {
7444
0
    CmdArgs.push_back("-fopenmp-is-target-device");
7445
0
    if (OpenMPDeviceInput) {
7446
0
      CmdArgs.push_back("-fopenmp-host-ir-file-path");
7447
0
      CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
7448
0
    }
7449
0
  }
7450
7451
0
  if (Triple.isAMDGPU()) {
7452
0
    handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7453
7454
0
    Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
7455
0
                      options::OPT_mno_unsafe_fp_atomics);
7456
0
    Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
7457
0
                       options::OPT_mno_amdgpu_ieee);
7458
0
  }
7459
7460
  // For all the host OpenMP offloading compile jobs we need to pass the targets
7461
  // information using -fopenmp-targets= option.
7462
0
  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
7463
0
    SmallString<128> Targets("-fopenmp-targets=");
7464
7465
0
    SmallVector<std::string, 4> Triples;
7466
0
    auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
7467
0
    std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
7468
0
                   [](auto TC) { return TC.second->getTripleString(); });
7469
0
    CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
7470
0
  }
7471
7472
0
  bool VirtualFunctionElimination =
7473
0
      Args.hasFlag(options::OPT_fvirtual_function_elimination,
7474
0
                   options::OPT_fno_virtual_function_elimination, false);
7475
0
  if (VirtualFunctionElimination) {
7476
    // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7477
    // in the future).
7478
0
    if (LTOMode != LTOK_Full)
7479
0
      D.Diag(diag::err_drv_argument_only_allowed_with)
7480
0
          << "-fvirtual-function-elimination"
7481
0
          << "-flto=full";
7482
7483
0
    CmdArgs.push_back("-fvirtual-function-elimination");
7484
0
  }
7485
7486
  // VFE requires whole-program-vtables, and enables it by default.
7487
0
  bool WholeProgramVTables = Args.hasFlag(
7488
0
      options::OPT_fwhole_program_vtables,
7489
0
      options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7490
0
  if (VirtualFunctionElimination && !WholeProgramVTables) {
7491
0
    D.Diag(diag::err_drv_argument_not_allowed_with)
7492
0
        << "-fno-whole-program-vtables"
7493
0
        << "-fvirtual-function-elimination";
7494
0
  }
7495
7496
0
  if (WholeProgramVTables) {
7497
    // PS4 uses the legacy LTO API, which does not support this feature in
7498
    // ThinLTO mode.
7499
0
    bool IsPS4 = getToolChain().getTriple().isPS4();
7500
7501
    // Check if we passed LTO options but they were suppressed because this is a
7502
    // device offloading action, or we passed device offload LTO options which
7503
    // were suppressed because this is not the device offload action.
7504
    // Check if we are using PS4 in regular LTO mode.
7505
    // Otherwise, issue an error.
7506
0
    if ((!IsUsingLTO && !D.isUsingLTO(!IsDeviceOffloadAction)) ||
7507
0
        (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7508
0
      D.Diag(diag::err_drv_argument_only_allowed_with)
7509
0
          << "-fwhole-program-vtables"
7510
0
          << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7511
7512
    // Propagate -fwhole-program-vtables if this is an LTO compile.
7513
0
    if (IsUsingLTO)
7514
0
      CmdArgs.push_back("-fwhole-program-vtables");
7515
0
  }
7516
7517
0
  bool DefaultsSplitLTOUnit =
7518
0
      ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7519
0
          (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7520
0
      (!Triple.isPS4() && UnifiedLTO);
7521
0
  bool SplitLTOUnit =
7522
0
      Args.hasFlag(options::OPT_fsplit_lto_unit,
7523
0
                   options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7524
0
  if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7525
0
    D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7526
0
                                                    << "-fsanitize=cfi";
7527
0
  if (SplitLTOUnit)
7528
0
    CmdArgs.push_back("-fsplit-lto-unit");
7529
7530
0
  if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
7531
0
                               options::OPT_fno_fat_lto_objects)) {
7532
0
    if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
7533
0
      assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
7534
0
      if (!Triple.isOSBinFormatELF()) {
7535
0
        D.Diag(diag::err_drv_unsupported_opt_for_target)
7536
0
            << A->getAsString(Args) << TC.getTripleString();
7537
0
      }
7538
0
      CmdArgs.push_back(Args.MakeArgString(
7539
0
          Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
7540
0
      CmdArgs.push_back("-flto-unit");
7541
0
      CmdArgs.push_back("-ffat-lto-objects");
7542
0
      A->render(Args, CmdArgs);
7543
0
    }
7544
0
  }
7545
7546
0
  if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7547
0
                               options::OPT_fno_global_isel)) {
7548
0
    CmdArgs.push_back("-mllvm");
7549
0
    if (A->getOption().matches(options::OPT_fglobal_isel)) {
7550
0
      CmdArgs.push_back("-global-isel=1");
7551
7552
      // GISel is on by default on AArch64 -O0, so don't bother adding
7553
      // the fallback remarks for it. Other combinations will add a warning of
7554
      // some kind.
7555
0
      bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7556
0
      bool IsOptLevelSupported = false;
7557
7558
0
      Arg *A = Args.getLastArg(options::OPT_O_Group);
7559
0
      if (Triple.getArch() == llvm::Triple::aarch64) {
7560
0
        if (!A || A->getOption().matches(options::OPT_O0))
7561
0
          IsOptLevelSupported = true;
7562
0
      }
7563
0
      if (!IsArchSupported || !IsOptLevelSupported) {
7564
0
        CmdArgs.push_back("-mllvm");
7565
0
        CmdArgs.push_back("-global-isel-abort=2");
7566
7567
0
        if (!IsArchSupported)
7568
0
          D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7569
0
        else
7570
0
          D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7571
0
      }
7572
0
    } else {
7573
0
      CmdArgs.push_back("-global-isel=0");
7574
0
    }
7575
0
  }
7576
7577
0
  if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
7578
0
     CmdArgs.push_back("-forder-file-instrumentation");
7579
     // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
7580
     // on, we need to pass these flags as linker flags and that will be handled
7581
     // outside of the compiler.
7582
0
     if (!IsUsingLTO) {
7583
0
       CmdArgs.push_back("-mllvm");
7584
0
       CmdArgs.push_back("-enable-order-file-instrumentation");
7585
0
     }
7586
0
  }
7587
7588
0
  if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7589
0
                               options::OPT_fno_force_enable_int128)) {
7590
0
    if (A->getOption().matches(options::OPT_fforce_enable_int128))
7591
0
      CmdArgs.push_back("-fforce-enable-int128");
7592
0
  }
7593
7594
0
  Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
7595
0
                    options::OPT_fno_keep_static_consts);
7596
0
  Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
7597
0
                    options::OPT_fno_keep_persistent_storage_variables);
7598
0
  Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
7599
0
                    options::OPT_fno_complete_member_pointers);
7600
0
  Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
7601
0
                     options::OPT_fno_cxx_static_destructors);
7602
7603
0
  addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7604
7605
0
  if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7606
0
                               options::OPT_mno_outline_atomics)) {
7607
    // Option -moutline-atomics supported for AArch64 target only.
7608
0
    if (!Triple.isAArch64()) {
7609
0
      D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
7610
0
          << Triple.getArchName() << A->getOption().getName();
7611
0
    } else {
7612
0
      if (A->getOption().matches(options::OPT_moutline_atomics)) {
7613
0
        CmdArgs.push_back("-target-feature");
7614
0
        CmdArgs.push_back("+outline-atomics");
7615
0
      } else {
7616
0
        CmdArgs.push_back("-target-feature");
7617
0
        CmdArgs.push_back("-outline-atomics");
7618
0
      }
7619
0
    }
7620
0
  } else if (Triple.isAArch64() &&
7621
0
             getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7622
0
    CmdArgs.push_back("-target-feature");
7623
0
    CmdArgs.push_back("+outline-atomics");
7624
0
  }
7625
7626
0
  if (Triple.isAArch64() &&
7627
0
      (Args.hasArg(options::OPT_mno_fmv) ||
7628
0
       (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
7629
0
       getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7630
    // Disable Function Multiversioning on AArch64 target.
7631
0
    CmdArgs.push_back("-target-feature");
7632
0
    CmdArgs.push_back("-fmv");
7633
0
  }
7634
7635
0
  if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7636
0
                   (TC.getTriple().isOSBinFormatELF() ||
7637
0
                    TC.getTriple().isOSBinFormatCOFF()) &&
7638
0
                       !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7639
0
                       !TC.getTriple().isOSNetBSD() &&
7640
0
                       !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7641
0
                       !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7642
0
    CmdArgs.push_back("-faddrsig");
7643
7644
0
  if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7645
0
      (EH || UnwindTables || AsyncUnwindTables ||
7646
0
       DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7647
0
    CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7648
7649
0
  if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7650
0
    std::string Str = A->getAsString(Args);
7651
0
    if (!TC.getTriple().isOSBinFormatELF())
7652
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
7653
0
          << Str << TC.getTripleString();
7654
0
    CmdArgs.push_back(Args.MakeArgString(Str));
7655
0
  }
7656
7657
  // Add the "-o out -x type src.c" flags last. This is done primarily to make
7658
  // the -cc1 command easier to edit when reproducing compiler crashes.
7659
0
  if (Output.getType() == types::TY_Dependencies) {
7660
    // Handled with other dependency code.
7661
0
  } else if (Output.isFilename()) {
7662
0
    if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7663
0
        Output.getType() == clang::driver::types::TY_IFS) {
7664
0
      SmallString<128> OutputFilename(Output.getFilename());
7665
0
      llvm::sys::path::replace_extension(OutputFilename, "ifs");
7666
0
      CmdArgs.push_back("-o");
7667
0
      CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7668
0
    } else {
7669
0
      CmdArgs.push_back("-o");
7670
0
      CmdArgs.push_back(Output.getFilename());
7671
0
    }
7672
0
  } else {
7673
0
    assert(Output.isNothing() && "Invalid output.");
7674
0
  }
7675
7676
0
  addDashXForInput(Args, Input, CmdArgs);
7677
7678
0
  ArrayRef<InputInfo> FrontendInputs = Input;
7679
0
  if (IsExtractAPI)
7680
0
    FrontendInputs = ExtractAPIInputs;
7681
0
  else if (Input.isNothing())
7682
0
    FrontendInputs = {};
7683
7684
0
  for (const InputInfo &Input : FrontendInputs) {
7685
0
    if (Input.isFilename())
7686
0
      CmdArgs.push_back(Input.getFilename());
7687
0
    else
7688
0
      Input.getInputArg().renderAsInput(Args, CmdArgs);
7689
0
  }
7690
7691
0
  if (D.CC1Main && !D.CCGenDiagnostics) {
7692
    // Invoke the CC1 directly in this process
7693
0
    C.addCommand(std::make_unique<CC1Command>(
7694
0
        JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7695
0
        Output, D.getPrependArg()));
7696
0
  } else {
7697
0
    C.addCommand(std::make_unique<Command>(
7698
0
        JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7699
0
        Output, D.getPrependArg()));
7700
0
  }
7701
7702
  // Make the compile command echo its inputs for /showFilenames.
7703
0
  if (Output.getType() == types::TY_Object &&
7704
0
      Args.hasFlag(options::OPT__SLASH_showFilenames,
7705
0
                   options::OPT__SLASH_showFilenames_, false)) {
7706
0
    C.getJobs().getJobs().back()->PrintInputFilenames = true;
7707
0
  }
7708
7709
0
  if (Arg *A = Args.getLastArg(options::OPT_pg))
7710
0
    if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
7711
0
        !Args.hasArg(options::OPT_mfentry))
7712
0
      D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
7713
0
                                                      << A->getAsString(Args);
7714
7715
  // Claim some arguments which clang supports automatically.
7716
7717
  // -fpch-preprocess is used with gcc to add a special marker in the output to
7718
  // include the PCH file.
7719
0
  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
7720
7721
  // Claim some arguments which clang doesn't support, but we don't
7722
  // care to warn the user about.
7723
0
  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
7724
0
  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
7725
7726
  // Disable warnings for clang -E -emit-llvm foo.c
7727
0
  Args.ClaimAllArgs(options::OPT_emit_llvm);
7728
0
}
7729
7730
Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
7731
    // CAUTION! The first constructor argument ("clang") is not arbitrary,
7732
    // as it is for other tools. Some operations on a Tool actually test
7733
    // whether that tool is Clang based on the Tool's Name as a string.
7734
0
    : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
7735
7736
0
Clang::~Clang() {}
7737
7738
/// Add options related to the Objective-C runtime/ABI.
7739
///
7740
/// Returns true if the runtime is non-fragile.
7741
ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
7742
                                      const InputInfoList &inputs,
7743
                                      ArgStringList &cmdArgs,
7744
0
                                      RewriteKind rewriteKind) const {
7745
  // Look for the controlling runtime option.
7746
0
  Arg *runtimeArg =
7747
0
      args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
7748
0
                      options::OPT_fobjc_runtime_EQ);
7749
7750
  // Just forward -fobjc-runtime= to the frontend.  This supercedes
7751
  // options about fragility.
7752
0
  if (runtimeArg &&
7753
0
      runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
7754
0
    ObjCRuntime runtime;
7755
0
    StringRef value = runtimeArg->getValue();
7756
0
    if (runtime.tryParse(value)) {
7757
0
      getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
7758
0
          << value;
7759
0
    }
7760
0
    if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
7761
0
        (runtime.getVersion() >= VersionTuple(2, 0)))
7762
0
      if (!getToolChain().getTriple().isOSBinFormatELF() &&
7763
0
          !getToolChain().getTriple().isOSBinFormatCOFF()) {
7764
0
        getToolChain().getDriver().Diag(
7765
0
            diag::err_drv_gnustep_objc_runtime_incompatible_binary)
7766
0
          << runtime.getVersion().getMajor();
7767
0
      }
7768
7769
0
    runtimeArg->render(args, cmdArgs);
7770
0
    return runtime;
7771
0
  }
7772
7773
  // Otherwise, we'll need the ABI "version".  Version numbers are
7774
  // slightly confusing for historical reasons:
7775
  //   1 - Traditional "fragile" ABI
7776
  //   2 - Non-fragile ABI, version 1
7777
  //   3 - Non-fragile ABI, version 2
7778
0
  unsigned objcABIVersion = 1;
7779
  // If -fobjc-abi-version= is present, use that to set the version.
7780
0
  if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
7781
0
    StringRef value = abiArg->getValue();
7782
0
    if (value == "1")
7783
0
      objcABIVersion = 1;
7784
0
    else if (value == "2")
7785
0
      objcABIVersion = 2;
7786
0
    else if (value == "3")
7787
0
      objcABIVersion = 3;
7788
0
    else
7789
0
      getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
7790
0
  } else {
7791
    // Otherwise, determine if we are using the non-fragile ABI.
7792
0
    bool nonFragileABIIsDefault =
7793
0
        (rewriteKind == RK_NonFragile ||
7794
0
         (rewriteKind == RK_None &&
7795
0
          getToolChain().IsObjCNonFragileABIDefault()));
7796
0
    if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
7797
0
                     options::OPT_fno_objc_nonfragile_abi,
7798
0
                     nonFragileABIIsDefault)) {
7799
// Determine the non-fragile ABI version to use.
7800
#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
7801
      unsigned nonFragileABIVersion = 1;
7802
#else
7803
0
      unsigned nonFragileABIVersion = 2;
7804
0
#endif
7805
7806
0
      if (Arg *abiArg =
7807
0
              args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
7808
0
        StringRef value = abiArg->getValue();
7809
0
        if (value == "1")
7810
0
          nonFragileABIVersion = 1;
7811
0
        else if (value == "2")
7812
0
          nonFragileABIVersion = 2;
7813
0
        else
7814
0
          getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
7815
0
              << value;
7816
0
      }
7817
7818
0
      objcABIVersion = 1 + nonFragileABIVersion;
7819
0
    } else {
7820
0
      objcABIVersion = 1;
7821
0
    }
7822
0
  }
7823
7824
  // We don't actually care about the ABI version other than whether
7825
  // it's non-fragile.
7826
0
  bool isNonFragile = objcABIVersion != 1;
7827
7828
  // If we have no runtime argument, ask the toolchain for its default runtime.
7829
  // However, the rewriter only really supports the Mac runtime, so assume that.
7830
0
  ObjCRuntime runtime;
7831
0
  if (!runtimeArg) {
7832
0
    switch (rewriteKind) {
7833
0
    case RK_None:
7834
0
      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7835
0
      break;
7836
0
    case RK_Fragile:
7837
0
      runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
7838
0
      break;
7839
0
    case RK_NonFragile:
7840
0
      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7841
0
      break;
7842
0
    }
7843
7844
    // -fnext-runtime
7845
0
  } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
7846
    // On Darwin, make this use the default behavior for the toolchain.
7847
0
    if (getToolChain().getTriple().isOSDarwin()) {
7848
0
      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7849
7850
      // Otherwise, build for a generic macosx port.
7851
0
    } else {
7852
0
      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7853
0
    }
7854
7855
    // -fgnu-runtime
7856
0
  } else {
7857
0
    assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
7858
    // Legacy behaviour is to target the gnustep runtime if we are in
7859
    // non-fragile mode or the GCC runtime in fragile mode.
7860
0
    if (isNonFragile)
7861
0
      runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
7862
0
    else
7863
0
      runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
7864
0
  }
7865
7866
0
  if (llvm::any_of(inputs, [](const InputInfo &input) {
7867
0
        return types::isObjC(input.getType());
7868
0
      }))
7869
0
    cmdArgs.push_back(
7870
0
        args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
7871
0
  return runtime;
7872
0
}
7873
7874
0
static bool maybeConsumeDash(const std::string &EH, size_t &I) {
7875
0
  bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
7876
0
  I += HaveDash;
7877
0
  return !HaveDash;
7878
0
}
7879
7880
namespace {
7881
struct EHFlags {
7882
  bool Synch = false;
7883
  bool Asynch = false;
7884
  bool NoUnwindC = false;
7885
};
7886
} // end anonymous namespace
7887
7888
/// /EH controls whether to run destructor cleanups when exceptions are
7889
/// thrown.  There are three modifiers:
7890
/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7891
/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7892
///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7893
/// - c: Assume that extern "C" functions are implicitly nounwind.
7894
/// The default is /EHs-c-, meaning cleanups are disabled.
7895
0
static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7896
0
  EHFlags EH;
7897
7898
0
  std::vector<std::string> EHArgs =
7899
0
      Args.getAllArgValues(options::OPT__SLASH_EH);
7900
0
  for (auto EHVal : EHArgs) {
7901
0
    for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7902
0
      switch (EHVal[I]) {
7903
0
      case 'a':
7904
0
        EH.Asynch = maybeConsumeDash(EHVal, I);
7905
0
        if (EH.Asynch)
7906
0
          EH.Synch = false;
7907
0
        continue;
7908
0
      case 'c':
7909
0
        EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7910
0
        continue;
7911
0
      case 's':
7912
0
        EH.Synch = maybeConsumeDash(EHVal, I);
7913
0
        if (EH.Synch)
7914
0
          EH.Asynch = false;
7915
0
        continue;
7916
0
      default:
7917
0
        break;
7918
0
      }
7919
0
      D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7920
0
      break;
7921
0
    }
7922
0
  }
7923
  // The /GX, /GX- flags are only processed if there are not /EH flags.
7924
  // The default is that /GX is not specified.
7925
0
  if (EHArgs.empty() &&
7926
0
      Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7927
0
                   /*Default=*/false)) {
7928
0
    EH.Synch = true;
7929
0
    EH.NoUnwindC = true;
7930
0
  }
7931
7932
0
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
7933
0
    EH.Synch = false;
7934
0
    EH.NoUnwindC = false;
7935
0
    EH.Asynch = false;
7936
0
  }
7937
7938
0
  return EH;
7939
0
}
7940
7941
void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7942
0
                           ArgStringList &CmdArgs) const {
7943
0
  bool isNVPTX = getToolChain().getTriple().isNVPTX();
7944
7945
0
  ProcessVSRuntimeLibrary(Args, CmdArgs);
7946
7947
0
  if (Arg *ShowIncludes =
7948
0
          Args.getLastArg(options::OPT__SLASH_showIncludes,
7949
0
                          options::OPT__SLASH_showIncludes_user)) {
7950
0
    CmdArgs.push_back("--show-includes");
7951
0
    if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7952
0
      CmdArgs.push_back("-sys-header-deps");
7953
0
  }
7954
7955
  // This controls whether or not we emit RTTI data for polymorphic types.
7956
0
  if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7957
0
                   /*Default=*/false))
7958
0
    CmdArgs.push_back("-fno-rtti-data");
7959
7960
  // This controls whether or not we emit stack-protector instrumentation.
7961
  // In MSVC, Buffer Security Check (/GS) is on by default.
7962
0
  if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7963
0
                               /*Default=*/true)) {
7964
0
    CmdArgs.push_back("-stack-protector");
7965
0
    CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7966
0
  }
7967
7968
0
  const Driver &D = getToolChain().getDriver();
7969
7970
0
  EHFlags EH = parseClangCLEHFlags(D, Args);
7971
0
  if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7972
0
    if (types::isCXX(InputType))
7973
0
      CmdArgs.push_back("-fcxx-exceptions");
7974
0
    CmdArgs.push_back("-fexceptions");
7975
0
    if (EH.Asynch)
7976
0
      CmdArgs.push_back("-fasync-exceptions");
7977
0
  }
7978
0
  if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7979
0
    CmdArgs.push_back("-fexternc-nounwind");
7980
7981
  // /EP should expand to -E -P.
7982
0
  if (Args.hasArg(options::OPT__SLASH_EP)) {
7983
0
    CmdArgs.push_back("-E");
7984
0
    CmdArgs.push_back("-P");
7985
0
  }
7986
7987
0
 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7988
0
                  options::OPT__SLASH_Zc_dllexportInlines,
7989
0
                  false)) {
7990
0
  CmdArgs.push_back("-fno-dllexport-inlines");
7991
0
 }
7992
7993
0
 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
7994
0
                  options::OPT__SLASH_Zc_wchar_t, false)) {
7995
0
   CmdArgs.push_back("-fno-wchar");
7996
0
 }
7997
7998
0
 if (Args.hasArg(options::OPT__SLASH_kernel)) {
7999
0
   llvm::Triple::ArchType Arch = getToolChain().getArch();
8000
0
   std::vector<std::string> Values =
8001
0
       Args.getAllArgValues(options::OPT__SLASH_arch);
8002
0
   if (!Values.empty()) {
8003
0
     llvm::SmallSet<std::string, 4> SupportedArches;
8004
0
     if (Arch == llvm::Triple::x86)
8005
0
       SupportedArches.insert("IA32");
8006
8007
0
     for (auto &V : Values)
8008
0
       if (!SupportedArches.contains(V))
8009
0
         D.Diag(diag::err_drv_argument_not_allowed_with)
8010
0
             << std::string("/arch:").append(V) << "/kernel";
8011
0
   }
8012
8013
0
   CmdArgs.push_back("-fno-rtti");
8014
0
   if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8015
0
     D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8016
0
                                                     << "/kernel";
8017
0
 }
8018
8019
0
  Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8020
0
  Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8021
0
  if (MostGeneralArg && BestCaseArg)
8022
0
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8023
0
        << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8024
8025
0
  if (MostGeneralArg) {
8026
0
    Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8027
0
    Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8028
0
    Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8029
8030
0
    Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8031
0
    Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8032
0
    if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8033
0
      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8034
0
          << FirstConflict->getAsString(Args)
8035
0
          << SecondConflict->getAsString(Args);
8036
8037
0
    if (SingleArg)
8038
0
      CmdArgs.push_back("-fms-memptr-rep=single");
8039
0
    else if (MultipleArg)
8040
0
      CmdArgs.push_back("-fms-memptr-rep=multiple");
8041
0
    else
8042
0
      CmdArgs.push_back("-fms-memptr-rep=virtual");
8043
0
  }
8044
8045
0
  if (Args.hasArg(options::OPT_regcall4))
8046
0
    CmdArgs.push_back("-regcall4");
8047
8048
  // Parse the default calling convention options.
8049
0
  if (Arg *CCArg =
8050
0
          Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8051
0
                          options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8052
0
                          options::OPT__SLASH_Gregcall)) {
8053
0
    unsigned DCCOptId = CCArg->getOption().getID();
8054
0
    const char *DCCFlag = nullptr;
8055
0
    bool ArchSupported = !isNVPTX;
8056
0
    llvm::Triple::ArchType Arch = getToolChain().getArch();
8057
0
    switch (DCCOptId) {
8058
0
    case options::OPT__SLASH_Gd:
8059
0
      DCCFlag = "-fdefault-calling-conv=cdecl";
8060
0
      break;
8061
0
    case options::OPT__SLASH_Gr:
8062
0
      ArchSupported = Arch == llvm::Triple::x86;
8063
0
      DCCFlag = "-fdefault-calling-conv=fastcall";
8064
0
      break;
8065
0
    case options::OPT__SLASH_Gz:
8066
0
      ArchSupported = Arch == llvm::Triple::x86;
8067
0
      DCCFlag = "-fdefault-calling-conv=stdcall";
8068
0
      break;
8069
0
    case options::OPT__SLASH_Gv:
8070
0
      ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8071
0
      DCCFlag = "-fdefault-calling-conv=vectorcall";
8072
0
      break;
8073
0
    case options::OPT__SLASH_Gregcall:
8074
0
      ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8075
0
      DCCFlag = "-fdefault-calling-conv=regcall";
8076
0
      break;
8077
0
    }
8078
8079
    // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8080
0
    if (ArchSupported && DCCFlag)
8081
0
      CmdArgs.push_back(DCCFlag);
8082
0
  }
8083
8084
0
  if (Args.hasArg(options::OPT__SLASH_Gregcall4))
8085
0
    CmdArgs.push_back("-regcall4");
8086
8087
0
  Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
8088
8089
0
  if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
8090
0
    CmdArgs.push_back("-fdiagnostics-format");
8091
0
    CmdArgs.push_back("msvc");
8092
0
  }
8093
8094
0
  if (Args.hasArg(options::OPT__SLASH_kernel))
8095
0
    CmdArgs.push_back("-fms-kernel");
8096
8097
0
  for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8098
0
    StringRef GuardArgs = A->getValue();
8099
    // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8100
    // "ehcont-".
8101
0
    if (GuardArgs.equals_insensitive("cf")) {
8102
      // Emit CFG instrumentation and the table of address-taken functions.
8103
0
      CmdArgs.push_back("-cfguard");
8104
0
    } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8105
      // Emit only the table of address-taken functions.
8106
0
      CmdArgs.push_back("-cfguard-no-checks");
8107
0
    } else if (GuardArgs.equals_insensitive("ehcont")) {
8108
      // Emit EH continuation table.
8109
0
      CmdArgs.push_back("-ehcontguard");
8110
0
    } else if (GuardArgs.equals_insensitive("cf-") ||
8111
0
               GuardArgs.equals_insensitive("ehcont-")) {
8112
      // Do nothing, but we might want to emit a security warning in future.
8113
0
    } else {
8114
0
      D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8115
0
    }
8116
0
    A->claim();
8117
0
  }
8118
0
}
8119
8120
const char *Clang::getBaseInputName(const ArgList &Args,
8121
0
                                    const InputInfo &Input) {
8122
0
  return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
8123
0
}
8124
8125
const char *Clang::getBaseInputStem(const ArgList &Args,
8126
0
                                    const InputInfoList &Inputs) {
8127
0
  const char *Str = getBaseInputName(Args, Inputs[0]);
8128
8129
0
  if (const char *End = strrchr(Str, '.'))
8130
0
    return Args.MakeArgString(std::string(Str, End));
8131
8132
0
  return Str;
8133
0
}
8134
8135
const char *Clang::getDependencyFileName(const ArgList &Args,
8136
0
                                         const InputInfoList &Inputs) {
8137
  // FIXME: Think about this more.
8138
8139
0
  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8140
0
    SmallString<128> OutputFilename(OutputOpt->getValue());
8141
0
    llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8142
0
    return Args.MakeArgString(OutputFilename);
8143
0
  }
8144
8145
0
  return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
8146
0
}
8147
8148
// Begin ClangAs
8149
8150
void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8151
0
                                ArgStringList &CmdArgs) const {
8152
0
  StringRef CPUName;
8153
0
  StringRef ABIName;
8154
0
  const llvm::Triple &Triple = getToolChain().getTriple();
8155
0
  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8156
8157
0
  CmdArgs.push_back("-target-abi");
8158
0
  CmdArgs.push_back(ABIName.data());
8159
0
}
8160
8161
void ClangAs::AddX86TargetArgs(const ArgList &Args,
8162
0
                               ArgStringList &CmdArgs) const {
8163
0
  addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
8164
0
                        /*IsLTO=*/false);
8165
8166
0
  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8167
0
    StringRef Value = A->getValue();
8168
0
    if (Value == "intel" || Value == "att") {
8169
0
      CmdArgs.push_back("-mllvm");
8170
0
      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
8171
0
    } else {
8172
0
      getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8173
0
          << A->getSpelling() << Value;
8174
0
    }
8175
0
  }
8176
0
}
8177
8178
void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8179
0
                                     ArgStringList &CmdArgs) const {
8180
0
  CmdArgs.push_back("-target-abi");
8181
0
  CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
8182
0
                                               getToolChain().getTriple())
8183
0
                        .data());
8184
0
}
8185
8186
void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8187
0
                               ArgStringList &CmdArgs) const {
8188
0
  const llvm::Triple &Triple = getToolChain().getTriple();
8189
0
  StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8190
8191
0
  CmdArgs.push_back("-target-abi");
8192
0
  CmdArgs.push_back(ABIName.data());
8193
8194
0
  if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8195
0
                   options::OPT_mno_default_build_attributes, true)) {
8196
0
      CmdArgs.push_back("-mllvm");
8197
0
      CmdArgs.push_back("-riscv-add-build-attributes");
8198
0
  }
8199
0
}
8200
8201
void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8202
                           const InputInfo &Output, const InputInfoList &Inputs,
8203
                           const ArgList &Args,
8204
0
                           const char *LinkingOutput) const {
8205
0
  ArgStringList CmdArgs;
8206
8207
0
  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8208
0
  const InputInfo &Input = Inputs[0];
8209
8210
0
  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8211
0
  const std::string &TripleStr = Triple.getTriple();
8212
0
  const auto &D = getToolChain().getDriver();
8213
8214
  // Don't warn about "clang -w -c foo.s"
8215
0
  Args.ClaimAllArgs(options::OPT_w);
8216
  // and "clang -emit-llvm -c foo.s"
8217
0
  Args.ClaimAllArgs(options::OPT_emit_llvm);
8218
8219
0
  claimNoWarnArgs(Args);
8220
8221
  // Invoke ourselves in -cc1as mode.
8222
  //
8223
  // FIXME: Implement custom jobs for internal actions.
8224
0
  CmdArgs.push_back("-cc1as");
8225
8226
  // Add the "effective" target triple.
8227
0
  CmdArgs.push_back("-triple");
8228
0
  CmdArgs.push_back(Args.MakeArgString(TripleStr));
8229
8230
0
  getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
8231
8232
  // Set the output mode, we currently only expect to be used as a real
8233
  // assembler.
8234
0
  CmdArgs.push_back("-filetype");
8235
0
  CmdArgs.push_back("obj");
8236
8237
  // Set the main file name, so that debug info works even with
8238
  // -save-temps or preprocessed assembly.
8239
0
  CmdArgs.push_back("-main-file-name");
8240
0
  CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
8241
8242
  // Add the target cpu
8243
0
  std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
8244
0
  if (!CPU.empty()) {
8245
0
    CmdArgs.push_back("-target-cpu");
8246
0
    CmdArgs.push_back(Args.MakeArgString(CPU));
8247
0
  }
8248
8249
  // Add the target features
8250
0
  getTargetFeatures(D, Triple, Args, CmdArgs, true);
8251
8252
  // Ignore explicit -force_cpusubtype_ALL option.
8253
0
  (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8254
8255
  // Pass along any -I options so we get proper .include search paths.
8256
0
  Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8257
8258
  // Determine the original source input.
8259
0
  auto FindSource = [](const Action *S) -> const Action * {
8260
0
    while (S->getKind() != Action::InputClass) {
8261
0
      assert(!S->getInputs().empty() && "unexpected root action!");
8262
0
      S = S->getInputs()[0];
8263
0
    }
8264
0
    return S;
8265
0
  };
8266
0
  const Action *SourceAction = FindSource(&JA);
8267
8268
  // Forward -g and handle debug info related flags, assuming we are dealing
8269
  // with an actual assembly file.
8270
0
  bool WantDebug = false;
8271
0
  Args.ClaimAllArgs(options::OPT_g_Group);
8272
0
  if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8273
0
    WantDebug = !A->getOption().matches(options::OPT_g0) &&
8274
0
                !A->getOption().matches(options::OPT_ggdb0);
8275
8276
0
  llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8277
0
      llvm::codegenoptions::NoDebugInfo;
8278
8279
  // Add the -fdebug-compilation-dir flag if needed.
8280
0
  const char *DebugCompilationDir =
8281
0
      addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
8282
8283
0
  if (SourceAction->getType() == types::TY_Asm ||
8284
0
      SourceAction->getType() == types::TY_PP_Asm) {
8285
    // You might think that it would be ok to set DebugInfoKind outside of
8286
    // the guard for source type, however there is a test which asserts
8287
    // that some assembler invocation receives no -debug-info-kind,
8288
    // and it's not clear whether that test is just overly restrictive.
8289
0
    DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8290
0
                               : llvm::codegenoptions::NoDebugInfo);
8291
8292
0
    addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
8293
0
                         CmdArgs);
8294
8295
    // Set the AT_producer to the clang version when using the integrated
8296
    // assembler on assembly source files.
8297
0
    CmdArgs.push_back("-dwarf-debug-producer");
8298
0
    CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
8299
8300
    // And pass along -I options
8301
0
    Args.AddAllArgs(CmdArgs, options::OPT_I);
8302
0
  }
8303
0
  const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
8304
0
  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8305
0
                          llvm::DebuggerKind::Default);
8306
0
  renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
8307
0
  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
8308
8309
  // Handle -fPIC et al -- the relocation-model affects the assembler
8310
  // for some targets.
8311
0
  llvm::Reloc::Model RelocationModel;
8312
0
  unsigned PICLevel;
8313
0
  bool IsPIE;
8314
0
  std::tie(RelocationModel, PICLevel, IsPIE) =
8315
0
      ParsePICArgs(getToolChain(), Args);
8316
8317
0
  const char *RMName = RelocationModelName(RelocationModel);
8318
0
  if (RMName) {
8319
0
    CmdArgs.push_back("-mrelocation-model");
8320
0
    CmdArgs.push_back(RMName);
8321
0
  }
8322
8323
  // Optionally embed the -cc1as level arguments into the debug info, for build
8324
  // analysis.
8325
0
  if (getToolChain().UseDwarfDebugFlags()) {
8326
0
    ArgStringList OriginalArgs;
8327
0
    for (const auto &Arg : Args)
8328
0
      Arg->render(Args, OriginalArgs);
8329
8330
0
    SmallString<256> Flags;
8331
0
    const char *Exec = getToolChain().getDriver().getClangProgramPath();
8332
0
    EscapeSpacesAndBackslashes(Exec, Flags);
8333
0
    for (const char *OriginalArg : OriginalArgs) {
8334
0
      SmallString<128> EscapedArg;
8335
0
      EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
8336
0
      Flags += " ";
8337
0
      Flags += EscapedArg;
8338
0
    }
8339
0
    CmdArgs.push_back("-dwarf-debug-flags");
8340
0
    CmdArgs.push_back(Args.MakeArgString(Flags));
8341
0
  }
8342
8343
  // FIXME: Add -static support, once we have it.
8344
8345
  // Add target specific flags.
8346
0
  switch (getToolChain().getArch()) {
8347
0
  default:
8348
0
    break;
8349
8350
0
  case llvm::Triple::mips:
8351
0
  case llvm::Triple::mipsel:
8352
0
  case llvm::Triple::mips64:
8353
0
  case llvm::Triple::mips64el:
8354
0
    AddMIPSTargetArgs(Args, CmdArgs);
8355
0
    break;
8356
8357
0
  case llvm::Triple::x86:
8358
0
  case llvm::Triple::x86_64:
8359
0
    AddX86TargetArgs(Args, CmdArgs);
8360
0
    break;
8361
8362
0
  case llvm::Triple::arm:
8363
0
  case llvm::Triple::armeb:
8364
0
  case llvm::Triple::thumb:
8365
0
  case llvm::Triple::thumbeb:
8366
    // This isn't in AddARMTargetArgs because we want to do this for assembly
8367
    // only, not C/C++.
8368
0
    if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8369
0
                     options::OPT_mno_default_build_attributes, true)) {
8370
0
        CmdArgs.push_back("-mllvm");
8371
0
        CmdArgs.push_back("-arm-add-build-attributes");
8372
0
    }
8373
0
    break;
8374
8375
0
  case llvm::Triple::aarch64:
8376
0
  case llvm::Triple::aarch64_32:
8377
0
  case llvm::Triple::aarch64_be:
8378
0
    if (Args.hasArg(options::OPT_mmark_bti_property)) {
8379
0
      CmdArgs.push_back("-mllvm");
8380
0
      CmdArgs.push_back("-aarch64-mark-bti-property");
8381
0
    }
8382
0
    break;
8383
8384
0
  case llvm::Triple::loongarch32:
8385
0
  case llvm::Triple::loongarch64:
8386
0
    AddLoongArchTargetArgs(Args, CmdArgs);
8387
0
    break;
8388
8389
0
  case llvm::Triple::riscv32:
8390
0
  case llvm::Triple::riscv64:
8391
0
    AddRISCVTargetArgs(Args, CmdArgs);
8392
0
    break;
8393
0
  }
8394
8395
  // Consume all the warning flags. Usually this would be handled more
8396
  // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8397
  // doesn't handle that so rather than warning about unused flags that are
8398
  // actually used, we'll lie by omission instead.
8399
  // FIXME: Stop lying and consume only the appropriate driver flags
8400
0
  Args.ClaimAllArgs(options::OPT_W_Group);
8401
8402
0
  CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8403
0
                                    getToolChain().getDriver());
8404
8405
0
  Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8406
8407
0
  if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8408
0
    addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8409
0
                       Output.getFilename());
8410
8411
  // Fixup any previous commands that use -object-file-name because when we
8412
  // generated them, the final .obj name wasn't yet known.
8413
0
  for (Command &J : C.getJobs()) {
8414
0
    if (SourceAction != FindSource(&J.getSource()))
8415
0
      continue;
8416
0
    auto &JArgs = J.getArguments();
8417
0
    for (unsigned I = 0; I < JArgs.size(); ++I) {
8418
0
      if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
8419
0
          Output.isFilename()) {
8420
0
       ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8421
0
       addDebugObjectName(Args, NewArgs, DebugCompilationDir,
8422
0
                          Output.getFilename());
8423
0
       NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
8424
0
       J.replaceArguments(NewArgs);
8425
0
       break;
8426
0
      }
8427
0
    }
8428
0
  }
8429
8430
0
  assert(Output.isFilename() && "Unexpected lipo output.");
8431
0
  CmdArgs.push_back("-o");
8432
0
  CmdArgs.push_back(Output.getFilename());
8433
8434
0
  const llvm::Triple &T = getToolChain().getTriple();
8435
0
  Arg *A;
8436
0
  if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
8437
0
      T.isOSBinFormatELF()) {
8438
0
    CmdArgs.push_back("-split-dwarf-output");
8439
0
    CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
8440
0
  }
8441
8442
0
  if (Triple.isAMDGPU())
8443
0
    handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8444
8445
0
  assert(Input.isFilename() && "Invalid input.");
8446
0
  CmdArgs.push_back(Input.getFilename());
8447
8448
0
  const char *Exec = getToolChain().getDriver().getClangProgramPath();
8449
0
  if (D.CC1Main && !D.CCGenDiagnostics) {
8450
    // Invoke cc1as directly in this process.
8451
0
    C.addCommand(std::make_unique<CC1Command>(
8452
0
        JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8453
0
        Output, D.getPrependArg()));
8454
0
  } else {
8455
0
    C.addCommand(std::make_unique<Command>(
8456
0
        JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8457
0
        Output, D.getPrependArg()));
8458
0
  }
8459
0
}
8460
8461
// Begin OffloadBundler
8462
8463
void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8464
                                  const InputInfo &Output,
8465
                                  const InputInfoList &Inputs,
8466
                                  const llvm::opt::ArgList &TCArgs,
8467
0
                                  const char *LinkingOutput) const {
8468
  // The version with only one output is expected to refer to a bundling job.
8469
0
  assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8470
8471
  // The bundling command looks like this:
8472
  // clang-offload-bundler -type=bc
8473
  //   -targets=host-triple,openmp-triple1,openmp-triple2
8474
  //   -output=output_file
8475
  //   -input=unbundle_file_host
8476
  //   -input=unbundle_file_tgt1
8477
  //   -input=unbundle_file_tgt2
8478
8479
0
  ArgStringList CmdArgs;
8480
8481
  // Get the type.
8482
0
  CmdArgs.push_back(TCArgs.MakeArgString(
8483
0
      Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
8484
8485
0
  assert(JA.getInputs().size() == Inputs.size() &&
8486
0
         "Not have inputs for all dependence actions??");
8487
8488
  // Get the targets.
8489
0
  SmallString<128> Triples;
8490
0
  Triples += "-targets=";
8491
0
  for (unsigned I = 0; I < Inputs.size(); ++I) {
8492
0
    if (I)
8493
0
      Triples += ',';
8494
8495
    // Find ToolChain for this input.
8496
0
    Action::OffloadKind CurKind = Action::OFK_Host;
8497
0
    const ToolChain *CurTC = &getToolChain();
8498
0
    const Action *CurDep = JA.getInputs()[I];
8499
8500
0
    if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
8501
0
      CurTC = nullptr;
8502
0
      OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
8503
0
        assert(CurTC == nullptr && "Expected one dependence!");
8504
0
        CurKind = A->getOffloadingDeviceKind();
8505
0
        CurTC = TC;
8506
0
      });
8507
0
    }
8508
0
    Triples += Action::GetOffloadKindName(CurKind);
8509
0
    Triples += '-';
8510
0
    Triples += CurTC->getTriple().normalize();
8511
0
    if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
8512
0
        !StringRef(CurDep->getOffloadingArch()).empty()) {
8513
0
      Triples += '-';
8514
0
      Triples += CurDep->getOffloadingArch();
8515
0
    }
8516
8517
    // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8518
    //       with each toolchain.
8519
0
    StringRef GPUArchName;
8520
0
    if (CurKind == Action::OFK_OpenMP) {
8521
      // Extract GPUArch from -march argument in TC argument list.
8522
0
      for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8523
0
        auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8524
0
        auto Arch = ArchStr.starts_with_insensitive("-march=");
8525
0
        if (Arch) {
8526
0
          GPUArchName = ArchStr.substr(7);
8527
0
          Triples += "-";
8528
0
          break;
8529
0
        }
8530
0
      }
8531
0
      Triples += GPUArchName.str();
8532
0
    }
8533
0
  }
8534
0
  CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8535
8536
  // Get bundled file command.
8537
0
  CmdArgs.push_back(
8538
0
      TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
8539
8540
  // Get unbundled files command.
8541
0
  for (unsigned I = 0; I < Inputs.size(); ++I) {
8542
0
    SmallString<128> UB;
8543
0
    UB += "-input=";
8544
8545
    // Find ToolChain for this input.
8546
0
    const ToolChain *CurTC = &getToolChain();
8547
0
    if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
8548
0
      CurTC = nullptr;
8549
0
      OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
8550
0
        assert(CurTC == nullptr && "Expected one dependence!");
8551
0
        CurTC = TC;
8552
0
      });
8553
0
      UB += C.addTempFile(
8554
0
          C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
8555
0
    } else {
8556
0
      UB += CurTC->getInputFilename(Inputs[I]);
8557
0
    }
8558
0
    CmdArgs.push_back(TCArgs.MakeArgString(UB));
8559
0
  }
8560
0
  if (TCArgs.hasFlag(options::OPT_offload_compress,
8561
0
                     options::OPT_no_offload_compress, false))
8562
0
    CmdArgs.push_back("-compress");
8563
0
  if (TCArgs.hasArg(options::OPT_v))
8564
0
    CmdArgs.push_back("-verbose");
8565
  // All the inputs are encoded as commands.
8566
0
  C.addCommand(std::make_unique<Command>(
8567
0
      JA, *this, ResponseFileSupport::None(),
8568
0
      TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8569
0
      CmdArgs, std::nullopt, Output));
8570
0
}
8571
8572
void OffloadBundler::ConstructJobMultipleOutputs(
8573
    Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8574
    const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8575
0
    const char *LinkingOutput) const {
8576
  // The version with multiple outputs is expected to refer to a unbundling job.
8577
0
  auto &UA = cast<OffloadUnbundlingJobAction>(JA);
8578
8579
  // The unbundling command looks like this:
8580
  // clang-offload-bundler -type=bc
8581
  //   -targets=host-triple,openmp-triple1,openmp-triple2
8582
  //   -input=input_file
8583
  //   -output=unbundle_file_host
8584
  //   -output=unbundle_file_tgt1
8585
  //   -output=unbundle_file_tgt2
8586
  //   -unbundle
8587
8588
0
  ArgStringList CmdArgs;
8589
8590
0
  assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8591
0
  InputInfo Input = Inputs.front();
8592
8593
  // Get the type.
8594
0
  CmdArgs.push_back(TCArgs.MakeArgString(
8595
0
      Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
8596
8597
  // Get the targets.
8598
0
  SmallString<128> Triples;
8599
0
  Triples += "-targets=";
8600
0
  auto DepInfo = UA.getDependentActionsInfo();
8601
0
  for (unsigned I = 0; I < DepInfo.size(); ++I) {
8602
0
    if (I)
8603
0
      Triples += ',';
8604
8605
0
    auto &Dep = DepInfo[I];
8606
0
    Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8607
0
    Triples += '-';
8608
0
    Triples += Dep.DependentToolChain->getTriple().normalize();
8609
0
    if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8610
0
         Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8611
0
        !Dep.DependentBoundArch.empty()) {
8612
0
      Triples += '-';
8613
0
      Triples += Dep.DependentBoundArch;
8614
0
    }
8615
    // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8616
    //       with each toolchain.
8617
0
    StringRef GPUArchName;
8618
0
    if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8619
      // Extract GPUArch from -march argument in TC argument list.
8620
0
      for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8621
0
        StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8622
0
        auto Arch = ArchStr.starts_with_insensitive("-march=");
8623
0
        if (Arch) {
8624
0
          GPUArchName = ArchStr.substr(7);
8625
0
          Triples += "-";
8626
0
          break;
8627
0
        }
8628
0
      }
8629
0
      Triples += GPUArchName.str();
8630
0
    }
8631
0
  }
8632
8633
0
  CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8634
8635
  // Get bundled file command.
8636
0
  CmdArgs.push_back(
8637
0
      TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
8638
8639
  // Get unbundled files command.
8640
0
  for (unsigned I = 0; I < Outputs.size(); ++I) {
8641
0
    SmallString<128> UB;
8642
0
    UB += "-output=";
8643
0
    UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
8644
0
    CmdArgs.push_back(TCArgs.MakeArgString(UB));
8645
0
  }
8646
0
  CmdArgs.push_back("-unbundle");
8647
0
  CmdArgs.push_back("-allow-missing-bundles");
8648
0
  if (TCArgs.hasArg(options::OPT_v))
8649
0
    CmdArgs.push_back("-verbose");
8650
8651
  // All the inputs are encoded as commands.
8652
0
  C.addCommand(std::make_unique<Command>(
8653
0
      JA, *this, ResponseFileSupport::None(),
8654
0
      TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8655
0
      CmdArgs, std::nullopt, Outputs));
8656
0
}
8657
8658
void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
8659
                                   const InputInfo &Output,
8660
                                   const InputInfoList &Inputs,
8661
                                   const llvm::opt::ArgList &Args,
8662
0
                                   const char *LinkingOutput) const {
8663
0
  ArgStringList CmdArgs;
8664
8665
  // Add the output file name.
8666
0
  assert(Output.isFilename() && "Invalid output.");
8667
0
  CmdArgs.push_back("-o");
8668
0
  CmdArgs.push_back(Output.getFilename());
8669
8670
  // Create the inputs to bundle the needed metadata.
8671
0
  for (const InputInfo &Input : Inputs) {
8672
0
    const Action *OffloadAction = Input.getAction();
8673
0
    const ToolChain *TC = OffloadAction->getOffloadingToolChain();
8674
0
    const ArgList &TCArgs =
8675
0
        C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
8676
0
                              OffloadAction->getOffloadingDeviceKind());
8677
0
    StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
8678
0
    StringRef Arch = OffloadAction->getOffloadingArch()
8679
0
                         ? OffloadAction->getOffloadingArch()
8680
0
                         : TCArgs.getLastArgValue(options::OPT_march_EQ);
8681
0
    StringRef Kind =
8682
0
      Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
8683
8684
0
    ArgStringList Features;
8685
0
    SmallVector<StringRef> FeatureArgs;
8686
0
    getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
8687
0
                      false);
8688
0
    llvm::copy_if(Features, std::back_inserter(FeatureArgs),
8689
0
                  [](StringRef Arg) { return !Arg.starts_with("-target"); });
8690
8691
0
    if (TC->getTriple().isAMDGPU()) {
8692
0
      for (StringRef Feature : llvm::split(Arch.split(':').second, ':')) {
8693
0
        FeatureArgs.emplace_back(
8694
0
            Args.MakeArgString(Feature.take_back() + Feature.drop_back()));
8695
0
      }
8696
0
    }
8697
8698
    // TODO: We need to pass in the full target-id and handle it properly in the
8699
    // linker wrapper.
8700
0
    SmallVector<std::string> Parts{
8701
0
        "file=" + File.str(),
8702
0
        "triple=" + TC->getTripleString(),
8703
0
        "arch=" + getProcessorFromTargetID(TC->getTriple(), Arch).str(),
8704
0
        "kind=" + Kind.str(),
8705
0
    };
8706
8707
0
    if (TC->getDriver().isUsingLTO(/* IsOffload */ true) ||
8708
0
        TC->getTriple().isAMDGPU())
8709
0
      for (StringRef Feature : FeatureArgs)
8710
0
        Parts.emplace_back("feature=" + Feature.str());
8711
8712
0
    CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
8713
0
  }
8714
8715
0
  C.addCommand(std::make_unique<Command>(
8716
0
      JA, *this, ResponseFileSupport::None(),
8717
0
      Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8718
0
      CmdArgs, Inputs, Output));
8719
0
}
8720
8721
void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
8722
                                 const InputInfo &Output,
8723
                                 const InputInfoList &Inputs,
8724
                                 const ArgList &Args,
8725
0
                                 const char *LinkingOutput) const {
8726
0
  const Driver &D = getToolChain().getDriver();
8727
0
  const llvm::Triple TheTriple = getToolChain().getTriple();
8728
0
  ArgStringList CmdArgs;
8729
8730
  // Pass the CUDA path to the linker wrapper tool.
8731
0
  for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
8732
0
    auto TCRange = C.getOffloadToolChains(Kind);
8733
0
    for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
8734
0
      const ToolChain *TC = I.second;
8735
0
      if (TC->getTriple().isNVPTX()) {
8736
0
        CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
8737
0
        if (CudaInstallation.isValid())
8738
0
          CmdArgs.push_back(Args.MakeArgString(
8739
0
              "--cuda-path=" + CudaInstallation.getInstallPath()));
8740
0
        break;
8741
0
      }
8742
0
    }
8743
0
  }
8744
8745
  // Pass in the optimization level to use for LTO.
8746
0
  if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
8747
0
    StringRef OOpt;
8748
0
    if (A->getOption().matches(options::OPT_O4) ||
8749
0
        A->getOption().matches(options::OPT_Ofast))
8750
0
      OOpt = "3";
8751
0
    else if (A->getOption().matches(options::OPT_O)) {
8752
0
      OOpt = A->getValue();
8753
0
      if (OOpt == "g")
8754
0
        OOpt = "1";
8755
0
      else if (OOpt == "s" || OOpt == "z")
8756
0
        OOpt = "2";
8757
0
    } else if (A->getOption().matches(options::OPT_O0))
8758
0
      OOpt = "0";
8759
0
    if (!OOpt.empty())
8760
0
      CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
8761
0
  }
8762
8763
0
  CmdArgs.push_back(
8764
0
      Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
8765
0
  if (Args.hasArg(options::OPT_v))
8766
0
    CmdArgs.push_back("--wrapper-verbose");
8767
8768
0
  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
8769
0
    if (!A->getOption().matches(options::OPT_g0))
8770
0
      CmdArgs.push_back("--device-debug");
8771
0
  }
8772
8773
  // code-object-version=X needs to be passed to clang-linker-wrapper to ensure
8774
  // that it is used by lld.
8775
0
  if (const Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
8776
0
    CmdArgs.push_back(Args.MakeArgString("-mllvm"));
8777
0
    CmdArgs.push_back(Args.MakeArgString(
8778
0
        Twine("--amdhsa-code-object-version=") + A->getValue()));
8779
0
  }
8780
8781
0
  for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
8782
0
    CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
8783
8784
  // Forward remarks passes to the LLVM backend in the wrapper.
8785
0
  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
8786
0
    CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
8787
0
                                         A->getValue()));
8788
0
  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
8789
0
    CmdArgs.push_back(Args.MakeArgString(
8790
0
        Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
8791
0
  if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
8792
0
    CmdArgs.push_back(Args.MakeArgString(
8793
0
        Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
8794
0
  if (Args.getLastArg(options::OPT_save_temps_EQ))
8795
0
    CmdArgs.push_back("--save-temps");
8796
8797
  // Construct the link job so we can wrap around it.
8798
0
  Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
8799
0
  const auto &LinkCommand = C.getJobs().getJobs().back();
8800
8801
  // Forward -Xoffload-linker<-triple> arguments to the device link job.
8802
0
  for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
8803
0
    StringRef Val = A->getValue(0);
8804
0
    if (Val.empty())
8805
0
      CmdArgs.push_back(
8806
0
          Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
8807
0
    else
8808
0
      CmdArgs.push_back(Args.MakeArgString(
8809
0
          "--device-linker=" +
8810
0
          ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
8811
0
          A->getValue(1)));
8812
0
  }
8813
0
  Args.ClaimAllArgs(options::OPT_Xoffload_linker);
8814
8815
  // Embed bitcode instead of an object in JIT mode.
8816
0
  if (Args.hasFlag(options::OPT_fopenmp_target_jit,
8817
0
                   options::OPT_fno_openmp_target_jit, false))
8818
0
    CmdArgs.push_back("--embed-bitcode");
8819
8820
  // Forward `-mllvm` arguments to the LLVM invocations if present.
8821
0
  for (Arg *A : Args.filtered(options::OPT_mllvm)) {
8822
0
    CmdArgs.push_back("-mllvm");
8823
0
    CmdArgs.push_back(A->getValue());
8824
0
    A->claim();
8825
0
  }
8826
8827
  // Add the linker arguments to be forwarded by the wrapper.
8828
0
  CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
8829
0
                                       LinkCommand->getExecutable()));
8830
0
  CmdArgs.push_back("--");
8831
0
  for (const char *LinkArg : LinkCommand->getArguments())
8832
0
    CmdArgs.push_back(LinkArg);
8833
8834
0
  const char *Exec =
8835
0
      Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
8836
8837
  // Replace the executable and arguments of the link job with the
8838
  // wrapper.
8839
0
  LinkCommand->replaceExecutable(Exec);
8840
0
  LinkCommand->replaceArguments(CmdArgs);
8841
0
}