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

        use std::str::FromStr;

        #[derive(Eq, PartialEq, Debug)]
        pub enum OptimizationPass {
            /// removes arguments to calls in an lto-like manner
Dae,
/// removes arguments to calls in an lto-like manner, and optimizes where we removed
DaeOptimizing,
/// reduce # of locals by coalescing
CoalesceLocals,
/// reduce # of locals by coalescing and learning
CoalesceLocalsLearning,
/// push code forward, potentially making it not always execute
CodePushing,
/// fold code, merging duplicates
CodeFolding,
/// hoist repeated constants to a local
ConstHoisting,
/// removes unreachable code
Dce,
/// turns indirect calls into direct ones
Directize,
/// optimizes using the DataFlow SSA IR
Dfo,
/// removes duplicate functions
DuplicateFunctionElimination,
/// leaves just one function (useful for debugging)
ExtractFunction,
/// flattens out code, removing nesting
Flatten,
/// emulates function pointer casts, allowing incorrect indirect calls to (sometimes) work
FpcastEmu,
/// reports function metrics
FuncMetrics,
/// generate Stack IR
GenerateStackIr,
/// inline functions (you probably want inlining-optimizing)
Inlining,
/// inline functions and optimizes where we inlined
InliningOptimizing,
/// legalizes i64 types on the import/export boundary
LegalizeJsInterface,
/// legalizes i64 types on the import/export boundary in a minimal manner, only on things only JS will call
LegalizeJsInterfaceMinimally,
/// common subexpression elimination inside basic blocks
LocalCse,
/// instrument the build with logging of where execution goes
LogExecution,
/// lower all uses of i64s to use i32s instead
I64ToI32Lowering,
/// instrument the build with code to intercept all loads and stores
InstrumentLocals,
/// instrument the build with code to intercept all loads and stores
InstrumentMemory,
/// loop invariant code motion
Licm,
/// attempt to merge segments to fit within web limits
LimitSegments,
/// packs memory into separate segments, skipping zeros
MemoryPacking,
/// merges blocks to their parents
MergeBlocks,
/// merges locals when beneficial
MergeLocals,
/// reports metrics
Metrics,
/// minifies import names (only those, and not export names), and emits a mapping to the minified ones
MinifyImports,
/// minifies both import and export names, and emits a mapping to the minified ones
MinifyImportsAndExports,
/// name list
Nm,
/// removes calls to atexit(), which is valid if the C runtime will never be exited
NoExitRuntime,
/// optimizes added constants into load/store offsets
OptimizeAddedConstants,
/// optimizes added constants into load/store offsets, propagating them across locals too
OptimizeAddedConstantsPropagate,
/// optimizes instruction combinations
OptimizeInstructions,
/// optimize Stack IR
OptimizeStackIr,
/// pick load signs based on their uses
PickLoadSigns,
/// miscellaneous optimizations for Emscripten-generated code
PostEmscripten,
/// computes compile-time evaluatable expressions
Precompute,
/// computes compile-time evaluatable expressions and propagates them through locals
PrecomputePropagate,
/// print in s-expression format
Print,
/// print in minified s-expression format
PrintMinified,
/// print options for enabled features
PrintFeatures,
/// print in full s-expression format
PrintFull,
/// print call graph
PrintCallGraph,
/// print out Stack IR (useful for internal debugging)
PrintStackIr,
/// thread relooper jumps (fastcomp output only)
RelooperJumpThreading,
/// removes operations incompatible with js
RemoveNonJsOps,
/// removes imports and replaces them with nops
RemoveImports,
/// removes memory segments
RemoveMemory,
/// removes breaks from locations that are not needed
RemoveUnusedBrs,
/// removes unused module elements
RemoveUnusedModuleElements,
/// removes unused module elements that are not functions
RemoveUnusedNonfunctionModuleElements,
/// removes names from locations that are never branched to
RemoveUnusedNames,
/// sorts functions by access frequency
ReorderFunctions,
/// sorts locals by access frequency
ReorderLocals,
/// re-optimize control flow using the relooper algorithm
Rereloop,
/// remove redundant local.sets
Rse,
/// instrument loads and stores to check for invalid behavior
SafeHeap,
/// miscellaneous locals-related optimizations
SimplifyLocals,
/// miscellaneous locals-related optimizations (no nesting at all; preserves flatness)
SimplifyLocalsNonesting,
/// miscellaneous locals-related optimizations (no tees)
SimplifyLocalsNotee,
/// miscellaneous locals-related optimizations (no structure)
SimplifyLocalsNostructure,
/// miscellaneous locals-related optimizations (no tees or structure)
SimplifyLocalsNoteeNostructure,
/// emit Souper IR in text form
Souperify,
/// emit Souper IR in text form (single-use nodes only)
SouperifySingleUse,
/// spill pointers to the C stack (useful for Boehm-style GC)
SpillPointers,
/// ssa-ify variables so that they have a single assignment
Ssa,
/// ssa-ify variables so that they have a single assignment, ignoring merges
SsaNomerge,
/// deprecated; same as strip-debug
Strip,
/// strip debug info (including the names section)
StripDebug,
/// strip the wasm producers section
StripProducers,
/// strip the wasm target features section
StripTargetFeatures,
/// replace trapping operations with clamping semantics
TrapModeClamp,
/// replace trapping operations with js semantics
TrapModeJs,
/// removes local.tees, replacing them with sets and gets
Untee,
/// removes obviously unneeded code
Vacuum,
/// lowers i64 into pairs of i32s
LowerI64
        }

        impl FromStr for OptimizationPass {
            type Err = ();
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                match s {
                    "dae" => Ok(OptimizationPass::Dae),
"dae-optimizing" => Ok(OptimizationPass::DaeOptimizing),
"coalesce-locals" => Ok(OptimizationPass::CoalesceLocals),
"coalesce-locals-learning" => Ok(OptimizationPass::CoalesceLocalsLearning),
"code-pushing" => Ok(OptimizationPass::CodePushing),
"code-folding" => Ok(OptimizationPass::CodeFolding),
"const-hoisting" => Ok(OptimizationPass::ConstHoisting),
"dce" => Ok(OptimizationPass::Dce),
"directize" => Ok(OptimizationPass::Directize),
"dfo" => Ok(OptimizationPass::Dfo),
"duplicate-function-elimination" => Ok(OptimizationPass::DuplicateFunctionElimination),
"extract-function" => Ok(OptimizationPass::ExtractFunction),
"flatten" => Ok(OptimizationPass::Flatten),
"fpcast-emu" => Ok(OptimizationPass::FpcastEmu),
"func-metrics" => Ok(OptimizationPass::FuncMetrics),
"generate-stack-ir" => Ok(OptimizationPass::GenerateStackIr),
"inlining" => Ok(OptimizationPass::Inlining),
"inlining-optimizing" => Ok(OptimizationPass::InliningOptimizing),
"legalize-js-interface" => Ok(OptimizationPass::LegalizeJsInterface),
"legalize-js-interface-minimally" => Ok(OptimizationPass::LegalizeJsInterfaceMinimally),
"local-cse" => Ok(OptimizationPass::LocalCse),
"log-execution" => Ok(OptimizationPass::LogExecution),
"i64-to-i32-lowering" => Ok(OptimizationPass::I64ToI32Lowering),
"instrument-locals" => Ok(OptimizationPass::InstrumentLocals),
"instrument-memory" => Ok(OptimizationPass::InstrumentMemory),
"licm" => Ok(OptimizationPass::Licm),
"limit-segments" => Ok(OptimizationPass::LimitSegments),
"memory-packing" => Ok(OptimizationPass::MemoryPacking),
"merge-blocks" => Ok(OptimizationPass::MergeBlocks),
"merge-locals" => Ok(OptimizationPass::MergeLocals),
"metrics" => Ok(OptimizationPass::Metrics),
"minify-imports" => Ok(OptimizationPass::MinifyImports),
"minify-imports-and-exports" => Ok(OptimizationPass::MinifyImportsAndExports),
"nm" => Ok(OptimizationPass::Nm),
"no-exit-runtime" => Ok(OptimizationPass::NoExitRuntime),
"optimize-added-constants" => Ok(OptimizationPass::OptimizeAddedConstants),
"optimize-added-constants-propagate" => Ok(OptimizationPass::OptimizeAddedConstantsPropagate),
"optimize-instructions" => Ok(OptimizationPass::OptimizeInstructions),
"optimize-stack-ir" => Ok(OptimizationPass::OptimizeStackIr),
"pick-load-signs" => Ok(OptimizationPass::PickLoadSigns),
"post-emscripten" => Ok(OptimizationPass::PostEmscripten),
"precompute" => Ok(OptimizationPass::Precompute),
"precompute-propagate" => Ok(OptimizationPass::PrecomputePropagate),
"print" => Ok(OptimizationPass::Print),
"print-minified" => Ok(OptimizationPass::PrintMinified),
"print-features" => Ok(OptimizationPass::PrintFeatures),
"print-full" => Ok(OptimizationPass::PrintFull),
"print-call-graph" => Ok(OptimizationPass::PrintCallGraph),
"print-stack-ir" => Ok(OptimizationPass::PrintStackIr),
"relooper-jump-threading" => Ok(OptimizationPass::RelooperJumpThreading),
"remove-non-js-ops" => Ok(OptimizationPass::RemoveNonJsOps),
"remove-imports" => Ok(OptimizationPass::RemoveImports),
"remove-memory" => Ok(OptimizationPass::RemoveMemory),
"remove-unused-brs" => Ok(OptimizationPass::RemoveUnusedBrs),
"remove-unused-module-elements" => Ok(OptimizationPass::RemoveUnusedModuleElements),
"remove-unused-nonfunction-module-elements" => Ok(OptimizationPass::RemoveUnusedNonfunctionModuleElements),
"remove-unused-names" => Ok(OptimizationPass::RemoveUnusedNames),
"reorder-functions" => Ok(OptimizationPass::ReorderFunctions),
"reorder-locals" => Ok(OptimizationPass::ReorderLocals),
"rereloop" => Ok(OptimizationPass::Rereloop),
"rse" => Ok(OptimizationPass::Rse),
"safe-heap" => Ok(OptimizationPass::SafeHeap),
"simplify-locals" => Ok(OptimizationPass::SimplifyLocals),
"simplify-locals-nonesting" => Ok(OptimizationPass::SimplifyLocalsNonesting),
"simplify-locals-notee" => Ok(OptimizationPass::SimplifyLocalsNotee),
"simplify-locals-nostructure" => Ok(OptimizationPass::SimplifyLocalsNostructure),
"simplify-locals-notee-nostructure" => Ok(OptimizationPass::SimplifyLocalsNoteeNostructure),
"souperify" => Ok(OptimizationPass::Souperify),
"souperify-single-use" => Ok(OptimizationPass::SouperifySingleUse),
"spill-pointers" => Ok(OptimizationPass::SpillPointers),
"ssa" => Ok(OptimizationPass::Ssa),
"ssa-nomerge" => Ok(OptimizationPass::SsaNomerge),
"strip" => Ok(OptimizationPass::Strip),
"strip-debug" => Ok(OptimizationPass::StripDebug),
"strip-producers" => Ok(OptimizationPass::StripProducers),
"strip-target-features" => Ok(OptimizationPass::StripTargetFeatures),
"trap-mode-clamp" => Ok(OptimizationPass::TrapModeClamp),
"trap-mode-js" => Ok(OptimizationPass::TrapModeJs),
"untee" => Ok(OptimizationPass::Untee),
"vacuum" => Ok(OptimizationPass::Vacuum),
"lower-i64" => Ok(OptimizationPass::LowerI64),
                    _ => Err(()),
                }
            }
        }

        trait OptimizationPassDescription {
            fn description(&self) -> &'static str;
        }

        impl OptimizationPassDescription for OptimizationPass {
            fn description(&self) -> &'static str {
                match self {
                    OptimizationPass::Dae => "removes arguments to calls in an lto-like manner",
OptimizationPass::DaeOptimizing => "removes arguments to calls in an lto-like manner, and optimizes where we removed",
OptimizationPass::CoalesceLocals => "reduce # of locals by coalescing",
OptimizationPass::CoalesceLocalsLearning => "reduce # of locals by coalescing and learning",
OptimizationPass::CodePushing => "push code forward, potentially making it not always execute",
OptimizationPass::CodeFolding => "fold code, merging duplicates",
OptimizationPass::ConstHoisting => "hoist repeated constants to a local",
OptimizationPass::Dce => "removes unreachable code",
OptimizationPass::Directize => "turns indirect calls into direct ones",
OptimizationPass::Dfo => "optimizes using the DataFlow SSA IR",
OptimizationPass::DuplicateFunctionElimination => "removes duplicate functions",
OptimizationPass::ExtractFunction => "leaves just one function (useful for debugging)",
OptimizationPass::Flatten => "flattens out code, removing nesting",
OptimizationPass::FpcastEmu => "emulates function pointer casts, allowing incorrect indirect calls to (sometimes) work",
OptimizationPass::FuncMetrics => "reports function metrics",
OptimizationPass::GenerateStackIr => "generate Stack IR",
OptimizationPass::Inlining => "inline functions (you probably want inlining-optimizing)",
OptimizationPass::InliningOptimizing => "inline functions and optimizes where we inlined",
OptimizationPass::LegalizeJsInterface => "legalizes i64 types on the import/export boundary",
OptimizationPass::LegalizeJsInterfaceMinimally => "legalizes i64 types on the import/export boundary in a minimal manner, only on things only JS will call",
OptimizationPass::LocalCse => "common subexpression elimination inside basic blocks",
OptimizationPass::LogExecution => "instrument the build with logging of where execution goes",
OptimizationPass::I64ToI32Lowering => "lower all uses of i64s to use i32s instead",
OptimizationPass::InstrumentLocals => "instrument the build with code to intercept all loads and stores",
OptimizationPass::InstrumentMemory => "instrument the build with code to intercept all loads and stores",
OptimizationPass::Licm => "loop invariant code motion",
OptimizationPass::LimitSegments => "attempt to merge segments to fit within web limits",
OptimizationPass::MemoryPacking => "packs memory into separate segments, skipping zeros",
OptimizationPass::MergeBlocks => "merges blocks to their parents",
OptimizationPass::MergeLocals => "merges locals when beneficial",
OptimizationPass::Metrics => "reports metrics",
OptimizationPass::MinifyImports => "minifies import names (only those, and not export names), and emits a mapping to the minified ones",
OptimizationPass::MinifyImportsAndExports => "minifies both import and export names, and emits a mapping to the minified ones",
OptimizationPass::Nm => "name list",
OptimizationPass::NoExitRuntime => "removes calls to atexit(), which is valid if the C runtime will never be exited",
OptimizationPass::OptimizeAddedConstants => "optimizes added constants into load/store offsets",
OptimizationPass::OptimizeAddedConstantsPropagate => "optimizes added constants into load/store offsets, propagating them across locals too",
OptimizationPass::OptimizeInstructions => "optimizes instruction combinations",
OptimizationPass::OptimizeStackIr => "optimize Stack IR",
OptimizationPass::PickLoadSigns => "pick load signs based on their uses",
OptimizationPass::PostEmscripten => "miscellaneous optimizations for Emscripten-generated code",
OptimizationPass::Precompute => "computes compile-time evaluatable expressions",
OptimizationPass::PrecomputePropagate => "computes compile-time evaluatable expressions and propagates them through locals",
OptimizationPass::Print => "print in s-expression format",
OptimizationPass::PrintMinified => "print in minified s-expression format",
OptimizationPass::PrintFeatures => "print options for enabled features",
OptimizationPass::PrintFull => "print in full s-expression format",
OptimizationPass::PrintCallGraph => "print call graph",
OptimizationPass::PrintStackIr => "print out Stack IR (useful for internal debugging)",
OptimizationPass::RelooperJumpThreading => "thread relooper jumps (fastcomp output only)",
OptimizationPass::RemoveNonJsOps => "removes operations incompatible with js",
OptimizationPass::RemoveImports => "removes imports and replaces them with nops",
OptimizationPass::RemoveMemory => "removes memory segments",
OptimizationPass::RemoveUnusedBrs => "removes breaks from locations that are not needed",
OptimizationPass::RemoveUnusedModuleElements => "removes unused module elements",
OptimizationPass::RemoveUnusedNonfunctionModuleElements => "removes unused module elements that are not functions",
OptimizationPass::RemoveUnusedNames => "removes names from locations that are never branched to",
OptimizationPass::ReorderFunctions => "sorts functions by access frequency",
OptimizationPass::ReorderLocals => "sorts locals by access frequency",
OptimizationPass::Rereloop => "re-optimize control flow using the relooper algorithm",
OptimizationPass::Rse => "remove redundant local.sets",
OptimizationPass::SafeHeap => "instrument loads and stores to check for invalid behavior",
OptimizationPass::SimplifyLocals => "miscellaneous locals-related optimizations",
OptimizationPass::SimplifyLocalsNonesting => "miscellaneous locals-related optimizations (no nesting at all; preserves flatness)",
OptimizationPass::SimplifyLocalsNotee => "miscellaneous locals-related optimizations (no tees)",
OptimizationPass::SimplifyLocalsNostructure => "miscellaneous locals-related optimizations (no structure)",
OptimizationPass::SimplifyLocalsNoteeNostructure => "miscellaneous locals-related optimizations (no tees or structure)",
OptimizationPass::Souperify => "emit Souper IR in text form",
OptimizationPass::SouperifySingleUse => "emit Souper IR in text form (single-use nodes only)",
OptimizationPass::SpillPointers => "spill pointers to the C stack (useful for Boehm-style GC)",
OptimizationPass::Ssa => "ssa-ify variables so that they have a single assignment",
OptimizationPass::SsaNomerge => "ssa-ify variables so that they have a single assignment, ignoring merges",
OptimizationPass::Strip => "deprecated; same as strip-debug",
OptimizationPass::StripDebug => "strip debug info (including the names section)",
OptimizationPass::StripProducers => "strip the wasm producers section",
OptimizationPass::StripTargetFeatures => "strip the wasm target features section",
OptimizationPass::TrapModeClamp => "replace trapping operations with clamping semantics",
OptimizationPass::TrapModeJs => "replace trapping operations with js semantics",
OptimizationPass::Untee => "removes local.tees, replacing them with sets and gets",
OptimizationPass::Vacuum => "removes obviously unneeded code",
OptimizationPass::LowerI64 => "lowers i64 into pairs of i32s"
                }
            }
        }

        #[cfg(test)]
        mod tests {
            use super::*;

            #[test]
            fn test_from_str() {
                assert_eq!(OptimizationPass::Dae, OptimizationPass::from_str("dae").expect("from_str expected to work"));
            }

            #[test]
            fn test_description() {
                assert_eq!(OptimizationPass::Dae.description(), "removes arguments to calls in an lto-like manner");
            }
        }