Coverage Report

Created: 2022-05-14 11:35

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/BackendUtil.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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/CodeGen/BackendUtil.h"
10
#include "clang/Basic/CodeGenOptions.h"
11
#include "clang/Basic/Diagnostic.h"
12
#include "clang/Basic/LangOptions.h"
13
#include "clang/Basic/TargetOptions.h"
14
#include "clang/Frontend/FrontendDiagnostic.h"
15
#include "clang/Frontend/Utils.h"
16
#include "clang/Lex/HeaderSearchOptions.h"
17
#include "llvm/ADT/SmallSet.h"
18
#include "llvm/ADT/StringExtras.h"
19
#include "llvm/ADT/StringSwitch.h"
20
#include "llvm/ADT/Triple.h"
21
#include "llvm/Analysis/AliasAnalysis.h"
22
#include "llvm/Analysis/StackSafetyAnalysis.h"
23
#include "llvm/Analysis/TargetLibraryInfo.h"
24
#include "llvm/Analysis/TargetTransformInfo.h"
25
#include "llvm/Bitcode/BitcodeReader.h"
26
#include "llvm/Bitcode/BitcodeWriter.h"
27
#include "llvm/Bitcode/BitcodeWriterPass.h"
28
#include "llvm/CodeGen/RegAllocRegistry.h"
29
#include "llvm/CodeGen/SchedulerRegistry.h"
30
#include "llvm/CodeGen/TargetSubtargetInfo.h"
31
#include "llvm/IR/DataLayout.h"
32
#include "llvm/IR/IRPrintingPasses.h"
33
#include "llvm/IR/LegacyPassManager.h"
34
#include "llvm/IR/Module.h"
35
#include "llvm/IR/ModuleSummaryIndex.h"
36
#include "llvm/IR/PassManager.h"
37
#include "llvm/IR/Verifier.h"
38
#include "llvm/LTO/LTOBackend.h"
39
#include "llvm/MC/MCAsmInfo.h"
40
#include "llvm/MC/SubtargetFeature.h"
41
#include "llvm/MC/TargetRegistry.h"
42
#include "llvm/Object/OffloadBinary.h"
43
#include "llvm/Passes/PassBuilder.h"
44
#include "llvm/Passes/PassPlugin.h"
45
#include "llvm/Passes/StandardInstrumentations.h"
46
#include "llvm/Support/BuryPointer.h"
47
#include "llvm/Support/CommandLine.h"
48
#include "llvm/Support/MemoryBuffer.h"
49
#include "llvm/Support/PrettyStackTrace.h"
50
#include "llvm/Support/TimeProfiler.h"
51
#include "llvm/Support/Timer.h"
52
#include "llvm/Support/ToolOutputFile.h"
53
#include "llvm/Support/raw_ostream.h"
54
#include "llvm/Target/TargetMachine.h"
55
#include "llvm/Target/TargetOptions.h"
56
#include "llvm/Transforms/Coroutines/CoroCleanup.h"
57
#include "llvm/Transforms/Coroutines/CoroEarly.h"
58
#include "llvm/Transforms/Coroutines/CoroElide.h"
59
#include "llvm/Transforms/Coroutines/CoroSplit.h"
60
#include "llvm/Transforms/IPO.h"
61
#include "llvm/Transforms/IPO/AlwaysInliner.h"
62
#include "llvm/Transforms/IPO/LowerTypeTests.h"
63
#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64
#include "llvm/Transforms/InstCombine/InstCombine.h"
65
#include "llvm/Transforms/Instrumentation.h"
66
#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67
#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
68
#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
69
#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
70
#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
71
#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
72
#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
73
#include "llvm/Transforms/Instrumentation/MemProfiler.h"
74
#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
75
#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
76
#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
77
#include "llvm/Transforms/ObjCARC.h"
78
#include "llvm/Transforms/Scalar.h"
79
#include "llvm/Transforms/Scalar/EarlyCSE.h"
80
#include "llvm/Transforms/Scalar/GVN.h"
81
#include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
82
#include "llvm/Transforms/Utils.h"
83
#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
84
#include "llvm/Transforms/Utils/Debugify.h"
85
#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
86
#include "llvm/Transforms/Utils/ModuleUtils.h"
87
#include "llvm/Transforms/Utils/NameAnonGlobals.h"
88
#include "llvm/Transforms/Utils/SymbolRewriter.h"
89
#include <memory>
90
using namespace clang;
91
using namespace llvm;
92
93
#define HANDLE_EXTENSION(Ext)                                                  \
94
  llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
95
#include "llvm/Support/Extension.def"
96
97
namespace llvm {
98
extern cl::opt<bool> DebugInfoCorrelate;
99
}
100
101
namespace {
102
103
// Default filename used for profile generation.
104
8
std::string getDefaultProfileGenName() {
105
8
  return DebugInfoCorrelate ? 
"default_%p.proflite"0
: "default_%m.profraw";
106
8
}
107
108
class EmitAssemblyHelper {
109
  DiagnosticsEngine &Diags;
110
  const HeaderSearchOptions &HSOpts;
111
  const CodeGenOptions &CodeGenOpts;
112
  const clang::TargetOptions &TargetOpts;
113
  const LangOptions &LangOpts;
114
  Module *TheModule;
115
116
  Timer CodeGenerationTime;
117
118
  std::unique_ptr<raw_pwrite_stream> OS;
119
120
  Triple TargetTriple;
121
122
4.39k
  TargetIRAnalysis getTargetIRAnalysis() const {
123
4.39k
    if (TM)
124
4.39k
      return TM->getTargetIRAnalysis();
125
126
0
    return TargetIRAnalysis();
127
4.39k
  }
128
129
  /// Generates the TargetMachine.
130
  /// Leaves TM unchanged if it is unable to create the target machine.
131
  /// Some of our clang tests specify triples which are not built
132
  /// into clang. This is okay because these tests check the generated
133
  /// IR, and they require DataLayout which depends on the triple.
134
  /// In this case, we allow this method to fail and not report an error.
135
  /// When MustCreateTM is used, we print an error if we are unable to load
136
  /// the requested target.
137
  void CreateTargetMachine(bool MustCreateTM);
138
139
  /// Add passes necessary to emit assembly or LLVM IR.
140
  ///
141
  /// \return True on success.
142
  bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
143
                     raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
144
145
7
  std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
146
7
    std::error_code EC;
147
7
    auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
148
7
                                                     llvm::sys::fs::OF_None);
149
7
    if (EC) {
150
0
      Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
151
0
      F.reset();
152
0
    }
153
7
    return F;
154
7
  }
155
156
  void
157
  RunOptimizationPipeline(BackendAction Action,
158
                          std::unique_ptr<raw_pwrite_stream> &OS,
159
                          std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS);
160
  void RunCodegenPipeline(BackendAction Action,
161
                          std::unique_ptr<raw_pwrite_stream> &OS,
162
                          std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
163
164
  /// Check whether we should emit a module summary for regular LTO.
165
  /// The module summary should be emitted by default for regular LTO
166
  /// except for ld64 targets.
167
  ///
168
  /// \return True if the module summary should be emitted.
169
505
  bool shouldEmitRegularLTOSummary() const {
170
505
    return CodeGenOpts.PrepareForLTO && 
!CodeGenOpts.DisableLLVMPasses22
&&
171
505
           
TargetTriple.getVendor() != llvm::Triple::Apple19
;
172
505
  }
173
174
public:
175
  EmitAssemblyHelper(DiagnosticsEngine &_Diags,
176
                     const HeaderSearchOptions &HeaderSearchOpts,
177
                     const CodeGenOptions &CGOpts,
178
                     const clang::TargetOptions &TOpts,
179
                     const LangOptions &LOpts, Module *M)
180
      : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
181
        TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
182
        CodeGenerationTime("codegen", "Code Generation Time"),
183
19.9k
        TargetTriple(TheModule->getTargetTriple()) {}
184
185
19.9k
  ~EmitAssemblyHelper() {
186
19.9k
    if (CodeGenOpts.DisableFree)
187
4.28k
      BuryPointer(std::move(TM));
188
19.9k
  }
189
190
  std::unique_ptr<TargetMachine> TM;
191
192
  // Emit output using the new pass manager for the optimization pipeline.
193
  void EmitAssembly(BackendAction Action,
194
                    std::unique_ptr<raw_pwrite_stream> OS);
195
};
196
}
197
198
static SanitizerCoverageOptions
199
16
getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
200
16
  SanitizerCoverageOptions Opts;
201
16
  Opts.CoverageType =
202
16
      static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
203
16
  Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
204
16
  Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
205
16
  Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
206
16
  Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
207
16
  Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
208
16
  Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
209
16
  Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
210
16
  Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
211
16
  Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
212
16
  Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
213
16
  Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
214
16
  Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
215
16
  Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
216
16
  Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
217
16
  Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
218
16
  return Opts;
219
16
}
220
221
// Check if ASan should use GC-friendly instrumentation for globals.
222
// First of all, there is no point if -fdata-sections is off (expect for MachO,
223
// where this is not a factor). Also, on ELF this feature requires an assembler
224
// extension that only works with -integrated-as at the moment.
225
95
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
226
95
  if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
227
80
    return false;
228
15
  switch (T.getObjectFormat()) {
229
8
  case Triple::MachO:
230
10
  case Triple::COFF:
231
10
    return true;
232
5
  case Triple::ELF:
233
5
    return !CGOpts.DisableIntegratedAS;
234
0
  case Triple::GOFF:
235
0
    llvm::report_fatal_error("ASan not implemented for GOFF");
236
0
  case Triple::XCOFF:
237
0
    llvm::report_fatal_error("ASan not implemented for XCOFF.");
238
0
  case Triple::Wasm:
239
0
  case Triple::DXContainer:
240
0
  case Triple::SPIRV:
241
0
  case Triple::UnknownObjectFormat:
242
0
    break;
243
15
  }
244
0
  return false;
245
15
}
246
247
static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
248
24.3k
                                         const CodeGenOptions &CodeGenOpts) {
249
24.3k
  TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
250
251
24.3k
  switch (CodeGenOpts.getVecLib()) {
252
0
  case CodeGenOptions::Accelerate:
253
0
    TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
254
0
    break;
255
0
  case CodeGenOptions::LIBMVEC:
256
0
    switch(TargetTriple.getArch()) {
257
0
      default:
258
0
        break;
259
0
      case llvm::Triple::x86_64:
260
0
        TLII->addVectorizableFunctionsFromVecLib
261
0
                (TargetLibraryInfoImpl::LIBMVEC_X86);
262
0
        break;
263
0
    }
264
0
    break;
265
0
  case CodeGenOptions::MASSV:
266
0
    TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
267
0
    break;
268
0
  case CodeGenOptions::SVML:
269
0
    TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
270
0
    break;
271
1
  case CodeGenOptions::Darwin_libsystem_m:
272
1
    TLII->addVectorizableFunctionsFromVecLib(
273
1
        TargetLibraryInfoImpl::DarwinLibSystemM);
274
1
    break;
275
24.3k
  default:
276
24.3k
    break;
277
24.3k
  }
278
24.3k
  return TLII;
279
24.3k
}
280
281
16.3k
static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
282
16.3k
  switch (CodeGenOpts.OptimizationLevel) {
283
0
  default:
284
0
    llvm_unreachable("Invalid optimization level!");
285
13.4k
  case 0:
286
13.4k
    return CodeGenOpt::None;
287
2.26k
  case 1:
288
2.26k
    return CodeGenOpt::Less;
289
478
  case 2:
290
478
    return CodeGenOpt::Default; // O2/Os/Oz
291
164
  case 3:
292
164
    return CodeGenOpt::Aggressive;
293
16.3k
  }
294
16.3k
}
295
296
static Optional<llvm::CodeModel::Model>
297
16.3k
getCodeModel(const CodeGenOptions &CodeGenOpts) {
298
16.3k
  unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
299
16.3k
                           .Case("tiny", llvm::CodeModel::Tiny)
300
16.3k
                           .Case("small", llvm::CodeModel::Small)
301
16.3k
                           .Case("kernel", llvm::CodeModel::Kernel)
302
16.3k
                           .Case("medium", llvm::CodeModel::Medium)
303
16.3k
                           .Case("large", llvm::CodeModel::Large)
304
16.3k
                           .Case("default", ~1u)
305
16.3k
                           .Default(~0u);
306
16.3k
  assert(CodeModel != ~0u && "invalid code model!");
307
16.3k
  if (CodeModel == ~1u)
308
16.3k
    return None;
309
5
  return static_cast<llvm::CodeModel::Model>(CodeModel);
310
16.3k
}
311
312
4.42k
static CodeGenFileType getCodeGenFileType(BackendAction Action) {
313
4.42k
  if (Action == Backend_EmitObj)
314
3.93k
    return CGFT_ObjectFile;
315
492
  else if (Action == Backend_EmitMCNull)
316
7
    return CGFT_Null;
317
485
  else {
318
485
    assert(Action == Backend_EmitAssembly && "Invalid action!");
319
0
    return CGFT_AssemblyFile;
320
485
  }
321
4.42k
}
322
323
39.9k
static bool actionRequiresCodeGen(BackendAction Action) {
324
39.9k
  return Action != Backend_EmitNothing && 
Action != Backend_EmitBC39.5k
&&
325
39.9k
         
Action != Backend_EmitLL38.4k
;
326
39.9k
}
327
328
static bool initTargetOptions(DiagnosticsEngine &Diags,
329
                              llvm::TargetOptions &Options,
330
                              const CodeGenOptions &CodeGenOpts,
331
                              const clang::TargetOptions &TargetOpts,
332
                              const LangOptions &LangOpts,
333
16.3k
                              const HeaderSearchOptions &HSOpts) {
334
16.3k
  switch (LangOpts.getThreadModel()) {
335
16.0k
  case LangOptions::ThreadModelKind::POSIX:
336
16.0k
    Options.ThreadModel = llvm::ThreadModel::POSIX;
337
16.0k
    break;
338
349
  case LangOptions::ThreadModelKind::Single:
339
349
    Options.ThreadModel = llvm::ThreadModel::Single;
340
349
    break;
341
16.3k
  }
342
343
  // Set float ABI type.
344
16.3k
  assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
345
16.3k
          CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
346
16.3k
         "Invalid Floating Point ABI!");
347
0
  Options.FloatABIType =
348
16.3k
      llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
349
16.3k
          .Case("soft", llvm::FloatABI::Soft)
350
16.3k
          .Case("softfp", llvm::FloatABI::Soft)
351
16.3k
          .Case("hard", llvm::FloatABI::Hard)
352
16.3k
          .Default(llvm::FloatABI::Default);
353
354
  // Set FP fusion mode.
355
16.3k
  switch (LangOpts.getDefaultFPContractMode()) {
356
12.0k
  case LangOptions::FPM_Off:
357
    // Preserve any contraction performed by the front-end.  (Strict performs
358
    // splitting of the muladd intrinsic in the backend.)
359
12.0k
    Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
360
12.0k
    break;
361
4.23k
  case LangOptions::FPM_On:
362
4.27k
  case LangOptions::FPM_FastHonorPragmas:
363
4.27k
    Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
364
4.27k
    break;
365
57
  case LangOptions::FPM_Fast:
366
57
    Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
367
57
    break;
368
16.3k
  }
369
370
16.3k
  Options.BinutilsVersion =
371
16.3k
      llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
372
16.3k
  Options.UseInitArray = CodeGenOpts.UseInitArray;
373
16.3k
  Options.LowerGlobalDtorsViaCxaAtExit =
374
16.3k
      CodeGenOpts.RegisterGlobalDtorsWithAtExit;
375
16.3k
  Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
376
16.3k
  Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
377
16.3k
  Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
378
379
  // Set EABI version.
380
16.3k
  Options.EABIVersion = TargetOpts.EABIVersion;
381
382
16.3k
  if (LangOpts.hasSjLjExceptions())
383
28
    Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
384
16.3k
  if (LangOpts.hasSEHExceptions())
385
22
    Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
386
16.3k
  if (LangOpts.hasDWARFExceptions())
387
22
    Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
388
16.3k
  if (LangOpts.hasWasmExceptions())
389
0
    Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
390
391
16.3k
  Options.NoInfsFPMath = LangOpts.NoHonorInfs;
392
16.3k
  Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
393
16.3k
  Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
394
16.3k
  Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
395
16.3k
  Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
396
397
16.3k
  Options.BBSections =
398
16.3k
      llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
399
16.3k
          .Case("all", llvm::BasicBlockSection::All)
400
16.3k
          .Case("labels", llvm::BasicBlockSection::Labels)
401
16.3k
          .StartsWith("list=", llvm::BasicBlockSection::List)
402
16.3k
          .Case("none", llvm::BasicBlockSection::None)
403
16.3k
          .Default(llvm::BasicBlockSection::None);
404
405
16.3k
  if (Options.BBSections == llvm::BasicBlockSection::List) {
406
2
    ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
407
2
        MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
408
2
    if (!MBOrErr) {
409
1
      Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
410
1
          << MBOrErr.getError().message();
411
1
      return false;
412
1
    }
413
1
    Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
414
1
  }
415
416
16.3k
  Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
417
16.3k
  Options.FunctionSections = CodeGenOpts.FunctionSections;
418
16.3k
  Options.DataSections = CodeGenOpts.DataSections;
419
16.3k
  Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
420
16.3k
  Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
421
16.3k
  Options.UniqueBasicBlockSectionNames =
422
16.3k
      CodeGenOpts.UniqueBasicBlockSectionNames;
423
16.3k
  Options.TLSSize = CodeGenOpts.TLSSize;
424
16.3k
  Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
425
16.3k
  Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
426
16.3k
  Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
427
16.3k
  Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
428
16.3k
  Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
429
16.3k
  Options.EmitAddrsig = CodeGenOpts.Addrsig;
430
16.3k
  Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
431
16.3k
  Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
432
16.3k
  Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
433
16.3k
  Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
434
16.3k
  Options.LoopAlignment = CodeGenOpts.LoopAlignment;
435
16.3k
  Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
436
16.3k
  Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
437
16.3k
  Options.Hotpatch = CodeGenOpts.HotPatch;
438
16.3k
  Options.JMCInstrument = CodeGenOpts.JMCInstrument;
439
440
16.3k
  switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
441
4
  case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
442
4
    Options.SwiftAsyncFramePointer =
443
4
        SwiftAsyncFramePointerMode::DeploymentBased;
444
4
    break;
445
446
16.3k
  case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
447
16.3k
    Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
448
16.3k
    break;
449
450
4
  case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
451
4
    Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
452
4
    break;
453
16.3k
  }
454
455
16.3k
  Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
456
16.3k
  Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
457
16.3k
  Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
458
16.3k
  Options.MCOptions.MCUseDwarfDirectory =
459
16.3k
      CodeGenOpts.NoDwarfDirectoryAsm
460
16.3k
          ? 
llvm::MCTargetOptions::DisableDwarfDirectory4
461
16.3k
          : 
llvm::MCTargetOptions::EnableDwarfDirectory16.3k
;
462
16.3k
  Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
463
16.3k
  Options.MCOptions.MCIncrementalLinkerCompatible =
464
16.3k
      CodeGenOpts.IncrementalLinkerCompatible;
465
16.3k
  Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
466
16.3k
  Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
467
16.3k
  Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
468
16.3k
  Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
469
16.3k
  Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
470
16.3k
  Options.MCOptions.ABIName = TargetOpts.ABI;
471
16.3k
  for (const auto &Entry : HSOpts.UserEntries)
472
38.0k
    if (!Entry.IsFramework &&
473
38.0k
        
(37.9k
Entry.Group == frontend::IncludeDirGroup::Quoted37.9k
||
474
37.9k
         
Entry.Group == frontend::IncludeDirGroup::Angled37.9k
||
475
37.9k
         
Entry.Group == frontend::IncludeDirGroup::System27.1k
))
476
33.5k
      Options.MCOptions.IASSearchPaths.push_back(
477
33.5k
          Entry.IgnoreSysRoot ? Entry.Path : 
HSOpts.Sysroot + Entry.Path0
);
478
16.3k
  Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
479
16.3k
  Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
480
16.3k
  Options.MisExpect = CodeGenOpts.MisExpect;
481
482
16.3k
  return true;
483
16.3k
}
484
485
static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
486
19.4k
                                            const LangOptions &LangOpts) {
487
19.4k
  if (!CodeGenOpts.EmitGcovArcs && 
!CodeGenOpts.EmitGcovNotes19.4k
)
488
19.4k
    return None;
489
  // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
490
  // LLVM's -default-gcov-version flag is set to something invalid.
491
15
  GCOVOptions Options;
492
15
  Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
493
15
  Options.EmitData = CodeGenOpts.EmitGcovArcs;
494
15
  llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
495
15
  Options.NoRedZone = CodeGenOpts.DisableRedZone;
496
15
  Options.Filter = CodeGenOpts.ProfileFilterFiles;
497
15
  Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
498
15
  Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
499
15
  return Options;
500
19.4k
}
501
502
static Optional<InstrProfOptions>
503
getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
504
19.4k
                    const LangOptions &LangOpts) {
505
19.4k
  if (!CodeGenOpts.hasProfileClangInstr())
506
19.3k
    return None;
507
117
  InstrProfOptions Options;
508
117
  Options.NoRedZone = CodeGenOpts.DisableRedZone;
509
117
  Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
510
117
  Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
511
117
  return Options;
512
19.4k
}
513
514
20.0k
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
515
20.0k
  SmallVector<const char *, 16> BackendArgs;
516
20.0k
  BackendArgs.push_back("clang"); // Fake program name.
517
20.0k
  if (!CodeGenOpts.DebugPass.empty()) {
518
1
    BackendArgs.push_back("-debug-pass");
519
1
    BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
520
1
  }
521
20.0k
  if (!CodeGenOpts.LimitFloatPrecision.empty()) {
522
0
    BackendArgs.push_back("-limit-float-precision");
523
0
    BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
524
0
  }
525
  // Check for the default "clang" invocation that won't set any cl::opt values.
526
  // Skip trying to parse the command line invocation to avoid the issues
527
  // described below.
528
20.0k
  if (BackendArgs.size() == 1)
529
20.0k
    return;
530
1
  BackendArgs.push_back(nullptr);
531
  // FIXME: The command line parser below is not thread-safe and shares a global
532
  // state, so this call might crash or overwrite the options of another Clang
533
  // instance in the same process.
534
1
  llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
535
1
                                    BackendArgs.data());
536
1
}
537
538
19.9k
void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
539
  // Create the TargetMachine for generating code.
540
19.9k
  std::string Error;
541
19.9k
  std::string Triple = TheModule->getTargetTriple();
542
19.9k
  const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
543
19.9k
  if (!TheTarget) {
544
3.63k
    if (MustCreateTM)
545
0
      Diags.Report(diag::err_fe_unable_to_create_target) << Error;
546
3.63k
    return;
547
3.63k
  }
548
549
16.3k
  Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
550
16.3k
  std::string FeaturesStr =
551
16.3k
      llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
552
16.3k
  llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
553
16.3k
  CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
554
555
16.3k
  llvm::TargetOptions Options;
556
16.3k
  if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
557
16.3k
                         HSOpts))
558
1
    return;
559
16.3k
  TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
560
16.3k
                                          Options, RM, CM, OptLevel));
561
16.3k
}
562
563
bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
564
                                       BackendAction Action,
565
                                       raw_pwrite_stream &OS,
566
4.39k
                                       raw_pwrite_stream *DwoOS) {
567
  // Add LibraryInfo.
568
4.39k
  std::unique_ptr<TargetLibraryInfoImpl> TLII(
569
4.39k
      createTLII(TargetTriple, CodeGenOpts));
570
4.39k
  CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
571
572
  // Normal mode, emit a .s or .o file by running the code generator. Note,
573
  // this also adds codegenerator level optimization passes.
574
4.39k
  CodeGenFileType CGFT = getCodeGenFileType(Action);
575
576
  // Add ObjC ARC final-cleanup optimizations. This is done as part of the
577
  // "codegen" passes so that it isn't run multiple times when there is
578
  // inlining happening.
579
4.39k
  if (CodeGenOpts.OptimizationLevel > 0)
580
376
    CodeGenPasses.add(createObjCARCContractPass());
581
582
4.39k
  if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
583
4.39k
                              /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
584
0
    Diags.Report(diag::err_fe_unable_to_interface_with_target);
585
0
    return false;
586
0
  }
587
588
4.39k
  return true;
589
4.39k
}
590
591
19.4k
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
592
19.4k
  switch (Opts.OptimizationLevel) {
593
0
  default:
594
0
    llvm_unreachable("Invalid optimization level!");
595
596
16.6k
  case 0:
597
16.6k
    return OptimizationLevel::O0;
598
599
2.14k
  case 1:
600
2.14k
    return OptimizationLevel::O1;
601
602
473
  case 2:
603
473
    switch (Opts.OptimizeSize) {
604
0
    default:
605
0
      llvm_unreachable("Invalid optimization level for size!");
606
607
405
    case 0:
608
405
      return OptimizationLevel::O2;
609
610
49
    case 1:
611
49
      return OptimizationLevel::Os;
612
613
19
    case 2:
614
19
      return OptimizationLevel::Oz;
615
473
    }
616
617
160
  case 3:
618
160
    return OptimizationLevel::O3;
619
19.4k
  }
620
19.4k
}
621
622
static void addSanitizers(const Triple &TargetTriple,
623
                          const CodeGenOptions &CodeGenOpts,
624
19.4k
                          const LangOptions &LangOpts, PassBuilder &PB) {
625
19.4k
  PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
626
19.4k
                                         OptimizationLevel Level) {
627
19.4k
    if (CodeGenOpts.hasSanitizeCoverage()) {
628
16
      auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
629
16
      MPM.addPass(ModuleSanitizerCoveragePass(
630
16
          SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
631
16
          CodeGenOpts.SanitizeCoverageIgnorelistFiles));
632
16
    }
633
634
38.8k
    auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
635
38.8k
      if (LangOpts.Sanitize.has(Mask)) {
636
39
        int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
637
39
        bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
638
639
39
        MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
640
39
                                       CodeGenOpts.SanitizeMemoryParamRetval);
641
39
        MPM.addPass(ModuleMemorySanitizerPass(options));
642
39
        FunctionPassManager FPM;
643
39
        FPM.addPass(MemorySanitizerPass(options));
644
39
        if (Level != OptimizationLevel::O0) {
645
          // MemorySanitizer inserts complex instrumentation that mostly
646
          // follows the logic of the original code, but operates on
647
          // "shadow" values. It can benefit from re-running some
648
          // general purpose optimization passes.
649
15
          FPM.addPass(EarlyCSEPass());
650
          // TODO: Consider add more passes like in
651
          // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
652
          // difference on size. It's not clear if the rest is still
653
          // usefull. InstCombinePass breakes
654
          // compiler-rt/test/msan/select_origin.cpp.
655
15
        }
656
39
        MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
657
39
      }
658
38.8k
    };
659
19.4k
    MSanPass(SanitizerKind::Memory, false);
660
19.4k
    MSanPass(SanitizerKind::KernelMemory, true);
661
662
19.4k
    if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
663
38
      MPM.addPass(ModuleThreadSanitizerPass());
664
38
      MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
665
38
    }
666
667
38.8k
    auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
668
38.8k
      if (LangOpts.Sanitize.has(Mask)) {
669
95
        bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
670
95
        bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
671
95
        llvm::AsanDtorKind DestructorKind =
672
95
            CodeGenOpts.getSanitizeAddressDtor();
673
95
        AddressSanitizerOptions Opts;
674
95
        Opts.CompileKernel = CompileKernel;
675
95
        Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
676
95
        Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
677
95
        Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
678
95
        MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
679
95
        MPM.addPass(ModuleAddressSanitizerPass(
680
95
            Opts, UseGlobalGC, UseOdrIndicator, DestructorKind));
681
95
      }
682
38.8k
    };
683
19.4k
    ASanPass(SanitizerKind::Address, false);
684
19.4k
    ASanPass(SanitizerKind::KernelAddress, true);
685
686
38.8k
    auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
687
38.8k
      if (LangOpts.Sanitize.has(Mask)) {
688
28
        bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
689
28
        MPM.addPass(HWAddressSanitizerPass(
690
28
            {CompileKernel, Recover,
691
28
             /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
692
28
      }
693
38.8k
    };
694
19.4k
    HWASanPass(SanitizerKind::HWAddress, false);
695
19.4k
    HWASanPass(SanitizerKind::KernelHWAddress, true);
696
697
19.4k
    if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
698
10
      MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
699
10
    }
700
19.4k
  });
701
19.4k
}
702
703
void EmitAssemblyHelper::RunOptimizationPipeline(
704
    BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
705
19.9k
    std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) {
706
19.9k
  Optional<PGOOptions> PGOOpt;
707
708
19.9k
  if (CodeGenOpts.hasProfileIRInstr())
709
    // -fprofile-generate.
710
5
    PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
711
5
                            ? getDefaultProfileGenName()
712
5
                            : 
CodeGenOpts.InstrProfileOutput0
,
713
5
                        "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
714
5
                        CodeGenOpts.DebugInfoForProfiling);
715
19.9k
  else if (CodeGenOpts.hasProfileIRUse()) {
716
    // -fprofile-use.
717
18
    auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? 
PGOOptions::CSIRUse4
718
18
                                                    : 
PGOOptions::NoCSAction14
;
719
18
    PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
720
18
                        CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
721
18
                        CSAction, CodeGenOpts.DebugInfoForProfiling);
722
19.9k
  } else if (!CodeGenOpts.SampleProfileFile.empty())
723
    // -fprofile-sample-use
724
11
    PGOOpt = PGOOptions(
725
11
        CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
726
11
        PGOOptions::SampleUse, PGOOptions::NoCSAction,
727
11
        CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
728
19.9k
  else if (CodeGenOpts.PseudoProbeForProfiling)
729
    // -fpseudo-probe-for-profiling
730
4
    PGOOpt =
731
4
        PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
732
4
                   CodeGenOpts.DebugInfoForProfiling, true);
733
19.9k
  else if (CodeGenOpts.DebugInfoForProfiling)
734
    // -fdebug-info-for-profiling
735
4
    PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
736
4
                        PGOOptions::NoCSAction, true);
737
738
  // Check to see if we want to generate a CS profile.
739
19.9k
  if (CodeGenOpts.hasProfileCSIRInstr()) {
740
6
    assert(!CodeGenOpts.hasProfileCSIRUse() &&
741
6
           "Cannot have both CSProfileUse pass and CSProfileGen pass at "
742
6
           "the same time");
743
6
    if (PGOOpt.hasValue()) {
744
3
      assert(PGOOpt->Action != PGOOptions::IRInstr &&
745
3
             PGOOpt->Action != PGOOptions::SampleUse &&
746
3
             "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
747
3
             " pass");
748
3
      PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
749
3
                                     ? 
getDefaultProfileGenName()1
750
3
                                     : 
CodeGenOpts.InstrProfileOutput2
;
751
3
      PGOOpt->CSAction = PGOOptions::CSIRInstr;
752
3
    } else
753
3
      PGOOpt = PGOOptions("",
754
3
                          CodeGenOpts.InstrProfileOutput.empty()
755
3
                              ? 
getDefaultProfileGenName()2
756
3
                              : 
CodeGenOpts.InstrProfileOutput1
,
757
3
                          "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
758
3
                          CodeGenOpts.DebugInfoForProfiling);
759
6
  }
760
19.9k
  if (TM)
761
16.3k
    TM->setPGOOption(PGOOpt);
762
763
19.9k
  PipelineTuningOptions PTO;
764
19.9k
  PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
765
  // For historical reasons, loop interleaving is set to mirror setting for loop
766
  // unrolling.
767
19.9k
  PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
768
19.9k
  PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
769
19.9k
  PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
770
19.9k
  PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
771
  // Only enable CGProfilePass when using integrated assembler, since
772
  // non-integrated assemblers don't recognize .cgprofile section.
773
19.9k
  PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
774
775
19.9k
  LoopAnalysisManager LAM;
776
19.9k
  FunctionAnalysisManager FAM;
777
19.9k
  CGSCCAnalysisManager CGAM;
778
19.9k
  ModuleAnalysisManager MAM;
779
780
19.9k
  bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
781
19.9k
  PassInstrumentationCallbacks PIC;
782
19.9k
  PrintPassOptions PrintPassOpts;
783
19.9k
  PrintPassOpts.Indent = DebugPassStructure;
784
19.9k
  PrintPassOpts.SkipAnalyses = DebugPassStructure;
785
19.9k
  StandardInstrumentations SI(CodeGenOpts.DebugPassManager ||
786
19.9k
                                  
DebugPassStructure19.9k
,
787
19.9k
                              /*VerifyEach*/ false, PrintPassOpts);
788
19.9k
  SI.registerCallbacks(PIC, &FAM);
789
19.9k
  PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
790
791
  // Attempt to load pass plugins and register their callbacks with PB.
792
19.9k
  for (auto &PluginFN : CodeGenOpts.PassPlugins) {
793
0
    auto PassPlugin = PassPlugin::Load(PluginFN);
794
0
    if (PassPlugin) {
795
0
      PassPlugin->registerPassBuilderCallbacks(PB);
796
0
    } else {
797
0
      Diags.Report(diag::err_fe_unable_to_load_plugin)
798
0
          << PluginFN << toString(PassPlugin.takeError());
799
0
    }
800
0
  }
801
19.9k
#define HANDLE_EXTENSION(Ext)                                                  \
802
19.9k
  get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
803
19.9k
#include "llvm/Support/Extension.def"
804
805
  // Register the target library analysis directly and give it a customized
806
  // preset TLI.
807
19.9k
  std::unique_ptr<TargetLibraryInfoImpl> TLII(
808
19.9k
      createTLII(TargetTriple, CodeGenOpts));
809
19.9k
  FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
810
811
  // Register all the basic analyses with the managers.
812
19.9k
  PB.registerModuleAnalyses(MAM);
813
19.9k
  PB.registerCGSCCAnalyses(CGAM);
814
19.9k
  PB.registerFunctionAnalyses(FAM);
815
19.9k
  PB.registerLoopAnalyses(LAM);
816
19.9k
  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
817
818
19.9k
  ModulePassManager MPM;
819
820
19.9k
  if (!CodeGenOpts.DisableLLVMPasses) {
821
    // Map our optimization levels into one of the distinct levels used to
822
    // configure the pipeline.
823
19.4k
    OptimizationLevel Level = mapToLevel(CodeGenOpts);
824
825
19.4k
    bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
826
19.4k
    bool IsLTO = CodeGenOpts.PrepareForLTO;
827
828
19.4k
    if (LangOpts.ObjCAutoRefCount) {
829
137
      PB.registerPipelineStartEPCallback(
830
137
          [](ModulePassManager &MPM, OptimizationLevel Level) {
831
137
            if (Level != OptimizationLevel::O0)
832
4
              MPM.addPass(
833
4
                  createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
834
137
          });
835
137
      PB.registerPipelineEarlySimplificationEPCallback(
836
137
          [](ModulePassManager &MPM, OptimizationLevel Level) {
837
137
            if (Level != OptimizationLevel::O0)
838
4
              MPM.addPass(ObjCARCAPElimPass());
839
137
          });
840
137
      PB.registerScalarOptimizerLateEPCallback(
841
137
          [](FunctionPassManager &FPM, OptimizationLevel Level) {
842
137
            if (Level != OptimizationLevel::O0)
843
4
              FPM.addPass(ObjCARCOptPass());
844
137
          });
845
137
    }
846
847
    // If we reached here with a non-empty index file name, then the index
848
    // file was empty and we are not performing ThinLTO backend compilation
849
    // (used in testing in a distributed build environment).
850
19.4k
    bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
851
    // If so drop any the type test assume sequences inserted for whole program
852
    // vtables so that codegen doesn't complain.
853
19.4k
    if (IsThinLTOPostLink)
854
4
      PB.registerPipelineStartEPCallback(
855
4
          [](ModulePassManager &MPM, OptimizationLevel Level) {
856
4
            MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
857
4
                                           /*ImportSummary=*/nullptr,
858
4
                                           /*DropTypeTests=*/true));
859
4
          });
860
861
19.4k
    if (CodeGenOpts.InstrumentFunctions ||
862
19.4k
        
CodeGenOpts.InstrumentFunctionEntryBare19.4k
||
863
19.4k
        
CodeGenOpts.InstrumentFunctionsAfterInlining19.4k
||
864
19.4k
        
CodeGenOpts.InstrumentForProfiling19.4k
) {
865
68
      PB.registerPipelineStartEPCallback(
866
68
          [](ModulePassManager &MPM, OptimizationLevel Level) {
867
68
            MPM.addPass(createModuleToFunctionPassAdaptor(
868
68
                EntryExitInstrumenterPass(/*PostInlining=*/false)));
869
68
          });
870
68
      PB.registerOptimizerLastEPCallback(
871
68
          [](ModulePassManager &MPM, OptimizationLevel Level) {
872
68
            MPM.addPass(createModuleToFunctionPassAdaptor(
873
68
                EntryExitInstrumenterPass(/*PostInlining=*/true)));
874
68
          });
875
68
    }
876
877
    // Register callbacks to schedule sanitizer passes at the appropriate part
878
    // of the pipeline.
879
19.4k
    if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
880
4
      PB.registerScalarOptimizerLateEPCallback(
881
4
          [](FunctionPassManager &FPM, OptimizationLevel Level) {
882
4
            FPM.addPass(BoundsCheckingPass());
883
4
          });
884
885
    // Don't add sanitizers if we are here from ThinLTO PostLink. That already
886
    // done on PreLink stage.
887
19.4k
    if (!IsThinLTOPostLink)
888
19.4k
      addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
889
890
19.4k
    if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
891
15
      PB.registerPipelineStartEPCallback(
892
15
          [Options](ModulePassManager &MPM, OptimizationLevel Level) {
893
15
            MPM.addPass(GCOVProfilerPass(*Options));
894
15
          });
895
19.4k
    if (Optional<InstrProfOptions> Options =
896
19.4k
            getInstrProfOptions(CodeGenOpts, LangOpts))
897
117
      PB.registerPipelineStartEPCallback(
898
117
          [Options](ModulePassManager &MPM, OptimizationLevel Level) {
899
117
            MPM.addPass(InstrProfiling(*Options, false));
900
117
          });
901
902
19.4k
    if (CodeGenOpts.OptimizationLevel == 0) {
903
16.6k
      MPM = PB.buildO0DefaultPipeline(Level, IsLTO || 
IsThinLTO16.5k
);
904
16.6k
    } else 
if (2.78k
IsThinLTO2.78k
) {
905
31
      MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
906
2.74k
    } else if (IsLTO) {
907
25
      MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
908
2.72k
    } else {
909
2.72k
      MPM = PB.buildPerModuleDefaultPipeline(Level);
910
2.72k
    }
911
912
19.4k
    if (!CodeGenOpts.MemoryProfileOutput.empty()) {
913
4
      MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
914
4
      MPM.addPass(ModuleMemProfilerPass());
915
4
    }
916
19.4k
  }
917
918
  // Add a verifier pass if requested. We don't have to do this if the action
919
  // requires code generation because there will already be a verifier pass in
920
  // the code-generation pipeline.
921
19.9k
  if (!actionRequiresCodeGen(Action) && 
CodeGenOpts.VerifyModule15.5k
)
922
15.5k
    MPM.addPass(VerifierPass());
923
924
19.9k
  switch (Action) {
925
545
  case Backend_EmitBC:
926
545
    if (CodeGenOpts.PrepareForThinLTO && 
!CodeGenOpts.DisableLLVMPasses41
) {
927
40
      if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
928
1
        ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
929
1
        if (!ThinLinkOS)
930
0
          return;
931
1
      }
932
40
      if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
933
39
        TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
934
39
                                 CodeGenOpts.EnableSplitLTOUnit);
935
40
      MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()1
936
40
                                                           : 
nullptr39
));
937
505
    } else {
938
      // Emit a module summary by default for Regular LTO except for ld64
939
      // targets
940
505
      bool EmitLTOSummary = shouldEmitRegularLTOSummary();
941
505
      if (EmitLTOSummary) {
942
15
        if (!TheModule->getModuleFlag("ThinLTO"))
943
15
          TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
944
15
        if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
945
15
          TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
946
15
                                   uint32_t(1));
947
15
      }
948
505
      MPM.addPass(
949
505
          BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
950
505
    }
951
545
    break;
952
953
14.8k
  case Backend_EmitLL:
954
14.8k
    MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
955
14.8k
    break;
956
957
4.62k
  default:
958
4.62k
    break;
959
19.9k
  }
960
961
  // Now that we have all of the passes ready, run them.
962
19.9k
  {
963
19.9k
    PrettyStackTraceString CrashInfo("Optimizer");
964
19.9k
    llvm::TimeTraceScope TimeScope("Optimizer");
965
19.9k
    MPM.run(*TheModule, MAM);
966
19.9k
  }
967
19.9k
}
968
969
void EmitAssemblyHelper::RunCodegenPipeline(
970
    BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
971
19.9k
    std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
972
  // We still use the legacy PM to run the codegen pipeline since the new PM
973
  // does not work with the codegen pipeline.
974
  // FIXME: make the new PM work with the codegen pipeline.
975
19.9k
  legacy::PassManager CodeGenPasses;
976
977
  // Append any output we need to the pass manager.
978
19.9k
  switch (Action) {
979
478
  case Backend_EmitAssembly:
980
485
  case Backend_EmitMCNull:
981
4.39k
  case Backend_EmitObj:
982
4.39k
    CodeGenPasses.add(
983
4.39k
        createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
984
4.39k
    if (!CodeGenOpts.SplitDwarfOutput.empty()) {
985
6
      DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
986
6
      if (!DwoOS)
987
0
        return;
988
6
    }
989
4.39k
    if (!AddEmitPasses(CodeGenPasses, Action, *OS,
990
4.39k
                       DwoOS ? 
&DwoOS->os()6
:
nullptr4.39k
))
991
      // FIXME: Should we handle this error differently?
992
0
      return;
993
4.39k
    break;
994
15.5k
  default:
995
15.5k
    return;
996
19.9k
  }
997
998
4.39k
  {
999
4.39k
    PrettyStackTraceString CrashInfo("Code generation");
1000
4.39k
    llvm::TimeTraceScope TimeScope("CodeGenPasses");
1001
4.39k
    CodeGenPasses.run(*TheModule);
1002
4.39k
  }
1003
4.39k
}
1004
1005
void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1006
19.9k
                                      std::unique_ptr<raw_pwrite_stream> OS) {
1007
19.9k
  TimeRegion Region(CodeGenOpts.TimePasses ? 
&CodeGenerationTime13
:
nullptr19.9k
);
1008
19.9k
  setCommandLineOpts(CodeGenOpts);
1009
1010
19.9k
  bool RequiresCodeGen = actionRequiresCodeGen(Action);
1011
19.9k
  CreateTargetMachine(RequiresCodeGen);
1012
1013
19.9k
  if (RequiresCodeGen && 
!TM4.40k
)
1014
1
    return;
1015
19.9k
  if (TM)
1016
16.3k
    TheModule->setDataLayout(TM->createDataLayout());
1017
1018
  // Before executing passes, print the final values of the LLVM options.
1019
19.9k
  cl::PrintOptionValues();
1020
1021
19.9k
  std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1022
19.9k
  RunOptimizationPipeline(Action, OS, ThinLinkOS);
1023
19.9k
  RunCodegenPipeline(Action, OS, DwoOS);
1024
1025
19.9k
  if (ThinLinkOS)
1026
1
    ThinLinkOS->keep();
1027
19.9k
  if (DwoOS)
1028
6
    DwoOS->keep();
1029
19.9k
}
1030
1031
static void runThinLTOBackend(
1032
    DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1033
    const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1034
    const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1035
    std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1036
45
    std::string ProfileRemapping, BackendAction Action) {
1037
45
  StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1038
45
      ModuleToDefinedGVSummaries;
1039
45
  CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1040
1041
45
  setCommandLineOpts(CGOpts);
1042
1043
  // We can simply import the values mentioned in the combined index, since
1044
  // we should only invoke this using the individual indexes written out
1045
  // via a WriteIndexesThinBackend.
1046
45
  FunctionImporter::ImportMapTy ImportList;
1047
45
  if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1048
0
    return;
1049
1050
45
  auto AddStream = [&](size_t Task) {
1051
26
    return std::make_unique<CachedFileStream>(std::move(OS),
1052
26
                                              CGOpts.ObjectFilenameForDebug);
1053
26
  };
1054
45
  lto::Config Conf;
1055
45
  if (CGOpts.SaveTempsFilePrefix != "") {
1056
5
    if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1057
5
                                    /* UseInputModulePath */ false)) {
1058
0
      handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1059
0
        errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1060
0
               << '\n';
1061
0
      });
1062
0
    }
1063
5
  }
1064
45
  Conf.CPU = TOpts.CPU;
1065
45
  Conf.CodeModel = getCodeModel(CGOpts);
1066
45
  Conf.MAttrs = TOpts.Features;
1067
45
  Conf.RelocModel = CGOpts.RelocationModel;
1068
45
  Conf.CGOptLevel = getCGOptLevel(CGOpts);
1069
45
  Conf.OptLevel = CGOpts.OptimizationLevel;
1070
45
  initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1071
45
  Conf.SampleProfile = std::move(SampleProfile);
1072
45
  Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1073
  // For historical reasons, loop interleaving is set to mirror setting for loop
1074
  // unrolling.
1075
45
  Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1076
45
  Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1077
45
  Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1078
  // Only enable CGProfilePass when using integrated assembler, since
1079
  // non-integrated assemblers don't recognize .cgprofile section.
1080
45
  Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1081
1082
  // Context sensitive profile.
1083
45
  if (CGOpts.hasProfileCSIRInstr()) {
1084
1
    Conf.RunCSIRInstr = true;
1085
1
    Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1086
44
  } else if (CGOpts.hasProfileCSIRUse()) {
1087
2
    Conf.RunCSIRInstr = false;
1088
2
    Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1089
2
  }
1090
1091
45
  Conf.ProfileRemapping = std::move(ProfileRemapping);
1092
45
  Conf.DebugPassManager = CGOpts.DebugPassManager;
1093
45
  Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1094
45
  Conf.RemarksFilename = CGOpts.OptRecordFile;
1095
45
  Conf.RemarksPasses = CGOpts.OptRecordPasses;
1096
45
  Conf.RemarksFormat = CGOpts.OptRecordFormat;
1097
45
  Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1098
45
  Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1099
45
  switch (Action) {
1100
0
  case Backend_EmitNothing:
1101
0
    Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1102
0
      return false;
1103
0
    };
1104
0
    break;
1105
17
  case Backend_EmitLL:
1106
17
    Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1107
17
      M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1108
17
      return false;
1109
17
    };
1110
17
    break;
1111
1
  case Backend_EmitBC:
1112
1
    Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1113
1
      WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1114
1
      return false;
1115
1
    };
1116
1
    break;
1117
27
  default:
1118
27
    Conf.CGFileType = getCodeGenFileType(Action);
1119
27
    break;
1120
45
  }
1121
45
  if (Error E =
1122
45
          thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1123
45
                      ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1124
45
                      /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1125
1
    handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1126
1
      errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1127
1
    });
1128
1
  }
1129
45
}
1130
1131
void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1132
                              const HeaderSearchOptions &HeaderOpts,
1133
                              const CodeGenOptions &CGOpts,
1134
                              const clang::TargetOptions &TOpts,
1135
                              const LangOptions &LOpts,
1136
                              StringRef TDesc, Module *M,
1137
                              BackendAction Action,
1138
20.0k
                              std::unique_ptr<raw_pwrite_stream> OS) {
1139
1140
20.0k
  llvm::TimeTraceScope TimeScope("Backend");
1141
1142
20.0k
  std::unique_ptr<llvm::Module> EmptyModule;
1143
20.0k
  if (!CGOpts.ThinLTOIndexFile.empty()) {
1144
    // If we are performing a ThinLTO importing compile, load the function index
1145
    // into memory and pass it into runThinLTOBackend, which will run the
1146
    // function importer and invoke LTO passes.
1147
50
    std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1148
50
    if (Error E = llvm::getModuleSummaryIndexForFile(
1149
50
                      CGOpts.ThinLTOIndexFile,
1150
50
                      /*IgnoreEmptyThinLTOIndexFile*/ true)
1151
50
                      .moveInto(CombinedIndex)) {
1152
1
      logAllUnhandledErrors(std::move(E), errs(),
1153
1
                            "Error loading index file '" +
1154
1
                            CGOpts.ThinLTOIndexFile + "': ");
1155
1
      return;
1156
1
    }
1157
1158
    // A null CombinedIndex means we should skip ThinLTO compilation
1159
    // (LLVM will optionally ignore empty index files, returning null instead
1160
    // of an error).
1161
49
    if (CombinedIndex) {
1162
46
      if (!CombinedIndex->skipModuleByDistributedBackend()) {
1163
45
        runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1164
45
                          TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1165
45
                          CGOpts.ProfileRemappingFile, Action);
1166
45
        return;
1167
45
      }
1168
      // Distributed indexing detected that nothing from the module is needed
1169
      // for the final linking. So we can skip the compilation. We sill need to
1170
      // output an empty object file to make sure that a linker does not fail
1171
      // trying to read it. Also for some features, like CFI, we must skip
1172
      // the compilation as CombinedIndex does not contain all required
1173
      // information.
1174
1
      EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1175
1
      EmptyModule->setTargetTriple(M->getTargetTriple());
1176
1
      M = EmptyModule.get();
1177
1
    }
1178
49
  }
1179
1180
19.9k
  EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1181
19.9k
  AsmHelper.EmitAssembly(Action, std::move(OS));
1182
1183
  // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1184
  // DataLayout.
1185
19.9k
  if (AsmHelper.TM) {
1186
16.3k
    std::string DLDesc = M->getDataLayout().getStringRepresentation();
1187
16.3k
    if (DLDesc != TDesc) {
1188
0
      unsigned DiagID = Diags.getCustomDiagID(
1189
0
          DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1190
0
                                    "expected target description '%1'");
1191
0
      Diags.Report(DiagID) << DLDesc << TDesc;
1192
0
    }
1193
16.3k
  }
1194
19.9k
}
1195
1196
// With -fembed-bitcode, save a copy of the llvm IR as data in the
1197
// __LLVM,__bitcode section.
1198
void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1199
19.6k
                         llvm::MemoryBufferRef Buf) {
1200
19.6k
  if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1201
19.6k
    return;
1202
22
  llvm::embedBitcodeInModule(
1203
22
      *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1204
22
      CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1205
22
      CGOpts.CmdArgs);
1206
22
}
1207
1208
void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1209
35.3k
                        DiagnosticsEngine &Diags) {
1210
35.3k
  if (CGOpts.OffloadObjects.empty())
1211
35.3k
    return;
1212
1213
3
  
for (StringRef OffloadObject : CGOpts.OffloadObjects)2
{
1214
3
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1215
3
        llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1216
3
    if (std::error_code EC = ObjectOrErr.getError()) {
1217
0
      auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1218
0
                                          "could not open '%0' for embedding");
1219
0
      Diags.Report(DiagID) << OffloadObject;
1220
0
      return;
1221
0
    }
1222
1223
3
    llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1224
3
                              Align(OffloadBinary::getAlignment()));
1225
3
  }
1226
2
}