Coverage Report

Created: 2020-02-15 09:57

/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/TargetLibraryInfo.h"
22
#include "llvm/Analysis/TargetTransformInfo.h"
23
#include "llvm/Bitcode/BitcodeReader.h"
24
#include "llvm/Bitcode/BitcodeWriter.h"
25
#include "llvm/Bitcode/BitcodeWriterPass.h"
26
#include "llvm/CodeGen/RegAllocRegistry.h"
27
#include "llvm/CodeGen/SchedulerRegistry.h"
28
#include "llvm/CodeGen/TargetSubtargetInfo.h"
29
#include "llvm/IR/DataLayout.h"
30
#include "llvm/IR/IRPrintingPasses.h"
31
#include "llvm/IR/LegacyPassManager.h"
32
#include "llvm/IR/Module.h"
33
#include "llvm/IR/ModuleSummaryIndex.h"
34
#include "llvm/IR/Verifier.h"
35
#include "llvm/LTO/LTOBackend.h"
36
#include "llvm/MC/MCAsmInfo.h"
37
#include "llvm/MC/SubtargetFeature.h"
38
#include "llvm/Passes/PassBuilder.h"
39
#include "llvm/Passes/PassPlugin.h"
40
#include "llvm/Passes/StandardInstrumentations.h"
41
#include "llvm/Support/BuryPointer.h"
42
#include "llvm/Support/CommandLine.h"
43
#include "llvm/Support/MemoryBuffer.h"
44
#include "llvm/Support/PrettyStackTrace.h"
45
#include "llvm/Support/TargetRegistry.h"
46
#include "llvm/Support/TimeProfiler.h"
47
#include "llvm/Support/Timer.h"
48
#include "llvm/Support/raw_ostream.h"
49
#include "llvm/Target/TargetMachine.h"
50
#include "llvm/Target/TargetOptions.h"
51
#include "llvm/Transforms/Coroutines.h"
52
#include "llvm/Transforms/IPO.h"
53
#include "llvm/Transforms/IPO/AlwaysInliner.h"
54
#include "llvm/Transforms/IPO/LowerTypeTests.h"
55
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
56
#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
57
#include "llvm/Transforms/InstCombine/InstCombine.h"
58
#include "llvm/Transforms/Instrumentation.h"
59
#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
60
#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
61
#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
62
#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
63
#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
64
#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
65
#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
66
#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
67
#include "llvm/Transforms/ObjCARC.h"
68
#include "llvm/Transforms/Scalar.h"
69
#include "llvm/Transforms/Scalar/GVN.h"
70
#include "llvm/Transforms/Utils.h"
71
#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
72
#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
73
#include "llvm/Transforms/Utils/NameAnonGlobals.h"
74
#include "llvm/Transforms/Utils/SymbolRewriter.h"
75
#include <memory>
76
using namespace clang;
77
using namespace llvm;
78
79
#define HANDLE_EXTENSION(Ext)                                                  \
80
  llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
81
#include "llvm/Support/Extension.def"
82
83
namespace {
84
85
// Default filename used for profile generation.
86
static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
87
88
class EmitAssemblyHelper {
89
  DiagnosticsEngine &Diags;
90
  const HeaderSearchOptions &HSOpts;
91
  const CodeGenOptions &CodeGenOpts;
92
  const clang::TargetOptions &TargetOpts;
93
  const LangOptions &LangOpts;
94
  Module *TheModule;
95
96
  Timer CodeGenerationTime;
97
98
  std::unique_ptr<raw_pwrite_stream> OS;
99
100
42.4k
  TargetIRAnalysis getTargetIRAnalysis() const {
101
42.4k
    if (TM)
102
42.0k
      return TM->getTargetIRAnalysis();
103
339
104
339
    return TargetIRAnalysis();
105
339
  }
106
107
  void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
108
109
  /// Generates the TargetMachine.
110
  /// Leaves TM unchanged if it is unable to create the target machine.
111
  /// Some of our clang tests specify triples which are not built
112
  /// into clang. This is okay because these tests check the generated
113
  /// IR, and they require DataLayout which depends on the triple.
114
  /// In this case, we allow this method to fail and not report an error.
115
  /// When MustCreateTM is used, we print an error if we are unable to load
116
  /// the requested target.
117
  void CreateTargetMachine(bool MustCreateTM);
118
119
  /// Add passes necessary to emit assembly or LLVM IR.
120
  ///
121
  /// \return True on success.
122
  bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
123
                     raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
124
125
9
  std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
126
9
    std::error_code EC;
127
9
    auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
128
9
                                                     llvm::sys::fs::OF_None);
129
9
    if (EC) {
130
0
      Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
131
0
      F.reset();
132
0
    }
133
9
    return F;
134
9
  }
135
136
public:
137
  EmitAssemblyHelper(DiagnosticsEngine &_Diags,
138
                     const HeaderSearchOptions &HeaderSearchOpts,
139
                     const CodeGenOptions &CGOpts,
140
                     const clang::TargetOptions &TOpts,
141
                     const LangOptions &LOpts, Module *M)
142
      : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
143
        TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
144
14.2k
        CodeGenerationTime("codegen", "Code Generation Time") {}
145
146
14.2k
  ~EmitAssemblyHelper() {
147
14.2k
    if (CodeGenOpts.DisableFree)
148
3.55k
      BuryPointer(std::move(TM));
149
14.2k
  }
150
151
  std::unique_ptr<TargetMachine> TM;
152
153
  void EmitAssembly(BackendAction Action,
154
                    std::unique_ptr<raw_pwrite_stream> OS);
155
156
  void EmitAssemblyWithNewPassManager(BackendAction Action,
157
                                      std::unique_ptr<raw_pwrite_stream> OS);
158
};
159
160
// We need this wrapper to access LangOpts and CGOpts from extension functions
161
// that we add to the PassManagerBuilder.
162
class PassManagerBuilderWrapper : public PassManagerBuilder {
163
public:
164
  PassManagerBuilderWrapper(const Triple &TargetTriple,
165
                            const CodeGenOptions &CGOpts,
166
                            const LangOptions &LangOpts)
167
      : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
168
13.8k
        LangOpts(LangOpts) {}
169
65
  const Triple &getTargetTriple() const { return TargetTriple; }
170
95
  const CodeGenOptions &getCGOpts() const { return CGOpts; }
171
0
  const LangOptions &getLangOpts() const { return LangOpts; }
172
173
private:
174
  const Triple &TargetTriple;
175
  const CodeGenOptions &CGOpts;
176
  const LangOptions &LangOpts;
177
};
178
}
179
180
6
static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
181
6
  if (Builder.OptLevel > 0)
182
6
    PM.add(createObjCARCAPElimPass());
183
6
}
184
185
126
static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
186
126
  if (Builder.OptLevel > 0)
187
6
    PM.add(createObjCARCExpandPass());
188
126
}
189
190
6
static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
191
6
  if (Builder.OptLevel > 0)
192
6
    PM.add(createObjCARCOptPass());
193
6
}
194
195
static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
196
6
                                     legacy::PassManagerBase &PM) {
197
6
  PM.add(createAddDiscriminatorsPass());
198
6
}
199
200
static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
201
1
                                  legacy::PassManagerBase &PM) {
202
1
  PM.add(createBoundsCheckingLegacyPass());
203
1
}
204
205
static SanitizerCoverageOptions
206
6
getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
207
6
  SanitizerCoverageOptions Opts;
208
6
  Opts.CoverageType =
209
6
      static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
210
6
  Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
211
6
  Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
212
6
  Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
213
6
  Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
214
6
  Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
215
6
  Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
216
6
  Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
217
6
  Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
218
6
  Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
219
6
  Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
220
6
  Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
221
6
  Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
222
6
  return Opts;
223
6
}
224
225
static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
226
0
                                     legacy::PassManagerBase &PM) {
227
0
  const PassManagerBuilderWrapper &BuilderWrapper =
228
0
      static_cast<const PassManagerBuilderWrapper &>(Builder);
229
0
  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
230
0
  auto Opts = getSancovOptsFromCGOpts(CGOpts);
231
0
  PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts));
232
0
}
233
234
// Check if ASan should use GC-friendly instrumentation for globals.
235
// First of all, there is no point if -fdata-sections is off (expect for MachO,
236
// where this is not a factor). Also, on ELF this feature requires an assembler
237
// extension that only works with -integrated-as at the moment.
238
72
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
239
72
  if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
240
49
    return false;
241
23
  switch (T.getObjectFormat()) {
242
15
  case Triple::MachO:
243
15
  case Triple::COFF:
244
15
    return true;
245
15
  case Triple::ELF:
246
8
    return CGOpts.DataSections && 
!CGOpts.DisableIntegratedAS4
;
247
15
  case Triple::XCOFF:
248
0
    llvm::report_fatal_error("ASan not implemented for XCOFF.");
249
15
  case Triple::Wasm:
250
0
  case Triple::UnknownObjectFormat:
251
0
    break;
252
0
  }
253
0
  return false;
254
0
}
255
256
static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
257
65
                                      legacy::PassManagerBase &PM) {
258
65
  const PassManagerBuilderWrapper &BuilderWrapper =
259
65
      static_cast<const PassManagerBuilderWrapper&>(Builder);
260
65
  const Triple &T = BuilderWrapper.getTargetTriple();
261
65
  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
262
65
  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
263
65
  bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
264
65
  bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
265
65
  bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
266
65
  PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
267
65
                                            UseAfterScope));
268
65
  PM.add(createModuleAddressSanitizerLegacyPassPass(
269
65
      /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
270
65
}
271
272
static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
273
6
                                            legacy::PassManagerBase &PM) {
274
6
  PM.add(createAddressSanitizerFunctionPass(
275
6
      /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
276
6
  PM.add(createModuleAddressSanitizerLegacyPassPass(
277
6
      /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
278
6
      /*UseOdrIndicator*/ false));
279
6
}
280
281
static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
282
7
                                            legacy::PassManagerBase &PM) {
283
7
  const PassManagerBuilderWrapper &BuilderWrapper =
284
7
      static_cast<const PassManagerBuilderWrapper &>(Builder);
285
7
  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
286
7
  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
287
7
  PM.add(
288
7
      createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
289
7
}
290
291
static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
292
5
                                            legacy::PassManagerBase &PM) {
293
5
  PM.add(createHWAddressSanitizerLegacyPassPass(
294
5
      /*CompileKernel*/ true, /*Recover*/ true));
295
5
}
296
297
static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
298
                                             legacy::PassManagerBase &PM,
299
23
                                             bool CompileKernel) {
300
23
  const PassManagerBuilderWrapper &BuilderWrapper =
301
23
      static_cast<const PassManagerBuilderWrapper&>(Builder);
302
23
  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
303
23
  int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
304
23
  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
305
23
  PM.add(createMemorySanitizerLegacyPassPass(
306
23
      MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
307
23
308
23
  // MemorySanitizer inserts complex instrumentation that mostly follows
309
23
  // the logic of the original code, but operates on "shadow" values.
310
23
  // It can benefit from re-running some general purpose optimization passes.
311
23
  if (Builder.OptLevel > 0) {
312
11
    PM.add(createEarlyCSEPass());
313
11
    PM.add(createReassociatePass());
314
11
    PM.add(createLICMPass());
315
11
    PM.add(createGVNPass());
316
11
    PM.add(createInstructionCombiningPass());
317
11
    PM.add(createDeadStoreEliminationPass());
318
11
  }
319
23
}
320
321
static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
322
18
                                   legacy::PassManagerBase &PM) {
323
18
  addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
324
18
}
325
326
static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
327
5
                                         legacy::PassManagerBase &PM) {
328
5
  addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
329
5
}
330
331
static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
332
32
                                   legacy::PassManagerBase &PM) {
333
32
  PM.add(createThreadSanitizerLegacyPassPass());
334
32
}
335
336
static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
337
0
                                     legacy::PassManagerBase &PM) {
338
0
  const PassManagerBuilderWrapper &BuilderWrapper =
339
0
      static_cast<const PassManagerBuilderWrapper&>(Builder);
340
0
  const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
341
0
  PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
342
0
}
343
344
static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
345
17.6k
                                         const CodeGenOptions &CodeGenOpts) {
346
17.6k
  TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
347
17.6k
348
17.6k
  switch (CodeGenOpts.getVecLib()) {
349
0
  case CodeGenOptions::Accelerate:
350
0
    TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
351
0
    break;
352
0
  case CodeGenOptions::MASSV:
353
0
    TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
354
0
    break;    
355
0
  case CodeGenOptions::SVML:
356
0
    TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
357
0
    break;
358
17.6k
  default:
359
17.6k
    break;
360
17.6k
  }
361
17.6k
  return TLII;
362
17.6k
}
363
364
static void addSymbolRewriterPass(const CodeGenOptions &Opts,
365
0
                                  legacy::PassManager *MPM) {
366
0
  llvm::SymbolRewriter::RewriteDescriptorList DL;
367
0
368
0
  llvm::SymbolRewriter::RewriteMapParser MapParser;
369
0
  for (const auto &MapFile : Opts.RewriteMapFiles)
370
0
    MapParser.parse(MapFile, &DL);
371
0
372
0
  MPM->add(createRewriteSymbolsPass(DL));
373
0
}
374
375
14.2k
static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
376
14.2k
  switch (CodeGenOpts.OptimizationLevel) {
377
0
  default:
378
0
    llvm_unreachable("Invalid optimization level!");
379
13.2k
  case 0:
380
13.2k
    return CodeGenOpt::None;
381
302
  case 1:
382
302
    return CodeGenOpt::Less;
383
503
  case 2:
384
503
    return CodeGenOpt::Default; // O2/Os/Oz
385
172
  case 3:
386
172
    return CodeGenOpt::Aggressive;
387
14.2k
  }
388
14.2k
}
389
390
static Optional<llvm::CodeModel::Model>
391
14.2k
getCodeModel(const CodeGenOptions &CodeGenOpts) {
392
14.2k
  unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
393
14.2k
                           .Case("tiny", llvm::CodeModel::Tiny)
394
14.2k
                           .Case("small", llvm::CodeModel::Small)
395
14.2k
                           .Case("kernel", llvm::CodeModel::Kernel)
396
14.2k
                           .Case("medium", llvm::CodeModel::Medium)
397
14.2k
                           .Case("large", llvm::CodeModel::Large)
398
14.2k
                           .Case("default", ~1u)
399
14.2k
                           .Default(~0u);
400
14.2k
  assert(CodeModel != ~0u && "invalid code model!");
401
14.2k
  if (CodeModel == ~1u)
402
14.2k
    return None;
403
5
  return static_cast<llvm::CodeModel::Model>(CodeModel);
404
5
}
405
406
3.69k
static CodeGenFileType getCodeGenFileType(BackendAction Action) {
407
3.69k
  if (Action == Backend_EmitObj)
408
3.45k
    return CGFT_ObjectFile;
409
240
  else if (Action == Backend_EmitMCNull)
410
3
    return CGFT_Null;
411
237
  else {
412
237
    assert(Action == Backend_EmitAssembly && "Invalid action!");
413
237
    return CGFT_AssemblyFile;
414
237
  }
415
3.69k
}
416
417
static void initTargetOptions(llvm::TargetOptions &Options,
418
                              const CodeGenOptions &CodeGenOpts,
419
                              const clang::TargetOptions &TargetOpts,
420
                              const LangOptions &LangOpts,
421
14.2k
                              const HeaderSearchOptions &HSOpts) {
422
14.2k
  Options.ThreadModel =
423
14.2k
      llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
424
14.2k
          .Case("posix", llvm::ThreadModel::POSIX)
425
14.2k
          .Case("single", llvm::ThreadModel::Single);
426
14.2k
427
14.2k
  // Set float ABI type.
428
14.2k
  assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
429
14.2k
          CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
430
14.2k
         "Invalid Floating Point ABI!");
431
14.2k
  Options.FloatABIType =
432
14.2k
      llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
433
14.2k
          .Case("soft", llvm::FloatABI::Soft)
434
14.2k
          .Case("softfp", llvm::FloatABI::Soft)
435
14.2k
          .Case("hard", llvm::FloatABI::Hard)
436
14.2k
          .Default(llvm::FloatABI::Default);
437
14.2k
438
14.2k
  // Set FP fusion mode.
439
14.2k
  switch (LangOpts.getDefaultFPContractMode()) {
440
13.9k
  case LangOptions::FPC_Off:
441
13.9k
    // Preserve any contraction performed by the front-end.  (Strict performs
442
13.9k
    // splitting of the muladd intrinsic in the backend.)
443
13.9k
    Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
444
13.9k
    break;
445
163
  case LangOptions::FPC_On:
446
163
    Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
447
163
    break;
448
121
  case LangOptions::FPC_Fast:
449
121
    Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
450
121
    break;
451
14.2k
  }
452
14.2k
453
14.2k
  Options.UseInitArray = CodeGenOpts.UseInitArray;
454
14.2k
  Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
455
14.2k
  Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
456
14.2k
  Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
457
14.2k
458
14.2k
  // Set EABI version.
459
14.2k
  Options.EABIVersion = TargetOpts.EABIVersion;
460
14.2k
461
14.2k
  if (LangOpts.SjLjExceptions)
462
27
    Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
463
14.2k
  if (LangOpts.SEHExceptions)
464
22
    Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
465
14.2k
  if (LangOpts.DWARFExceptions)
466
21
    Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
467
14.2k
  if (LangOpts.WasmExceptions)
468
3
    Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
469
14.2k
470
14.2k
  Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
471
14.2k
  Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
472
14.2k
  Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
473
14.2k
  Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
474
14.2k
  Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
475
14.2k
  Options.FunctionSections = CodeGenOpts.FunctionSections;
476
14.2k
  Options.DataSections = CodeGenOpts.DataSections;
477
14.2k
  Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
478
14.2k
  Options.TLSSize = CodeGenOpts.TLSSize;
479
14.2k
  Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
480
14.2k
  Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
481
14.2k
  Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
482
14.2k
  Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
483
14.2k
  Options.EmitAddrsig = CodeGenOpts.Addrsig;
484
14.2k
  Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
485
14.2k
  Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
486
14.2k
487
14.2k
  Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
488
14.2k
  Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
489
14.2k
  Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
490
14.2k
  Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
491
14.2k
  Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
492
14.2k
  Options.MCOptions.MCIncrementalLinkerCompatible =
493
14.2k
      CodeGenOpts.IncrementalLinkerCompatible;
494
14.2k
  Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
495
14.2k
  Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
496
14.2k
  Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
497
14.2k
  Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
498
14.2k
  Options.MCOptions.ABIName = TargetOpts.ABI;
499
14.2k
  for (const auto &Entry : HSOpts.UserEntries)
500
34.9k
    if (!Entry.IsFramework &&
501
34.9k
        
(34.8k
Entry.Group == frontend::IncludeDirGroup::Quoted34.8k
||
502
34.8k
         
Entry.Group == frontend::IncludeDirGroup::Angled34.8k
||
503
34.8k
         
Entry.Group == frontend::IncludeDirGroup::System25.3k
))
504
31.0k
      Options.MCOptions.IASSearchPaths.push_back(
505
31.0k
          Entry.IgnoreSysRoot ? Entry.Path : 
HSOpts.Sysroot + Entry.Path0
);
506
14.2k
}
507
13.9k
static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
508
13.9k
  if (CodeGenOpts.DisableGCov)
509
1
    return None;
510
13.9k
  if (!CodeGenOpts.EmitGcovArcs && 
!CodeGenOpts.EmitGcovNotes13.9k
)
511
13.9k
    return None;
512
13
  // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
513
13
  // LLVM's -default-gcov-version flag is set to something invalid.
514
13
  GCOVOptions Options;
515
13
  Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
516
13
  Options.EmitData = CodeGenOpts.EmitGcovArcs;
517
13
  llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
518
13
  Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
519
13
  Options.NoRedZone = CodeGenOpts.DisableRedZone;
520
13
  Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
521
13
  Options.Filter = CodeGenOpts.ProfileFilterFiles;
522
13
  Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
523
13
  Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
524
13
  return Options;
525
13
}
526
527
static Optional<InstrProfOptions>
528
getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
529
13.9k
                    const LangOptions &LangOpts) {
530
13.9k
  if (!CodeGenOpts.hasProfileClangInstr())
531
13.8k
    return None;
532
93
  InstrProfOptions Options;
533
93
  Options.NoRedZone = CodeGenOpts.DisableRedZone;
534
93
  Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
535
93
536
93
  // TODO: Surface the option to emit atomic profile counter increments at
537
93
  // the driver level.
538
93
  Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
539
93
  return Options;
540
93
}
541
542
void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
543
14.1k
                                      legacy::FunctionPassManager &FPM) {
544
14.1k
  // Handle disabling of all LLVM passes, where we want to preserve the
545
14.1k
  // internal module before any optimization.
546
14.1k
  if (CodeGenOpts.DisableLLVMPasses)
547
306
    return;
548
13.8k
549
13.8k
  // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
550
13.8k
  // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
551
13.8k
  // are inserted before PMBuilder ones - they'd get the default-constructed
552
13.8k
  // TLI with an unknown target otherwise.
553
13.8k
  Triple TargetTriple(TheModule->getTargetTriple());
554
13.8k
  std::unique_ptr<TargetLibraryInfoImpl> TLII(
555
13.8k
      createTLII(TargetTriple, CodeGenOpts));
556
13.8k
557
13.8k
  // If we reached here with a non-empty index file name, then the index file
558
13.8k
  // was empty and we are not performing ThinLTO backend compilation (used in
559
13.8k
  // testing in a distributed build environment). Drop any the type test
560
13.8k
  // assume sequences inserted for whole program vtables so that codegen doesn't
561
13.8k
  // complain.
562
13.8k
  if (!CodeGenOpts.ThinLTOIndexFile.empty())
563
3
    MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
564
3
                                     /*ImportSummary=*/nullptr,
565
3
                                     /*DropTypeTests=*/true));
566
13.8k
567
13.8k
  PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
568
13.8k
569
13.8k
  // At O0 and O1 we only run the always inliner which is more efficient. At
570
13.8k
  // higher optimization levels we run the normal inliner.
571
13.8k
  if (CodeGenOpts.OptimizationLevel <= 1) {
572
13.2k
    bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
573
13.2k
                                     
!CodeGenOpts.DisableLifetimeMarkers180
);
574
13.2k
    PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
575
13.2k
  } else {
576
537
    // We do not want to inline hot callsites for SamplePGO module-summary build
577
537
    // because profile annotation will happen again in ThinLTO backend, and we
578
537
    // want the IR of the hot path to match the profile.
579
537
    PMBuilder.Inliner = createFunctionInliningPass(
580
537
        CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
581
537
        (!CodeGenOpts.SampleProfileFile.empty() &&
582
537
         
CodeGenOpts.PrepareForThinLTO4
));
583
537
  }
584
13.8k
585
13.8k
  PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
586
13.8k
  PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
587
13.8k
  PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
588
13.8k
  PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
589
13.8k
590
13.8k
  PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
591
13.8k
  // Loop interleaving in the loop vectorizer has historically been set to be
592
13.8k
  // enabled when loop unrolling is enabled.
593
13.8k
  PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
594
13.8k
  PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
595
13.8k
  PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
596
13.8k
  PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
597
13.8k
  PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
598
13.8k
599
13.8k
  MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
600
13.8k
601
13.8k
  if (TM)
602
13.7k
    TM->adjustPassManager(PMBuilder);
603
13.8k
604
13.8k
  if (CodeGenOpts.DebugInfoForProfiling ||
605
13.8k
      !CodeGenOpts.SampleProfileFile.empty())
606
6
    PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
607
6
                           addAddDiscriminatorsPass);
608
13.8k
609
13.8k
  // In ObjC ARC mode, add the main ARC optimization passes.
610
13.8k
  if (LangOpts.ObjCAutoRefCount) {
611
126
    PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
612
126
                           addObjCARCExpandPass);
613
126
    PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
614
126
                           addObjCARCAPElimPass);
615
126
    PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
616
126
                           addObjCARCOptPass);
617
126
  }
618
13.8k
619
13.8k
  if (LangOpts.Coroutines)
620
34
    addCoroutinePassesToExtensionPoints(PMBuilder);
621
13.8k
622
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
623
1
    PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
624
1
                           addBoundsCheckingPass);
625
1
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
626
1
                           addBoundsCheckingPass);
627
1
  }
628
13.8k
629
13.8k
  if (CodeGenOpts.SanitizeCoverageType ||
630
13.8k
      CodeGenOpts.SanitizeCoverageIndirectCalls ||
631
13.8k
      CodeGenOpts.SanitizeCoverageTraceCmp) {
632
0
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
633
0
                           addSanitizerCoveragePass);
634
0
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
635
0
                           addSanitizerCoveragePass);
636
0
  }
637
13.8k
638
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
639
65
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
640
65
                           addAddressSanitizerPasses);
641
65
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
642
65
                           addAddressSanitizerPasses);
643
65
  }
644
13.8k
645
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
646
6
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
647
6
                           addKernelAddressSanitizerPasses);
648
6
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
649
6
                           addKernelAddressSanitizerPasses);
650
6
  }
651
13.8k
652
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
653
7
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
654
7
                           addHWAddressSanitizerPasses);
655
7
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
656
7
                           addHWAddressSanitizerPasses);
657
7
  }
658
13.8k
659
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
660
5
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
661
5
                           addKernelHWAddressSanitizerPasses);
662
5
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
663
5
                           addKernelHWAddressSanitizerPasses);
664
5
  }
665
13.8k
666
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
667
18
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
668
18
                           addMemorySanitizerPass);
669
18
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
670
18
                           addMemorySanitizerPass);
671
18
  }
672
13.8k
673
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
674
5
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
675
5
                           addKernelMemorySanitizerPass);
676
5
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
677
5
                           addKernelMemorySanitizerPass);
678
5
  }
679
13.8k
680
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
681
32
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
682
32
                           addThreadSanitizerPass);
683
32
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
684
32
                           addThreadSanitizerPass);
685
32
  }
686
13.8k
687
13.8k
  if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
688
0
    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
689
0
                           addDataFlowSanitizerPass);
690
0
    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
691
0
                           addDataFlowSanitizerPass);
692
0
  }
693
13.8k
694
13.8k
  // Set up the per-function pass manager.
695
13.8k
  FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
696
13.8k
  if (CodeGenOpts.VerifyModule)
697
13.8k
    FPM.add(createVerifierPass());
698
13.8k
699
13.8k
  // Set up the per-module pass manager.
700
13.8k
  if (!CodeGenOpts.RewriteMapFiles.empty())
701
0
    addSymbolRewriterPass(CodeGenOpts, &MPM);
702
13.8k
703
13.8k
  if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
704
11
    MPM.add(createGCOVProfilerPass(*Options));
705
11
    if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
706
10
      MPM.add(createStripSymbolsPass(true));
707
11
  }
708
13.8k
709
13.8k
  if (Optional<InstrProfOptions> Options =
710
90
          getInstrProfOptions(CodeGenOpts, LangOpts))
711
90
    MPM.add(createInstrProfilingLegacyPass(*Options, false));
712
13.8k
713
13.8k
  bool hasIRInstr = false;
714
13.8k
  if (CodeGenOpts.hasProfileIRInstr()) {
715
3
    PMBuilder.EnablePGOInstrGen = true;
716
3
    hasIRInstr = true;
717
3
  }
718
13.8k
  if (CodeGenOpts.hasProfileCSIRInstr()) {
719
5
    assert(!CodeGenOpts.hasProfileCSIRUse() &&
720
5
           "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
721
5
           "same time");
722
5
    assert(!hasIRInstr &&
723
5
           "Cannot have both ProfileGen pass and CSProfileGen pass at the "
724
5
           "same time");
725
5
    PMBuilder.EnablePGOCSInstrGen = true;
726
5
    hasIRInstr = true;
727
5
  }
728
13.8k
  if (hasIRInstr) {
729
8
    if (!CodeGenOpts.InstrProfileOutput.empty())
730
4
      PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
731
4
    else
732
4
      PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
733
8
  }
734
13.8k
  if (CodeGenOpts.hasProfileIRUse()) {
735
11
    PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
736
11
    PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
737
11
  }
738
13.8k
739
13.8k
  if (!CodeGenOpts.SampleProfileFile.empty())
740
6
    PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
741
13.8k
742
13.8k
  PMBuilder.populateFunctionPassManager(FPM);
743
13.8k
  PMBuilder.populateModulePassManager(MPM);
744
13.8k
}
745
746
14.3k
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
747
14.3k
  SmallVector<const char *, 16> BackendArgs;
748
14.3k
  BackendArgs.push_back("clang"); // Fake program name.
749
14.3k
  if (!CodeGenOpts.DebugPass.empty()) {
750
0
    BackendArgs.push_back("-debug-pass");
751
0
    BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
752
0
  }
753
14.3k
  if (!CodeGenOpts.LimitFloatPrecision.empty()) {
754
0
    BackendArgs.push_back("-limit-float-precision");
755
0
    BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
756
0
  }
757
14.3k
  BackendArgs.push_back(nullptr);
758
14.3k
  llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
759
14.3k
                                    BackendArgs.data());
760
14.3k
}
761
762
14.2k
void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
763
14.2k
  // Create the TargetMachine for generating code.
764
14.2k
  std::string Error;
765
14.2k
  std::string Triple = TheModule->getTargetTriple();
766
14.2k
  const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
767
14.2k
  if (!TheTarget) {
768
118
    if (MustCreateTM)
769
1
      Diags.Report(diag::err_fe_unable_to_create_target) << Error;
770
118
    return;
771
118
  }
772
14.1k
773
14.1k
  Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
774
14.1k
  std::string FeaturesStr =
775
14.1k
      llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
776
14.1k
  llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
777
14.1k
  CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
778
14.1k
779
14.1k
  llvm::TargetOptions Options;
780
14.1k
  initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
781
14.1k
  TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
782
14.1k
                                          Options, RM, CM, OptLevel));
783
14.1k
}
784
785
bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
786
                                       BackendAction Action,
787
                                       raw_pwrite_stream &OS,
788
3.66k
                                       raw_pwrite_stream *DwoOS) {
789
3.66k
  // Add LibraryInfo.
790
3.66k
  llvm::Triple TargetTriple(TheModule->getTargetTriple());
791
3.66k
  std::unique_ptr<TargetLibraryInfoImpl> TLII(
792
3.66k
      createTLII(TargetTriple, CodeGenOpts));
793
3.66k
  CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
794
3.66k
795
3.66k
  // Normal mode, emit a .s or .o file by running the code generator. Note,
796
3.66k
  // this also adds codegenerator level optimization passes.
797
3.66k
  CodeGenFileType CGFT = getCodeGenFileType(Action);
798
3.66k
799
3.66k
  // Add ObjC ARC final-cleanup optimizations. This is done as part of the
800
3.66k
  // "codegen" passes so that it isn't run multiple times when there is
801
3.66k
  // inlining happening.
802
3.66k
  if (CodeGenOpts.OptimizationLevel > 0)
803
138
    CodeGenPasses.add(createObjCARCContractPass());
804
3.66k
805
3.66k
  if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
806
3.66k
                              /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
807
0
    Diags.Report(diag::err_fe_unable_to_interface_with_target);
808
0
    return false;
809
0
  }
810
3.66k
811
3.66k
  return true;
812
3.66k
}
813
814
void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
815
14.1k
                                      std::unique_ptr<raw_pwrite_stream> OS) {
816
14.1k
  TimeRegion Region(FrontendTimesIsEnabled ? 
&CodeGenerationTime10
:
nullptr14.1k
);
817
14.1k
818
14.1k
  setCommandLineOpts(CodeGenOpts);
819
14.1k
820
14.1k
  bool UsesCodeGen = (Action != Backend_EmitNothing &&
821
14.1k
                      
Action != Backend_EmitBC13.9k
&&
822
14.1k
                      
Action != Backend_EmitLL13.5k
);
823
14.1k
  CreateTargetMachine(UsesCodeGen);
824
14.1k
825
14.1k
  if (UsesCodeGen && 
!TM3.65k
)
826
1
    return;
827
14.1k
  if (TM)
828
14.0k
    TheModule->setDataLayout(TM->createDataLayout());
829
14.1k
830
14.1k
  legacy::PassManager PerModulePasses;
831
14.1k
  PerModulePasses.add(
832
14.1k
      createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
833
14.1k
834
14.1k
  legacy::FunctionPassManager PerFunctionPasses(TheModule);
835
14.1k
  PerFunctionPasses.add(
836
14.1k
      createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
837
14.1k
838
14.1k
  CreatePasses(PerModulePasses, PerFunctionPasses);
839
14.1k
840
14.1k
  legacy::PassManager CodeGenPasses;
841
14.1k
  CodeGenPasses.add(
842
14.1k
      createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
843
14.1k
844
14.1k
  std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
845
14.1k
846
14.1k
  switch (Action) {
847
173
  case Backend_EmitNothing:
848
173
    break;
849
0
850
390
  case Backend_EmitBC:
851
390
    if (CodeGenOpts.PrepareForThinLTO && 
!CodeGenOpts.DisableLLVMPasses20
) {
852
19
      if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
853
1
        ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
854
1
        if (!ThinLinkOS)
855
0
          return;
856
19
      }
857
19
      TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
858
19
                               CodeGenOpts.EnableSplitLTOUnit);
859
19
      PerModulePasses.add(createWriteThinLTOBitcodePass(
860
19
          *OS, ThinLinkOS ? 
&ThinLinkOS->os()1
:
nullptr18
));
861
371
    } else {
862
371
      // Emit a module summary by default for Regular LTO except for ld64
863
371
      // targets
864
371
      bool EmitLTOSummary =
865
371
          (CodeGenOpts.PrepareForLTO &&
866
371
           
!CodeGenOpts.DisableLLVMPasses9
&&
867
371
           llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
868
6
               llvm::Triple::Apple);
869
371
      if (EmitLTOSummary) {
870
3
        if (!TheModule->getModuleFlag("ThinLTO"))
871
3
          TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
872
3
        TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
873
3
                                 uint32_t(1));
874
3
      }
875
371
876
371
      PerModulePasses.add(createBitcodeWriterPass(
877
371
          *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
878
371
    }
879
390
    break;
880
390
881
9.91k
  case Backend_EmitLL:
882
9.91k
    PerModulePasses.add(
883
9.91k
        createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
884
9.91k
    break;
885
390
886
3.65k
  default:
887
3.65k
    if (!CodeGenOpts.SplitDwarfOutput.empty()) {
888
6
      DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
889
6
      if (!DwoOS)
890
0
        return;
891
3.65k
    }
892
3.65k
    if (!AddEmitPasses(CodeGenPasses, Action, *OS,
893
3.65k
                       DwoOS ? 
&DwoOS->os()6
:
nullptr3.64k
))
894
0
      return;
895
14.1k
  }
896
14.1k
897
14.1k
  // Before executing passes, print the final values of the LLVM options.
898
14.1k
  cl::PrintOptionValues();
899
14.1k
900
14.1k
  // Run passes. For now we do all passes at once, but eventually we
901
14.1k
  // would like to have the option of streaming code generation.
902
14.1k
903
14.1k
  {
904
14.1k
    PrettyStackTraceString CrashInfo("Per-function optimization");
905
14.1k
    llvm::TimeTraceScope TimeScope("PerFunctionPasses");
906
14.1k
907
14.1k
    PerFunctionPasses.doInitialization();
908
14.1k
    for (Function &F : *TheModule)
909
280k
      if (!F.isDeclaration())
910
215k
        PerFunctionPasses.run(F);
911
14.1k
    PerFunctionPasses.doFinalization();
912
14.1k
  }
913
14.1k
914
14.1k
  {
915
14.1k
    PrettyStackTraceString CrashInfo("Per-module optimization passes");
916
14.1k
    llvm::TimeTraceScope TimeScope("PerModulePasses");
917
14.1k
    PerModulePasses.run(*TheModule);
918
14.1k
  }
919
14.1k
920
14.1k
  {
921
14.1k
    PrettyStackTraceString CrashInfo("Code generation");
922
14.1k
    llvm::TimeTraceScope TimeScope("CodeGenPasses");
923
14.1k
    CodeGenPasses.run(*TheModule);
924
14.1k
  }
925
14.1k
926
14.1k
  if (ThinLinkOS)
927
1
    ThinLinkOS->keep();
928
14.1k
  if (DwoOS)
929
6
    DwoOS->keep();
930
14.1k
}
931
932
93
static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
933
93
  switch (Opts.OptimizationLevel) {
934
0
  default:
935
0
    llvm_unreachable("Invalid optimization level!");
936
0
937
37
  case 1:
938
37
    return PassBuilder::OptimizationLevel::O1;
939
0
940
44
  case 2:
941
44
    switch (Opts.OptimizeSize) {
942
0
    default:
943
0
      llvm_unreachable("Invalid optimization level for size!");
944
0
945
39
    case 0:
946
39
      return PassBuilder::OptimizationLevel::O2;
947
0
948
3
    case 1:
949
3
      return PassBuilder::OptimizationLevel::Os;
950
0
951
2
    case 2:
952
2
      return PassBuilder::OptimizationLevel::Oz;
953
0
    }
954
0
955
12
  case 3:
956
12
    return PassBuilder::OptimizationLevel::O3;
957
93
  }
958
93
}
959
960
static void addSanitizersAtO0(ModulePassManager &MPM,
961
                              const Triple &TargetTriple,
962
                              const LangOptions &LangOpts,
963
54
                              const CodeGenOptions &CodeGenOpts) {
964
54
  auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
965
3
    MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
966
3
    bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
967
3
    MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
968
3
        CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
969
3
    bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
970
3
    MPM.addPass(
971
3
        ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
972
3
                                   CodeGenOpts.SanitizeAddressUseOdrIndicator));
973
3
  };
974
54
975
54
  if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
976
3
    ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
977
3
  }
978
54
979
54
  if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
980
0
    ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
981
0
  }
982
54
983
54
  if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
984
1
    MPM.addPass(MemorySanitizerPass({}));
985
1
    MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
986
1
  }
987
54
988
54
  if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
989
0
    MPM.addPass(createModuleToFunctionPassAdaptor(
990
0
        MemorySanitizerPass({0, false, /*Kernel=*/true})));
991
0
  }
992
54
993
54
  if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
994
2
    MPM.addPass(ThreadSanitizerPass());
995
2
    MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
996
2
  }
997
54
}
998
999
/// A clean version of `EmitAssembly` that uses the new pass manager.
1000
///
1001
/// Not all features are currently supported in this system, but where
1002
/// necessary it falls back to the legacy pass manager to at least provide
1003
/// basic functionality.
1004
///
1005
/// This API is planned to have its functionality finished and then to replace
1006
/// `EmitAssembly` at some point in the future when the default switches.
1007
void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1008
156
    BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1009
156
  TimeRegion Region(FrontendTimesIsEnabled ? 
&CodeGenerationTime0
: nullptr);
1010
156
  setCommandLineOpts(CodeGenOpts);
1011
156
1012
156
  bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1013
156
                          
Action != Backend_EmitBC148
&&
1014
156
                          
Action != Backend_EmitLL122
);
1015
156
  CreateTargetMachine(RequiresCodeGen);
1016
156
1017
156
  if (RequiresCodeGen && 
!TM12
)
1018
0
    return;
1019
156
  if (TM)
1020
152
    TheModule->setDataLayout(TM->createDataLayout());
1021
156
1022
156
  Optional<PGOOptions> PGOOpt;
1023
156
1024
156
  if (CodeGenOpts.hasProfileIRInstr())
1025
2
    // -fprofile-generate.
1026
2
    PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1027
2
                            ? std::string(DefaultProfileGenName)
1028
2
                            : 
CodeGenOpts.InstrProfileOutput0
,
1029
2
                        "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1030
2
                        CodeGenOpts.DebugInfoForProfiling);
1031
154
  else if (CodeGenOpts.hasProfileIRUse()) {
1032
13
    // -fprofile-use.
1033
13
    auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? 
PGOOptions::CSIRUse4
1034
13
                                                    : 
PGOOptions::NoCSAction9
;
1035
13
    PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1036
13
                        CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1037
13
                        CSAction, CodeGenOpts.DebugInfoForProfiling);
1038
141
  } else if (!CodeGenOpts.SampleProfileFile.empty())
1039
6
    // -fprofile-sample-use
1040
6
    PGOOpt =
1041
6
        PGOOptions(CodeGenOpts.SampleProfileFile, "",
1042
6
                   CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1043
6
                   PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1044
135
  else if (CodeGenOpts.DebugInfoForProfiling)
1045
0
    // -fdebug-info-for-profiling
1046
0
    PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1047
0
                        PGOOptions::NoCSAction, true);
1048
156
1049
156
  // Check to see if we want to generate a CS profile.
1050
156
  if (CodeGenOpts.hasProfileCSIRInstr()) {
1051
5
    assert(!CodeGenOpts.hasProfileCSIRUse() &&
1052
5
           "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1053
5
           "the same time");
1054
5
    if (PGOOpt.hasValue()) {
1055
3
      assert(PGOOpt->Action != PGOOptions::IRInstr &&
1056
3
             PGOOpt->Action != PGOOptions::SampleUse &&
1057
3
             "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1058
3
             " pass");
1059
3
      PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1060
3
                                     ? 
std::string(DefaultProfileGenName)1
1061
3
                                     : 
CodeGenOpts.InstrProfileOutput2
;
1062
3
      PGOOpt->CSAction = PGOOptions::CSIRInstr;
1063
3
    } else
1064
2
      PGOOpt = PGOOptions("",
1065
2
                          CodeGenOpts.InstrProfileOutput.empty()
1066
2
                              ? 
std::string(DefaultProfileGenName)1
1067
2
                              : 
CodeGenOpts.InstrProfileOutput1
,
1068
2
                          "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1069
2
                          CodeGenOpts.DebugInfoForProfiling);
1070
5
  }
1071
156
1072
156
  PipelineTuningOptions PTO;
1073
156
  PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1074
156
  // For historical reasons, loop interleaving is set to mirror setting for loop
1075
156
  // unrolling.
1076
156
  PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1077
156
  PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1078
156
  PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1079
156
1080
156
  PassInstrumentationCallbacks PIC;
1081
156
  StandardInstrumentations SI;
1082
156
  SI.registerCallbacks(PIC);
1083
156
  PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1084
156
1085
156
  // Attempt to load pass plugins and register their callbacks with PB.
1086
156
  for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1087
0
    auto PassPlugin = PassPlugin::Load(PluginFN);
1088
0
    if (PassPlugin) {
1089
0
      PassPlugin->registerPassBuilderCallbacks(PB);
1090
0
    } else {
1091
0
      Diags.Report(diag::err_fe_unable_to_load_plugin)
1092
0
          << PluginFN << toString(PassPlugin.takeError());
1093
0
    }
1094
0
  }
1095
156
#define HANDLE_EXTENSION(Ext)                                                  \
1096
156
  get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1097
156
#include "llvm/Support/Extension.def"
1098
156
1099
156
  LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1100
156
  FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1101
156
  CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1102
156
  ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1103
156
1104
156
  // Register the AA manager first so that our version is the one used.
1105
156
  FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1106
156
1107
156
  // Register the target library analysis directly and give it a customized
1108
156
  // preset TLI.
1109
156
  Triple TargetTriple(TheModule->getTargetTriple());
1110
156
  std::unique_ptr<TargetLibraryInfoImpl> TLII(
1111
156
      createTLII(TargetTriple, CodeGenOpts));
1112
156
  FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1113
156
1114
156
  // Register all the basic analyses with the managers.
1115
156
  PB.registerModuleAnalyses(MAM);
1116
156
  PB.registerCGSCCAnalyses(CGAM);
1117
156
  PB.registerFunctionAnalyses(FAM);
1118
156
  PB.registerLoopAnalyses(LAM);
1119
156
  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1120
156
1121
156
  ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1122
156
1123
156
  if (!CodeGenOpts.DisableLLVMPasses) {
1124
147
    bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1125
147
    bool IsLTO = CodeGenOpts.PrepareForLTO;
1126
147
1127
147
    if (CodeGenOpts.OptimizationLevel == 0) {
1128
54
      // If we reached here with a non-empty index file name, then the index
1129
54
      // file was empty and we are not performing ThinLTO backend compilation
1130
54
      // (used in testing in a distributed build environment). Drop any the type
1131
54
      // test assume sequences inserted for whole program vtables so that
1132
54
      // codegen doesn't complain.
1133
54
      if (!CodeGenOpts.ThinLTOIndexFile.empty())
1134
1
        MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1135
1
                                       /*ImportSummary=*/nullptr,
1136
1
                                       /*DropTypeTests=*/true));
1137
54
      if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1138
1
        MPM.addPass(GCOVProfilerPass(*Options));
1139
54
      if (Optional<InstrProfOptions> Options =
1140
1
              getInstrProfOptions(CodeGenOpts, LangOpts))
1141
1
        MPM.addPass(InstrProfiling(*Options, false));
1142
54
1143
54
      // Build a minimal pipeline based on the semantics required by Clang,
1144
54
      // which is just that always inlining occurs. Further, disable generating
1145
54
      // lifetime intrinsics to avoid enabling further optimizations during
1146
54
      // code generation.
1147
54
      MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
1148
54
1149
54
      // At -O0, we can still do PGO. Add all the requested passes for
1150
54
      // instrumentation PGO, if requested.
1151
54
      if (PGOOpt && 
(3
PGOOpt->Action == PGOOptions::IRInstr3
||
1152
3
                     
PGOOpt->Action == PGOOptions::IRUse2
))
1153
3
        PB.addPGOInstrPassesForO0(
1154
3
            MPM, CodeGenOpts.DebugPassManager,
1155
3
            /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1156
3
            /* IsCS */ false, PGOOpt->ProfileFile,
1157
3
            PGOOpt->ProfileRemappingFile);
1158
54
1159
54
      // At -O0 we directly run necessary sanitizer passes.
1160
54
      if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1161
1
        MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1162
54
1163
54
      // Lastly, add semantically necessary passes for LTO.
1164
54
      if (IsLTO || 
IsThinLTO40
) {
1165
14
        MPM.addPass(CanonicalizeAliasesPass());
1166
14
        MPM.addPass(NameAnonGlobalPass());
1167
14
      }
1168
93
    } else {
1169
93
      // Map our optimization levels into one of the distinct levels used to
1170
93
      // configure the pipeline.
1171
93
      PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1172
93
1173
93
      // If we reached here with a non-empty index file name, then the index
1174
93
      // file was empty and we are not performing ThinLTO backend compilation
1175
93
      // (used in testing in a distributed build environment). Drop any the type
1176
93
      // test assume sequences inserted for whole program vtables so that
1177
93
      // codegen doesn't complain.
1178
93
      if (!CodeGenOpts.ThinLTOIndexFile.empty())
1179
1
        PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1180
1
          MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1181
1
                                         /*ImportSummary=*/nullptr,
1182
1
                                         /*DropTypeTests=*/true));
1183
1
        });
1184
93
1185
93
      PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1186
93
        MPM.addPass(createModuleToFunctionPassAdaptor(
1187
93
            EntryExitInstrumenterPass(/*PostInlining=*/false)));
1188
93
      });
1189
93
1190
93
      // Register callbacks to schedule sanitizer passes at the appropriate part of
1191
93
      // the pipeline.
1192
93
      // FIXME: either handle asan/the remaining sanitizers or error out
1193
93
      if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1194
0
        PB.registerScalarOptimizerLateEPCallback(
1195
0
            [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1196
0
              FPM.addPass(BoundsCheckingPass());
1197
0
            });
1198
93
      if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1199
4
        PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1200
4
          MPM.addPass(MemorySanitizerPass({}));
1201
4
        });
1202
4
        PB.registerOptimizerLastEPCallback(
1203
4
            [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1204
4
              FPM.addPass(MemorySanitizerPass({}));
1205
4
            });
1206
4
      }
1207
93
      if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1208
4
        PB.registerPipelineStartEPCallback(
1209
4
            [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
1210
4
        PB.registerOptimizerLastEPCallback(
1211
4
            [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1212
4
              FPM.addPass(ThreadSanitizerPass());
1213
4
            });
1214
4
      }
1215
93
      if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1216
4
        PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1217
4
          MPM.addPass(
1218
4
              RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1219
4
        });
1220
4
        bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1221
4
        bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1222
4
        PB.registerOptimizerLastEPCallback(
1223
4
            [Recover, UseAfterScope](FunctionPassManager &FPM,
1224
4
                                     PassBuilder::OptimizationLevel Level) {
1225
3
              FPM.addPass(AddressSanitizerPass(
1226
3
                  /*CompileKernel=*/false, Recover, UseAfterScope));
1227
3
            });
1228
4
        bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1229
4
        bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1230
4
        PB.registerPipelineStartEPCallback(
1231
4
            [Recover, ModuleUseAfterScope,
1232
4
             UseOdrIndicator](ModulePassManager &MPM) {
1233
4
              MPM.addPass(ModuleAddressSanitizerPass(
1234
4
                  /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1235
4
                  UseOdrIndicator));
1236
4
            });
1237
4
      }
1238
93
      if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1239
1
        PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1240
1
          MPM.addPass(GCOVProfilerPass(*Options));
1241
1
        });
1242
93
      if (Optional<InstrProfOptions> Options =
1243
2
              getInstrProfOptions(CodeGenOpts, LangOpts))
1244
2
        PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1245
2
          MPM.addPass(InstrProfiling(*Options, false));
1246
2
        });
1247
93
1248
93
      if (IsThinLTO) {
1249
13
        MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1250
13
            Level, CodeGenOpts.DebugPassManager);
1251
13
        MPM.addPass(CanonicalizeAliasesPass());
1252
13
        MPM.addPass(NameAnonGlobalPass());
1253
80
      } else if (IsLTO) {
1254
13
        MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1255
13
                                                CodeGenOpts.DebugPassManager);
1256
13
        MPM.addPass(CanonicalizeAliasesPass());
1257
13
        MPM.addPass(NameAnonGlobalPass());
1258
67
      } else {
1259
67
        MPM = PB.buildPerModuleDefaultPipeline(Level,
1260
67
                                               CodeGenOpts.DebugPassManager);
1261
67
      }
1262
93
    }
1263
147
1264
147
    if (CodeGenOpts.SanitizeCoverageType ||
1265
147
        
CodeGenOpts.SanitizeCoverageIndirectCalls141
||
1266
147
        
CodeGenOpts.SanitizeCoverageTraceCmp141
) {
1267
6
      auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1268
6
      MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1269
6
    }
1270
147
1271
147
    if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1272
6
      bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1273
6
      MPM.addPass(HWAddressSanitizerPass(
1274
6
          /*CompileKernel=*/false, Recover));
1275
6
    }
1276
147
    if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1277
6
      MPM.addPass(HWAddressSanitizerPass(
1278
6
          /*CompileKernel=*/true, /*Recover=*/true));
1279
6
    }
1280
147
1281
147
    if (CodeGenOpts.OptimizationLevel == 0) {
1282
54
      addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1283
54
    }
1284
147
  }
1285
156
1286
156
  // FIXME: We still use the legacy pass manager to do code generation. We
1287
156
  // create that pass manager here and use it as needed below.
1288
156
  legacy::PassManager CodeGenPasses;
1289
156
  bool NeedCodeGen = false;
1290
156
  std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1291
156
1292
156
  // Append any output we need to the pass manager.
1293
156
  switch (Action) {
1294
8
  case Backend_EmitNothing:
1295
8
    break;
1296
0
1297
26
  case Backend_EmitBC:
1298
26
    if (CodeGenOpts.PrepareForThinLTO && 
!CodeGenOpts.DisableLLVMPasses13
) {
1299
12
      if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1300
1
        ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1301
1
        if (!ThinLinkOS)
1302
0
          return;
1303
12
      }
1304
12
      TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1305
12
                               CodeGenOpts.EnableSplitLTOUnit);
1306
12
      MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()1
1307
12
                                                           : 
nullptr11
));
1308
14
    } else {
1309
14
      // Emit a module summary by default for Regular LTO except for ld64
1310
14
      // targets
1311
14
      bool EmitLTOSummary =
1312
14
          (CodeGenOpts.PrepareForLTO &&
1313
14
           
!CodeGenOpts.DisableLLVMPasses11
&&
1314
14
           llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1315
9
               llvm::Triple::Apple);
1316
14
      if (EmitLTOSummary) {
1317
7
        if (!TheModule->getModuleFlag("ThinLTO"))
1318
7
          TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1319
7
        TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1320
7
                                 uint32_t(1));
1321
7
      }
1322
14
      MPM.addPass(
1323
14
          BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1324
14
    }
1325
26
    break;
1326
26
1327
110
  case Backend_EmitLL:
1328
110
    MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1329
110
    break;
1330
26
1331
26
  case Backend_EmitAssembly:
1332
12
  case Backend_EmitMCNull:
1333
12
  case Backend_EmitObj:
1334
12
    NeedCodeGen = true;
1335
12
    CodeGenPasses.add(
1336
12
        createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1337
12
    if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1338
1
      DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1339
1
      if (!DwoOS)
1340
0
        return;
1341
12
    }
1342
12
    if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1343
12
                       DwoOS ? 
&DwoOS->os()1
:
nullptr11
))
1344
0
      // FIXME: Should we handle this error differently?
1345
0
      return;
1346
12
    break;
1347
156
  }
1348
156
1349
156
  // Before executing passes, print the final values of the LLVM options.
1350
156
  cl::PrintOptionValues();
1351
156
1352
156
  // Now that we have all of the passes ready, run them.
1353
156
  {
1354
156
    PrettyStackTraceString CrashInfo("Optimizer");
1355
156
    MPM.run(*TheModule, MAM);
1356
156
  }
1357
156
1358
156
  // Now if needed, run the legacy PM for codegen.
1359
156
  if (NeedCodeGen) {
1360
12
    PrettyStackTraceString CrashInfo("Code generation");
1361
12
    CodeGenPasses.run(*TheModule);
1362
12
  }
1363
156
1364
156
  if (ThinLinkOS)
1365
1
    ThinLinkOS->keep();
1366
156
  if (DwoOS)
1367
1
    DwoOS->keep();
1368
156
}
1369
1370
8
Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1371
8
  Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1372
8
  if (!BMsOrErr)
1373
0
    return BMsOrErr.takeError();
1374
8
1375
8
  // The bitcode file may contain multiple modules, we want the one that is
1376
8
  // marked as being the ThinLTO module.
1377
8
  if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1378
7
    return *Bm;
1379
1
1380
1
  return make_error<StringError>("Could not find module summary",
1381
1
                                 inconvertibleErrorCode());
1382
1
}
1383
1384
57
BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1385
58
  for (BitcodeModule &BM : BMs) {
1386
58
    Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1387
58
    if (LTOInfo && LTOInfo->IsThinLTO)
1388
55
      return &BM;
1389
58
  }
1390
57
  
return nullptr2
;
1391
57
}
1392
1393
static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1394
                              const HeaderSearchOptions &HeaderOpts,
1395
                              const CodeGenOptions &CGOpts,
1396
                              const clang::TargetOptions &TOpts,
1397
                              const LangOptions &LOpts,
1398
                              std::unique_ptr<raw_pwrite_stream> OS,
1399
                              std::string SampleProfile,
1400
                              std::string ProfileRemapping,
1401
43
                              BackendAction Action) {
1402
43
  StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1403
43
      ModuleToDefinedGVSummaries;
1404
43
  CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1405
43
1406
43
  setCommandLineOpts(CGOpts);
1407
43
1408
43
  // We can simply import the values mentioned in the combined index, since
1409
43
  // we should only invoke this using the individual indexes written out
1410
43
  // via a WriteIndexesThinBackend.
1411
43
  FunctionImporter::ImportMapTy ImportList;
1412
71
  for (auto &GlobalList : *CombinedIndex) {
1413
71
    // Ignore entries for undefined references.
1414
71
    if (GlobalList.second.SummaryList.empty())
1415
0
      continue;
1416
71
1417
71
    auto GUID = GlobalList.first;
1418
72
    for (auto &Summary : GlobalList.second.SummaryList) {
1419
72
      // Skip the summaries for the importing module. These are included to
1420
72
      // e.g. record required linkage changes.
1421
72
      if (Summary->modulePath() == M->getModuleIdentifier())
1422
62
        continue;
1423
10
      // Add an entry to provoke importing by thinBackend.
1424
10
      ImportList[Summary->modulePath()].insert(GUID);
1425
10
    }
1426
71
  }
1427
43
1428
43
  std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1429
43
  MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1430
43
1431
43
  for (auto &I : ImportList) {
1432
8
    ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1433
8
        llvm::MemoryBuffer::getFile(I.first());
1434
8
    if (!MBOrErr) {
1435
0
      errs() << "Error loading imported file '" << I.first()
1436
0
             << "': " << MBOrErr.getError().message() << "\n";
1437
0
      return;
1438
0
    }
1439
8
1440
8
    Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1441
8
    if (!BMOrErr) {
1442
1
      handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1443
1
        errs() << "Error loading imported file '" << I.first()
1444
1
               << "': " << EIB.message() << '\n';
1445
1
      });
1446
1
      return;
1447
1
    }
1448
7
    ModuleMap.insert({I.first(), *BMOrErr});
1449
7
1450
7
    OwnedImports.push_back(std::move(*MBOrErr));
1451
7
  }
1452
43
  
auto AddStream = [&](size_t Task) 42
{
1453
27
    return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1454
27
  };
1455
42
  lto::Config Conf;
1456
42
  if (CGOpts.SaveTempsFilePrefix != "") {
1457
5
    if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1458
0
                                    /* UseInputModulePath */ false)) {
1459
0
      handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1460
0
        errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1461
0
               << '\n';
1462
0
      });
1463
0
    }
1464
5
  }
1465
42
  Conf.CPU = TOpts.CPU;
1466
42
  Conf.CodeModel = getCodeModel(CGOpts);
1467
42
  Conf.MAttrs = TOpts.Features;
1468
42
  Conf.RelocModel = CGOpts.RelocationModel;
1469
42
  Conf.CGOptLevel = getCGOptLevel(CGOpts);
1470
42
  Conf.OptLevel = CGOpts.OptimizationLevel;
1471
42
  initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1472
42
  Conf.SampleProfile = std::move(SampleProfile);
1473
42
  Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1474
42
  // For historical reasons, loop interleaving is set to mirror setting for loop
1475
42
  // unrolling.
1476
42
  Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1477
42
  Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1478
42
  Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1479
42
1480
42
  // Context sensitive profile.
1481
42
  if (CGOpts.hasProfileCSIRInstr()) {
1482
2
    Conf.RunCSIRInstr = true;
1483
2
    Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1484
40
  } else if (CGOpts.hasProfileCSIRUse()) {
1485
4
    Conf.RunCSIRInstr = false;
1486
4
    Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1487
4
  }
1488
42
1489
42
  Conf.ProfileRemapping = std::move(ProfileRemapping);
1490
42
  Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1491
42
  Conf.DebugPassManager = CGOpts.DebugPassManager;
1492
42
  Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1493
42
  Conf.RemarksFilename = CGOpts.OptRecordFile;
1494
42
  Conf.RemarksPasses = CGOpts.OptRecordPasses;
1495
42
  Conf.RemarksFormat = CGOpts.OptRecordFormat;
1496
42
  Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1497
42
  Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1498
42
  switch (Action) {
1499
0
  case Backend_EmitNothing:
1500
0
    Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1501
0
      return false;
1502
0
    };
1503
0
    break;
1504
14
  case Backend_EmitLL:
1505
14
    Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1506
14
      M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1507
14
      return false;
1508
14
    };
1509
14
    break;
1510
1
  case Backend_EmitBC:
1511
1
    Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1512
1
      WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1513
1
      return false;
1514
1
    };
1515
1
    break;
1516
27
  default:
1517
27
    Conf.CGFileType = getCodeGenFileType(Action);
1518
27
    break;
1519
42
  }
1520
42
  if (Error E = thinBackend(
1521
0
          Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1522
0
          ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1523
0
    handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1524
0
      errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1525
0
    });
1526
0
  }
1527
42
}
1528
1529
void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1530
                              const HeaderSearchOptions &HeaderOpts,
1531
                              const CodeGenOptions &CGOpts,
1532
                              const clang::TargetOptions &TOpts,
1533
                              const LangOptions &LOpts,
1534
                              const llvm::DataLayout &TDesc, Module *M,
1535
                              BackendAction Action,
1536
14.3k
                              std::unique_ptr<raw_pwrite_stream> OS) {
1537
14.3k
1538
14.3k
  llvm::TimeTraceScope TimeScope("Backend");
1539
14.3k
1540
14.3k
  std::unique_ptr<llvm::Module> EmptyModule;
1541
14.3k
  if (!CGOpts.ThinLTOIndexFile.empty()) {
1542
49
    // If we are performing a ThinLTO importing compile, load the function index
1543
49
    // into memory and pass it into runThinLTOBackend, which will run the
1544
49
    // function importer and invoke LTO passes.
1545
49
    Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1546
49
        llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1547
49
                                           /*IgnoreEmptyThinLTOIndexFile*/true);
1548
49
    if (!IndexOrErr) {
1549
1
      logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1550
1
                            "Error loading index file '" +
1551
1
                            CGOpts.ThinLTOIndexFile + "': ");
1552
1
      return;
1553
1
    }
1554
48
    std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1555
48
    // A null CombinedIndex means we should skip ThinLTO compilation
1556
48
    // (LLVM will optionally ignore empty index files, returning null instead
1557
48
    // of an error).
1558
48
    if (CombinedIndex) {
1559
44
      if (!CombinedIndex->skipModuleByDistributedBackend()) {
1560
43
        runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1561
43
                          LOpts, std::move(OS), CGOpts.SampleProfileFile,
1562
43
                          CGOpts.ProfileRemappingFile, Action);
1563
43
        return;
1564
43
      }
1565
1
      // Distributed indexing detected that nothing from the module is needed
1566
1
      // for the final linking. So we can skip the compilation. We sill need to
1567
1
      // output an empty object file to make sure that a linker does not fail
1568
1
      // trying to read it. Also for some features, like CFI, we must skip
1569
1
      // the compilation as CombinedIndex does not contain all required
1570
1
      // information.
1571
1
      EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1572
1
      EmptyModule->setTargetTriple(M->getTargetTriple());
1573
1
      M = EmptyModule.get();
1574
1
    }
1575
48
  }
1576
14.3k
1577
14.3k
  EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1578
14.2k
1579
14.2k
  if (CGOpts.ExperimentalNewPassManager)
1580
156
    AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1581
14.1k
  else
1582
14.1k
    AsmHelper.EmitAssembly(Action, std::move(OS));
1583
14.2k
1584
14.2k
  // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1585
14.2k
  // DataLayout.
1586
14.2k
  if (AsmHelper.TM) {
1587
14.1k
    std::string DLDesc = M->getDataLayout().getStringRepresentation();
1588
14.1k
    if (DLDesc != TDesc.getStringRepresentation()) {
1589
0
      unsigned DiagID = Diags.getCustomDiagID(
1590
0
          DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1591
0
                                    "expected target description '%1'");
1592
0
      Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1593
0
    }
1594
14.1k
  }
1595
14.2k
}
1596
1597
// With -fembed-bitcode, save a copy of the llvm IR as data in the
1598
// __LLVM,__bitcode section.
1599
void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1600
13.9k
                         llvm::MemoryBufferRef Buf) {
1601
13.9k
  if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1602
13.9k
    return;
1603
19
  llvm::EmbedBitcodeInModule(
1604
19
      *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1605
19
      CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1606
19
      &CGOpts.CmdArgs);
1607
19
}