-
-
Notifications
You must be signed in to change notification settings - Fork 266
/
Copy pathoptimizer.cpp
689 lines (614 loc) · 22.7 KB
/
optimizer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//===-- optimizer.cpp -----------------------------------------------------===//
//
// LDC – the LLVM D compiler
//
// This file is distributed under the BSD-style LDC license. See the LICENSE
// file for details.
//
// This module is compiled into both the compiler and the JIT runtime library
// (with predefined IN_JITRT).
//
//===----------------------------------------------------------------------===//
#ifdef IN_JITRT
#include "runtime/jit-rt/cpp-so/optimizer.h"
#include "runtime/jit-rt/cpp-so/valueparser.h"
#include "runtime/jit-rt/cpp-so/utils.h"
#endif
#include "gen/optimizer.h"
#ifndef IN_JITRT
#include "dmd/errors.h"
#include "gen/logger.h"
#endif
#include "gen/passes/GarbageCollect2Stack.h"
#include "gen/passes/StripExternals.h"
#include "gen/passes/SimplifyDRuntimeCalls.h"
#include "gen/passes/Passes.h"
#ifndef IN_JITRT
#include "driver/cl_options.h"
#include "driver/cl_options_instrumentation.h"
#include "driver/cl_options_sanitizers.h"
#include "driver/plugins.h"
#include "driver/targetmachine.h"
#endif
#if LDC_LLVM_VER < 1700
#include "llvm/ADT/Triple.h"
#else
#include "llvm/TargetParser/Triple.h"
#endif
#include "llvm/Analysis/InlineCost.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetMachine.h"
#if LDC_LLVM_VER >= 2000
#include "llvm/Transforms/Utils/Instrumentation.h"
#else
#include "llvm/Transforms/Instrumentation.h"
#endif
#include "llvm/Transforms/IPO.h"
#if LDC_LLVM_VER < 1700
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#endif
#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Passes/StandardInstrumentations.h"
#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
#include "llvm/Transforms/IPO/GlobalDCE.h"
#include "llvm/Transforms/Scalar/EarlyCSE.h"
#include "llvm/Transforms/Scalar/LICM.h"
#include "llvm/Transforms/Scalar/Reassociate.h"
#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
using namespace llvm;
static cl::opt<signed char> optimizeLevel(
cl::desc("Setting the optimization level:"), cl::ZeroOrMore,
cl::values(
clEnumValN(3, "O", "Equivalent to -O3"),
clEnumValN(0, "O0", "No optimizations (default)"),
clEnumValN(1, "O1", "Simple optimizations"),
clEnumValN(2, "O2", "Good optimizations"),
clEnumValN(3, "O3", "Aggressive optimizations"),
clEnumValN(4, "O4", "Equivalent to -O3"), // Not implemented yet.
clEnumValN(5, "O5", "Equivalent to -O3"), // Not implemented yet.
clEnumValN(-1, "Os", "Like -O2 with extra optimizations for size"),
clEnumValN(-2, "Oz", "Like -Os but reduces code size further")),
cl::init(0));
static cl::opt<bool> noVerify("disable-verify", cl::ZeroOrMore, cl::Hidden,
cl::desc("Do not verify result module"));
static cl::opt<bool>
verifyEach("verify-each", cl::ZeroOrMore, cl::Hidden,
cl::desc("Run verifier after D-specific and explicitly "
"specified optimization passes"));
static cl::opt<bool>
disableLangSpecificPasses("disable-d-passes", cl::ZeroOrMore,
cl::desc("Disable all D-specific passes"));
static cl::opt<bool> disableSimplifyDruntimeCalls(
"disable-simplify-drtcalls", cl::ZeroOrMore,
cl::desc("Disable simplification of druntime calls"));
static cl::opt<bool> disableSimplifyLibCalls(
"disable-simplify-libcalls", cl::ZeroOrMore,
cl::desc("Disable simplification of well-known C runtime calls"));
static cl::opt<bool> disableGCToStack(
"disable-gc2stack", cl::ZeroOrMore,
cl::desc("Disable promotion of GC allocations to stack memory"));
#ifndef IN_JITRT
static cl::opt<cl::boolOrDefault, false, opts::FlagParser<cl::boolOrDefault>>
enableInlining(
"inlining", cl::ZeroOrMore,
cl::desc("(*) Enable function inlining (default in -O2 and higher)"));
static cl::opt<cl::boolOrDefault, false, opts::FlagParser<cl::boolOrDefault>>
enableCrossModuleInlining(
"cross-module-inlining", cl::ZeroOrMore, cl::Hidden,
cl::desc("(*) Enable cross-module function inlining (default disabled)"));
#endif
static cl::opt<bool> stripDebug(
"strip-debug", cl::ZeroOrMore,
cl::desc("Strip symbolic debug information before optimization"));
static cl::opt<bool> disableLoopUnrolling(
"disable-loop-unrolling", cl::ZeroOrMore,
cl::desc("Disable loop unrolling in all relevant passes"));
static cl::opt<bool>
disableLoopVectorization("disable-loop-vectorization", cl::ZeroOrMore,
cl::desc("Disable the loop vectorization pass"));
static cl::opt<bool>
disableSLPVectorization("disable-slp-vectorization", cl::ZeroOrMore,
cl::desc("Disable the slp vectorization pass"));
static cl::opt<int> fSanitizeMemoryTrackOrigins(
"fsanitize-memory-track-origins", cl::ZeroOrMore, cl::init(0),
cl::desc(
"Enable origins tracking in MemorySanitizer (0=disabled, default)"));
unsigned optLevel() {
// Use -O2 as a base for the size-optimization levels.
return optimizeLevel >= 0 ? optimizeLevel : 2;
}
static unsigned sizeLevel() { return optimizeLevel < 0 ? -optimizeLevel : 0; }
// Determines whether or not to run the normal, full inlining pass.
bool willInline() {
#ifdef IN_JITRT
return false;
#else
return enableInlining == cl::BOU_TRUE ||
(enableInlining == cl::BOU_UNSET && optLevel() > 1);
#endif
}
bool willCrossModuleInline() {
#ifdef IN_JITRT
return false;
#else
return enableCrossModuleInlining == llvm::cl::BOU_TRUE && willInline();
#endif
}
bool isOptimizationEnabled() { return optimizeLevel != 0; }
llvm::CodeGenOptLevel codeGenOptLevel() {
// Use same appoach as clang (see lib/CodeGen/BackendUtil.cpp)
if (optLevel() == 0) {
return llvm::CodeGenOptLevel::None;
}
if (optLevel() >= 3) {
return llvm::CodeGenOptLevel::Aggressive;
}
return llvm::CodeGenOptLevel::Default;
}
std::unique_ptr<TargetLibraryInfoImpl> createTLII(llvm::Module &M) {
auto tlii = new TargetLibraryInfoImpl(Triple(M.getTargetTriple()));
// The -disable-simplify-libcalls flag actually disables all builtin optzns.
if (disableSimplifyLibCalls)
tlii->disableAllFunctions();
return std::unique_ptr<TargetLibraryInfoImpl>(tlii);
}
static OptimizationLevel getOptimizationLevel(){
switch(optimizeLevel) {
case 0: return OptimizationLevel::O0;
case 1: return OptimizationLevel::O1;
case 2: return OptimizationLevel::O2;
case 3:
case 4:
case 5: return OptimizationLevel::O3;
case -1: return OptimizationLevel::Os;
case -2: return OptimizationLevel::Oz;
}
//This should never be reached
llvm_unreachable("Unexpected optimizeLevel.");
return OptimizationLevel::O0;
}
#ifndef IN_JITRT
static void addAddressSanitizerPasses(ModulePassManager &mpm,
OptimizationLevel level
#if LDC_LLVM_VER >= 2000
,
ThinOrFullLTOPhase
#endif
) {
AddressSanitizerOptions aso;
aso.CompileKernel = false;
aso.Recover = opts::isSanitizerRecoveryEnabled(opts::AddressSanitizer);
aso.UseAfterScope = true;
aso.UseAfterReturn = opts::fSanitizeAddressUseAfterReturn;
#if LDC_LLVM_VER >= 1600
mpm.addPass(AddressSanitizerPass(aso));
#else
mpm.addPass(ModuleAddressSanitizerPass(aso));
#endif
}
static void addMemorySanitizerPass(ModulePassManager &mpm,
FunctionPassManager &fpm,
OptimizationLevel level ) {
int trackOrigins = fSanitizeMemoryTrackOrigins;
bool recover = opts::isSanitizerRecoveryEnabled(opts::MemorySanitizer);
bool kernel = false;
#if LDC_LLVM_VER >= 1600
mpm.addPass(MemorySanitizerPass(
MemorySanitizerOptions{trackOrigins, recover, kernel}));
#else
fpm.addPass(MemorySanitizerPass(
MemorySanitizerOptions{trackOrigins, recover, kernel}));
#endif
// MemorySanitizer inserts complex instrumentation that mostly follows
// the logic of the original code, but operates on "shadow" values.
// It can benefit from re-running some general purpose optimization passes.
if (level != OptimizationLevel::O0) {
fpm.addPass(EarlyCSEPass());
fpm.addPass(ReassociatePass());
//FIXME: Fix these parameters
fpm.addPass(createFunctionToLoopPassAdaptor(LICMPass(128,128,false)));
fpm.addPass(GVNPass());
//FIXME: Not sure what to do with these?
//fpm.addPass(InstructionCombiningPass());
//fpm.addPass(DeadStoreEliminationPass());
}
}
static void addThreadSanitizerPass(ModulePassManager &mpm,
OptimizationLevel level
#if LDC_LLVM_VER >= 2000
,
ThinOrFullLTOPhase
#endif
) {
mpm.addPass(ModuleThreadSanitizerPass());
mpm.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
}
static void addSanitizerCoveragePass(ModulePassManager &mpm,
OptimizationLevel level
#if LDC_LLVM_VER >= 2000
,
ThinOrFullLTOPhase
#endif
) {
#if LDC_LLVM_VER >= 1600
mpm.addPass(SanitizerCoveragePass(
opts::getSanitizerCoverageOptions()));
#else
mpm.addPass(ModuleSanitizerCoveragePass(
opts::getSanitizerCoverageOptions()));
#endif
}
// Adds PGO instrumentation generation and use passes.
static void addPGOPasses(ModulePassManager &mpm, OptimizationLevel level) {
if (opts::isInstrumentingForASTBasedPGO()) {
InstrProfOptions options;
options.NoRedZone = global.params.disableRedZone;
if (global.params.datafileInstrProf)
options.InstrProfileOutput = global.params.datafileInstrProf;
mpm.addPass(
#if LDC_LLVM_VER < 1800
InstrProfiling(options)
#else
InstrProfilingLoweringPass(options)
#endif // LDC_LLVM_VER < 1800
);
} else if (opts::isUsingASTBasedPGOProfile()) {
// We are generating code with PGO profile information available.
// Do indirect call promotion from -O1
if (level != OptimizationLevel::O0) {
mpm.addPass(PGOIndirectCallPromotion());
}
}
}
#endif // !IN_JITRT
static void addStripExternalsPass(ModulePassManager &mpm,
OptimizationLevel level
#if LDC_LLVM_VER >= 2000
,
ThinOrFullLTOPhase
#endif
) {
if (level == OptimizationLevel::O1 || level == OptimizationLevel::O2 ||
level == OptimizationLevel::O3) {
mpm.addPass(StripExternalsPass());
if (verifyEach) {
mpm.addPass(VerifierPass());
}
mpm.addPass(GlobalDCEPass());
}
}
static void addSimplifyDRuntimeCallsPass(ModulePassManager &mpm,
OptimizationLevel level
#if LDC_LLVM_VER >= 2000
,
ThinOrFullLTOPhase
#endif
) {
if (level == OptimizationLevel::O2 || level == OptimizationLevel::O3) {
mpm.addPass(createModuleToFunctionPassAdaptor(SimplifyDRuntimeCallsPass()));
if (verifyEach) {
mpm.addPass(VerifierPass());
}
}
}
static void addGarbageCollect2StackPass(ModulePassManager &mpm,
OptimizationLevel level
#if LDC_LLVM_VER >= 2000
,
ThinOrFullLTOPhase
#endif
) {
if (level == OptimizationLevel::O2 || level == OptimizationLevel::O3) {
mpm.addPass(createModuleToFunctionPassAdaptor(GarbageCollect2StackPass()));
if (verifyEach) {
mpm.addPass(VerifierPass());
}
}
}
#ifndef IN_JITRT
static llvm::Optional<PGOOptions> getPGOOptions() {
// FIXME: Do we have these anywhere?
bool debugInfoForProfiling = false;
bool pseudoProbeForProfiling = false;
if (opts::isInstrumentingForIRBasedPGO()) {
return PGOOptions(
global.params.datafileInstrProf, "", "",
#if LDC_LLVM_VER >= 1700
"" /*MemoryProfileUsePath*/, llvm::vfs::getRealFileSystem(),
#endif
PGOOptions::PGOAction::IRInstr, PGOOptions::CSPGOAction::NoCSAction,
#if LDC_LLVM_VER >= 1900
PGOOptions::ColdFuncOpt::Default,
#endif
debugInfoForProfiling, pseudoProbeForProfiling);
} else if (opts::isUsingIRBasedPGOProfile()) {
return PGOOptions(
global.params.datafileInstrProf, "", "",
#if LDC_LLVM_VER >= 1700
"" /*MemoryProfileUsePath*/, llvm::vfs::getRealFileSystem(),
#endif
PGOOptions::PGOAction::IRUse, PGOOptions::CSPGOAction::NoCSAction,
#if LDC_LLVM_VER >= 1900
PGOOptions::ColdFuncOpt::Default,
#endif
debugInfoForProfiling, pseudoProbeForProfiling);
} else if (opts::isUsingSampleBasedPGOProfile()) {
return PGOOptions(
global.params.datafileInstrProf, "", "",
#if LDC_LLVM_VER >= 1700
"" /*MemoryProfileUsePath*/, llvm::vfs::getRealFileSystem(),
#endif
PGOOptions::PGOAction::SampleUse, PGOOptions::CSPGOAction::NoCSAction,
#if LDC_LLVM_VER >= 1900
PGOOptions::ColdFuncOpt::Default,
#endif
debugInfoForProfiling, pseudoProbeForProfiling);
}
#if LDC_LLVM_VER < 1600
return None;
#else
return std::nullopt;
#endif
}
#endif // !IN_JITRT
static PipelineTuningOptions getPipelineTuningOptions(unsigned optLevelVal, unsigned sizeLevelVal) {
PipelineTuningOptions pto;
pto.LoopUnrolling = optLevelVal > 0;
pto.LoopUnrolling = !((disableLoopUnrolling.getNumOccurrences() > 0)
? disableLoopUnrolling
: optLevelVal == 0);
// This is final, unless there is a #pragma vectorize enable
if (disableLoopVectorization) {
pto.LoopVectorization = false;
// If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
} else if (!pto.LoopVectorization) {
pto.LoopVectorization = optLevelVal > 1 && sizeLevelVal < 2;
}
// When #pragma vectorize is on for SLP, do the same as above
pto.SLPVectorization =
disableSLPVectorization ? false : optLevelVal > 1 && sizeLevelVal < 2;
return pto;
}
/**
* Adds a set of optimization passes to the given module/function pass
* managers based on the given optimization and size reduction levels.
*
* The selection mirrors Clang behavior and is based on LLVM's
* PassManagerBuilder.
*/
//Run optimization passes using the new pass manager
void runOptimizationPasses(llvm::Module *M, llvm::TargetMachine *TM) {
// Create a ModulePassManager to hold and optimize the collection of
// per-module passes we are about to build.
unsigned optLevelVal = optLevel();
unsigned sizeLevelVal = sizeLevel();
// builder.OptLevel = optLevel;
// builder.SizeLevel = sizeLevel;
// builder.PrepareForLTO = opts::isUsingLTO();
// builder.PrepareForThinLTO = opts::isUsingThinLTO();
//
// if (willInline()) {
// auto params = llvm::getInlineParams(optLevel, sizeLevel);
// builder.Inliner = createFunctionInliningPass(params);
// } else {
// builder.Inliner = createAlwaysInlinerLegacyPass();
// }
LoopAnalysisManager lam;
FunctionAnalysisManager fam;
CGSCCAnalysisManager cgam;
ModuleAnalysisManager mam;
PassInstrumentationCallbacks pic;
PrintPassOptions ppo;
//FIXME: Where should these come from
bool debugLogging = false;
ppo.Indent = false;
ppo.SkipAnalyses = false;
#if LDC_LLVM_VER < 1600
StandardInstrumentations si(debugLogging, /*VerifyEach=*/false, ppo);
#else
StandardInstrumentations si(M->getContext(), debugLogging, /*VerifyEach=*/false, ppo);
#endif
#if LDC_LLVM_VER < 1700
si.registerCallbacks(pic, &fam);
#else
si.registerCallbacks(pic, &mam);
#endif
PassBuilder pb(TM, getPipelineTuningOptions(optLevelVal, sizeLevelVal),
#ifdef IN_JITRT
{}, &pic);
#else
getPGOOptions(), &pic);
#endif
// register the target library analysis directly because clang does :)
auto tlii = createTLII(*M);
fam.registerPass([&] { return TargetLibraryAnalysis(*tlii); });
ModulePassManager mpm;
if (!noVerify) {
pb.registerPipelineStartEPCallback(
[&](ModulePassManager &mpm, OptimizationLevel level,
ThinOrFullLTOPhase phase = ThinOrFullLTOPhase::None) {
mpm.addPass(VerifierPass());
});
}
// TODO: port over strip-debuginfos pass for -strip-debug
#ifndef IN_JITRT
pb.registerPipelineStartEPCallback(addPGOPasses);
if (opts::isSanitizerEnabled(opts::AddressSanitizer)) {
pb.registerOptimizerLastEPCallback(addAddressSanitizerPasses);
}
if (opts::isSanitizerEnabled(opts::MemorySanitizer)) {
pb.registerOptimizerLastEPCallback(
[&](ModulePassManager &mpm, OptimizationLevel level,
ThinOrFullLTOPhase phase = ThinOrFullLTOPhase::None) {
FunctionPassManager fpm;
addMemorySanitizerPass(mpm, fpm, level);
mpm.addPass(createModuleToFunctionPassAdaptor(std::move(fpm)));
});
}
if (opts::isSanitizerEnabled(opts::ThreadSanitizer)) {
pb.registerOptimizerLastEPCallback(addThreadSanitizerPass);
}
if (opts::isSanitizerEnabled(opts::CoverageSanitizer)) {
pb.registerOptimizerLastEPCallback(addSanitizerCoveragePass);
}
#endif // !IN_JITRT
if (!disableLangSpecificPasses) {
if (!disableSimplifyDruntimeCalls) {
// FIXME: Is this registerOptimizerLastEPCallback correct here
//(had registerLoopOptimizerEndEPCallback) but that seems wrong
pb.registerOptimizerLastEPCallback(addSimplifyDRuntimeCallsPass);
}
if (!disableGCToStack) {
// FIXME: This should be checked
fam.registerPass([&] { return DominatorTreeAnalysis(); });
mam.registerPass([&] { return CallGraphAnalysis(); });
// FIXME: Is this registerOptimizerLastEPCallback correct here
//(had registerLoopOptimizerEndEPCallback) but that seems wrong
pb.registerOptimizerLastEPCallback(addGarbageCollect2StackPass);
}
}
pb.registerOptimizerLastEPCallback(addStripExternalsPass);
#ifndef IN_JITRT
registerAllPluginsWithPassBuilder(pb);
#endif
pb.registerModuleAnalyses(mam);
pb.registerCGSCCAnalyses(cgam);
pb.registerFunctionAnalyses(fam);
pb.registerLoopAnalyses(lam);
pb.crossRegisterProxies(lam, fam, cgam, mam);
OptimizationLevel level = getOptimizationLevel();
if (optLevelVal == 0) {
#ifdef IN_JITRT
#if LDC_LLVM_VER >= 2000
const ThinOrFullLTOPhase ltoPrelink = ThinOrFullLTOPhase::None;
#else
const bool ltoPrelink = false;
#endif // LDC_LLVM_VER >= 2000
mpm = pb.buildO0DefaultPipeline(level, ltoPrelink);
#else
#if LDC_LLVM_VER >= 2000
const ThinOrFullLTOPhase ltoPrelink =
opts::isUsingLTO()
? (opts::isUsingThinLTO() ? ThinOrFullLTOPhase::ThinLTOPreLink
: ThinOrFullLTOPhase::FullLTOPreLink)
: ThinOrFullLTOPhase::None;
#else
const bool ltoPrelink = opts::isUsingLTO();
#endif // LDC_LLVM_VER >= 2000
mpm = pb.buildO0DefaultPipeline(level, ltoPrelink);
#if LDC_LLVM_VER >= 1700
} else if (opts::ltoFatObjects && opts::isUsingLTO()) {
mpm = pb.buildFatLTODefaultPipeline(level,
opts::isUsingThinLTO(),
opts::isUsingThinLTO()
);
#endif
} else if (opts::isUsingThinLTO()) {
mpm = pb.buildThinLTOPreLinkDefaultPipeline(level);
} else if (opts::isUsingLTO()) {
mpm = pb.buildLTOPreLinkDefaultPipeline(level);
#endif // !IN_JITRT
} else {
mpm = pb.buildPerModuleDefaultPipeline(level);
}
mpm.run(*M,mam);
}
////////////////////////////////////////////////////////////////////////////////
// This function runs optimization passes based on command line arguments.
// Returns true if any optimization passes were invoked.
bool ldc_optimize_module(llvm::Module *M, llvm::TargetMachine *TM) {
#ifndef IN_JITRT
// Dont optimise spirv modules because turning GEPs into extracts triggers
// asserts in the IR -> SPIR-V translation pass. SPIRV doesn't have a target
// machine, so any optimisation passes that rely on it to provide analysis,
// like DCE can't be run.
// The optimisation is supposed to happen between the SPIRV -> native machine
// code pass of the consumer of the binary.
// TODO: run rudimentary optimisations to improve IR debuggability.
if (getComputeTargetType(M) == ComputeBackend::SPIRV)
return false;
#endif
runOptimizationPasses(M, TM);
// Verify the resulting module.
if (!noVerify) {
verifyModule(M);
}
// Report that we run some passes.
return true;
}
#ifdef IN_JITRT
void optimizeModule(const OptimizerSettings &settings, llvm::Module *M,
llvm::TargetMachine *TM) {
if (settings.sizeLevel > 0) {
optimizeLevel = -settings.sizeLevel;
} else {
optimizeLevel = settings.optLevel;
}
ldc_optimize_module(M, TM);
}
#endif // IN_JITRT
// Verifies the module.
void verifyModule(llvm::Module *m) {
#ifndef IN_JITRT
Logger::println("Verifying module...");
LOG_SCOPE;
#endif
std::string ErrorStr;
raw_string_ostream OS(ErrorStr);
if (llvm::verifyModule(*m, &OS)) {
#ifndef IN_JITRT
error(Loc(), "%s", ErrorStr.c_str());
fatal();
#else
assert(false && "Verification failed!");
#endif
}
#ifndef IN_JITRT
Logger::println("Verification passed!");
#endif
}
// Output to `hash_os` all optimization settings that influence object code
// output and that are not observable in the IR. This is used to calculate the
// hash use for caching that uniquely identifies the object file output.
void outputOptimizationSettings(llvm::raw_ostream &hash_os) {
hash_os << optimizeLevel;
hash_os << willInline();
hash_os << disableLangSpecificPasses;
hash_os << disableSimplifyDruntimeCalls;
hash_os << disableSimplifyLibCalls;
hash_os << disableGCToStack;
hash_os << stripDebug;
hash_os << disableLoopUnrolling;
hash_os << disableLoopVectorization;
hash_os << disableSLPVectorization;
}
#ifdef IN_JITRT
void setRtCompileVar(const Context &context, llvm::Module &module,
const char *name, const void *init) {
assert(nullptr != name);
assert(nullptr != init);
auto var = module.getGlobalVariable(name);
if (nullptr != var) {
auto type = var->getValueType();
auto initializer =
parseInitializer(module.getDataLayout(), *type, init,
[&](const std::string &str) { fatal(context, str); });
var->setConstant(true);
var->setInitializer(initializer);
var->setLinkage(llvm::GlobalValue::PrivateLinkage);
}
}
#endif // IN_JITRT