Coverage Report

Created: 2019-07-24 05:18

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