-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProgram.cs
214 lines (180 loc) · 7.27 KB
/
Program.cs
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
using System.Text.RegularExpressions;
using CommandLine;
using CommandLine.Text;
using DistIL;
using DistIL.AsmIO;
using DistIL.Passes;
var parser = new CommandLine.Parser(c => {
c.CaseInsensitiveEnumValues = true;
});
var result = parser
.ParseArguments<OptimizerOptions>(args)
.WithParsed(RunOptimizer);
if (result.Tag == ParserResultType.NotParsed) {
var help = HelpText.AutoBuild(result, h => {
h.AddEnumValuesToHelpText = true;
return h;
});
Console.WriteLine(help);
}
static void RunOptimizer(OptimizerOptions options)
{
var logger = new ConsoleLogger() { MinLevel = options.Verbosity };
using var resolver = new ModuleResolver(logger);
resolver.AddSearchPaths([Path.GetDirectoryName(Path.GetFullPath(options.InputPath))!]);
resolver.AddSearchPaths(options.ResolverPaths);
if (!options.NoResolverFallback) {
resolver.AddTrustedSearchPaths();
}
var module = resolver.Load(options.InputPath);
var comp = new Compilation(module, logger, new CompilationSettings());
RunPasses(options, comp);
string? outputPath = options.OutputPath;
if (outputPath == null) {
File.Move(options.InputPath, Path.ChangeExtension(options.InputPath, ".dll.bak"), overwrite: true);
outputPath = options.InputPath;
}
module.Save(outputPath, savePdb: !options.DisablePdbGeneration);
}
static void RunPasses(OptimizerOptions options, Compilation comp)
{
var manager = new PassManager() {
Compilation = comp,
Inspectors = { new PassTimingInspector() }
};
manager.AddPasses()
.Apply<SimplifyCFG>()
.Apply<SsaPromotion>()
.Apply<ExpandLinq>()
.Apply<SimplifyInsts>(); // lambdas and devirtualization
manager.AddPasses(applyIndependently: true) // this is so that all callees are in SSA before inlining.
.Apply<InlineMethods>();
var simplifySeg = manager.AddPasses()
.Apply<SimplifyInsts>()
.Apply<SimplifyCFG>()
.Apply<DeadCodeElim>()
.RepeatUntilFixedPoint(maxIters: 3);
manager.AddPasses()
.Apply<ScalarReplacement>()
.IfChanged(c => c.Apply<SsaPromotion>()
.Apply<InlineMethods>()) // SROA+SSA uncovers new devirtualization oportunities
.RepeatUntilFixedPoint(maxIters: 3);
manager.AddPasses()
.Apply<ValueNumbering>()
// FIXME: broken
// .Apply<AssertionProp>()
.Apply<PresizeLists>()
.Apply<LoopStrengthReduction>()
.IfChanged(simplifySeg);
if (comp.Logger.IsEnabled(LogLevel.Debug)) {
manager.AddPasses().Apply<VerificationPass>();
}
var dumpFilter = options.DumpDir != null || options.PassDumpBundlePath != null
? CompileFilter(options.DumpMethodFilter) : null;
if (options.DumpDir != null) {
if (options.PurgeDumps && Directory.Exists(options.DumpDir)) {
Directory.Delete(options.DumpDir, recursive: true);
}
Directory.CreateDirectory(options.DumpDir);
manager.AddPasses().Apply(new DumpPass() {
BaseDir = options.DumpDir,
Formats = options.DumpFmts,
Filter = dumpFilter
});
}
if (options.PassDumpBundlePath != null) {
manager.Inspectors.Add(new PassDiffCollector(options.PassDumpBundlePath, dumpFilter));
}
var methods = PassManager.GetCandidateMethodsFromIL(comp.Module, GetCandidateFilter(options, comp));
if (options.BisectFilter != null) {
ApplyFuzzyBisect(options.BisectFilter, methods);
}
manager.Run(methods);
}
static PassManager.CandidateMethodFilter GetCandidateFilter(OptimizerOptions options, Compilation comp)
{
var filter = CompileFilter(options.PassMethodFilter);
return (caller, method) => {
if (method.Module != comp.Module) {
return false;
}
if (options.FilterUnmarked && !IsMarkedForOpts(method)) {
// Include inner lambdas and local functions within marked parent methods
// to enable inlining into marked methods. See #27
if (!(IsGeneratedInnerMethod(method) && caller != null && IsMarkedForOpts(caller))) {
return false;
}
}
// TODO: support for something like ILLink root descs file, see #30
if (filter != null && !filter.Invoke(method)) {
return false;
}
return true;
};
static bool IsMarkedForOpts(MethodDef method)
{
return (FindOptFlag(method) ?? FindOptFlag(method.DeclaringType)) is true;
}
static bool? FindOptFlag(ModuleEntity entity)
{
foreach (var attr in entity.GetCustomAttribs()) {
if (attr.Type.Namespace != "DistIL.Attributes") continue;
if (attr.Type.Name == "OptimizeAttribute") return true;
if (attr.Type.Name == "DoNotOptimizeAttribute") return false;
}
return null;
}
// Checks if the given method has a mangled lambda or local function name.
// - https://github.com/dotnet/roslyn/blob/main/src/Compilers/CSharp/Portable/Symbols/Synthesized/GeneratedNames.cs
static bool IsGeneratedInnerMethod(MethodDef method)
{
return method.Name.StartsWith('<') && (method.Name.Contains(">b__") || method.Name.Contains(">g__"));
}
}
// Fuzzy bisect will randomly filter-out methods based on a list of probabilities.
// Scripts can brute-force this list to easily find problematic methods.
static void ApplyFuzzyBisect(string filterStr, List<MethodDef> candidates)
{
string[] parts = filterStr.Split(':');
int sourceCount = candidates.Count;
for (int i = 1; i < parts.Length; i++) {
var rng = new Random(123 + i * 456);
float prob = float.Parse(parts[i]) / 100.0f;
candidates.RemoveAll(m => rng.NextSingle() < prob);
}
Console.WriteLine($"Fuzzy bisecting methods {candidates.Count}/{sourceCount}");
File.WriteAllLines("bisect_log.txt", candidates.Select(RenderMethodSig));
}
static Predicate<MethodDef>? CompileFilter(string? pattern)
{
if (pattern == null) {
return null;
}
// Pattern := (ClassName "::")? MethodName ( "(" Seq{TypeName} ")" )? ("|" Pattern)?
pattern = string.Join("|", pattern.Split('|').Select(part => {
var tokens = Regex.Match(part, @"^(?:(.+)::)?(.+?)(?:\((.+)\))?$");
var typeToken = WildcardToRegex(tokens.Groups[1].Value);
var methodToken = WildcardToRegex(tokens.Groups[2].Value);
var sigToken = WildcardToRegex(tokens.Groups[3].Value, true);
return @$"(?:{typeToken}::{methodToken}\({sigToken}\))";
}));
var regex = new Regex("^" + pattern + "$", RegexOptions.CultureInvariant);
return (m) => regex.IsMatch(RenderMethodSig(m));
static string WildcardToRegex(string value, bool normalizeSeq = false)
{
if (string.IsNullOrWhiteSpace(value)) {
return ".*";
}
// Based on https://stackoverflow.com/a/30300521
if (normalizeSeq) {
value = Regex.Replace(value, @"\s*,\s*", ",");
}
value = Regex.Escape(value);
return value.Replace("\\?", ".").Replace("\\*", ".*");
}
}
static string RenderMethodSig(MethodDef def)
{
var pars = def.ParamSig.Skip(def.IsInstance ? 1 : 0);
return $"{def.DeclaringType.Name}::{def.Name}({string.Join(',', pars.Select(p => p.Type.Name))})";
}