using-optimisation.rst 40 KB
Newer Older
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
.. _options-optimise:

Optimisation (code improvement)
-------------------------------

.. index::
   single: optimisation
   single: improvement, code

The ``-O*`` options specify convenient "packages" of optimisation flags;
the ``-f*`` options described later on specify *individual*
optimisations to be turned on/off; the ``-m*`` options specify
*machine-specific* optimisations to be turned on/off.

Most of these options are boolean and have options to turn them both "on" and
"off" (beginning with the prefix ``no-``). For instance, while ``-fspecialise``
enables specialisation, ``-fno-specialise`` disables it. When multiple flags for
the same option appear in the command-line they are evaluated from left to
right. For instance, ``-fno-specialise -fspecialise`` will enable
specialisation.

It is important to note that the ``-O*`` flags are roughly equivalent to
combinations of ``-f*`` flags. For this reason, the effect of the
``-O*`` and ``-f*`` flags is dependent upon the order in which they
occur on the command line.

For instance, take the example of ``-fno-specialise -O1``. Despite the
``-fno-specialise`` appearing in the command line, specialisation will
still be enabled. This is the case as ``-O1`` implies ``-fspecialise``,
overriding the previous flag. By contrast, ``-O1 -fno-specialise`` will
compile without specialisation, as one would expect.

.. _optimise-pkgs:

``-O*``: convenient “packages” of optimisation flags.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are *many* options that affect the quality of code produced by
GHC. Most people only have a general goal, something like "Compile
quickly" or "Make my program run like greased lightning." The following
"packages" of optimisations (or lack thereof) should suffice.

Note that higher optimisation levels cause more cross-module
optimisation to be performed, which can have an impact on how much of
your program needs to be recompiled when you change something. This is
one reason to stick to no-optimisation when developing code.

48
49
50
**No ``-O*``-type option specified:** This is taken to mean “Please 
compile quickly; I'm not over-bothered about compiled-code quality.”
So, for example, ``ghc -c Foo.hs``
51

52
.. ghc-flag:: -O0
53
54
55
    :shortdesc: Disable optimisations (default)
    :type: dynamic
    :category: optimization-levels
56
57
58

    Means "turn off all optimisation", reverting to the same settings as
    if no ``-O`` options had been specified. Saying ``-O0`` can be
59
    useful if e.g. ``make`` has inserted a ``-O`` on the command line
60
61
    already.

62
63
.. ghc-flag:: -O
              -O1
64
65
66
67
    :shortdesc: Enable level 1 optimisations
    :type: dynamic
    :reverse: -O0
    :category: optimization-levels
68

69
70
71
72
73
74
    .. index::
       single: optimise; normally

    Means: "Generate good-quality code without taking too long about
    it." Thus, for example: ``ghc -c -O Main.lhs``

75
.. ghc-flag:: -O2
76
77
78
79
    :shortdesc: Enable level 2 optimisations
    :type: dynamic
    :reverse: -O0
    :category: optimization-levels
80

81
82
83
84
    .. index::
       single: optimise; aggressively

    Means: "Apply every non-dangerous optimisation, even if it means
85
    significantly longer compile times."
86
87
88
89
90

    The avoided "dangerous" optimisations are those that can make
    runtime or space *worse* if you're unlucky. They are normally turned
    on or off individually.

91
.. ghc-flag:: -Odph
92
93
94
95
96
    :shortdesc: Enable level 2 optimisations, set
        ``-fmax-simplifier-iterations=20``
        and ``-fsimplifier-phases=3``.
    :type: dynamic
    :category: optimization-levels
97

98
99
100
101
102
103
104
105
106
107
108
109
110
    .. index::
       single: optimise; DPH

    Enables all ``-O2`` optimisation, sets
    ``-fmax-simplifier-iterations=20`` and ``-fsimplifier-phases=3``.
    Designed for use with :ref:`Data Parallel Haskell (DPH) <dph>`.

We don't use a ``-O*`` flag for day-to-day work. We use ``-O`` to get
respectable speed; e.g., when we want to measure something. When we want
to go for broke, we tend to use ``-O2`` (and we go for lots of coffee
breaks).

The easiest way to see what ``-O`` (etc.) “really mean” is to run with
111
:ghc-flag:`-v`, then stand back in amazement.
112
113
114
115
116
117
118
119
120
121
122

.. _options-f:

``-f*``: platform-independent flags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. index::
   single: -f\* options (GHC)
   single: -fno-\* options (GHC)

These flags turn on and off individual optimisations. Flags marked as
123
on by default are enabled by ``-O``, and as such you shouldn't
124
need to set any of them explicitly. A flag ``-fwombat`` can be negated
125
by saying ``-fno-wombat``.
126

127
.. ghc-flag:: -fcase-merge
128
129
130
131
    :shortdesc: Enable case-merging. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-case-merge
    :category:
132

133
    :default: on
134

Sylvain Henry's avatar
Sylvain Henry committed
135
    Merge immediately-nested case expressions that scrutinise the same variable.
136
    For example, ::
137
138
139

          case x of
             Red -> e1
140
             _   -> case x of
141
142
143
                      Blue -> e2
                      Green -> e3

144
    Is transformed to, ::
145
146
147
148
149
150

          case x of
             Red -> e1
             Blue -> e2
             Green -> e2

Sylvain Henry's avatar
Sylvain Henry committed
151
.. ghc-flag:: -fcase-folding
152
153
154
155
    :shortdesc: Enable constant folding in case expressions. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-case-folding
    :category:
Sylvain Henry's avatar
Sylvain Henry committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

    :default: on

    Allow constant folding in case expressions that scrutinise some primops:
    For example, ::

          case x `minusWord#` 10## of
             10## -> e1
             20## -> e2
             v    -> e3

    Is transformed to, ::

          case x of
             20## -> e1
             30## -> e2
             _    -> let v = x `minusWord#` 10## in e3

174
.. ghc-flag:: -fcall-arity
175
176
177
178
    :shortdesc: Enable call-arity optimisation. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-call-arity
    :category:
179

180
    :default: on
181

182
183
    Enable call-arity analysis.

184
185
186
187
188
189
190
191
192
193
.. ghc-flag:: -fexitification
    :shortdesc: Enables exitification optimisation. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-exitification
    :category:

    :default: on

    Enables the floating of exit paths out of recursive functions.

194
.. ghc-flag:: -fcmm-elim-common-blocks
195
196
197
198
    :shortdesc: Enable Cmm common block elimination. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-cmm-elim-common-blocks
    :category:
199
200

    :default: on
201

202
    Enables the common block elimination optimisation
203
204
205
    in the code generator. This optimisation attempts to find identical
    Cmm blocks and eliminate the duplicates.

206
.. ghc-flag:: -fcmm-sink
207
208
209
210
    :shortdesc: Enable Cmm sinking. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-cmm-sink
    :category:
211
212

    :default: on
213

214
    Enables the sinking pass in the code generator.
215
216
217
218
219
    This optimisation attempts to find identical Cmm blocks and
    eliminate the duplicates attempts to move variable bindings closer
    to their usage sites. It also inlines simple expressions like
    literals or registers.

220
.. ghc-flag:: -fcpr-anal
221
222
223
224
    :shortdesc: Turn on CPR analysis in the demand analyser. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-cpr-anal
    :category:
225

226
227
228
    :default: on

    Turn on CPR analysis in the demand analyser.
229

230
.. ghc-flag:: -fcse
231
232
233
234
    :shortdesc: Enable common sub-expression elimination. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-cse
    :category:
235
236

    :default: on
237

238
    Enables the common-sub-expression elimination
239
240
241
    optimisation. Switching this off can be useful if you have some
    ``unsafePerformIO`` expressions that you don't want commoned-up.

242
.. ghc-flag:: -fstg-cse
243
244
245
246
247
    :shortdesc: Enable common sub-expression elimination on the STG
        intermediate language
    :type: dynamic
    :reverse: -fno-stg-cse
    :category:
248
249
250
251
252
253
254

    :default: on

    Enables the common-sub-expression elimination optimisation on the STG
    intermediate language, where it is able to common up some subexpressions
    that differ in their types, but not their represetation.

255
.. ghc-flag:: -fdicts-cheap
256
257
258
259
    :shortdesc: Make dictionary-valued expressions seem cheap to the optimiser.
    :type: dynamic
    :reverse: -fno-dicts-cheap
    :category:
260

261
262
    :default: off

263
264
265
    A very experimental flag that makes dictionary-valued expressions
    seem cheap to the optimiser.

266
.. ghc-flag:: -fdicts-strict
267
268
269
270
    :shortdesc: Make dictionaries strict
    :type: dynamic
    :reverse: -fno-dicts-strict
    :category:
271

272
273
    :default: off

274
275
    Make dictionaries strict.

276
.. ghc-flag:: -fdmd-tx-dict-sel
277
278
279
280
281
    :shortdesc: Use a special demand transformer for dictionary selectors.
        Always enabled by default.
    :type: dynamic
    :reverse: -fno-dmd-tx-dict-sel
    :category:
282

283
    :default: on
284
285
286

    Use a special demand transformer for dictionary selectors.

287
.. ghc-flag:: -fdo-eta-reduction
288
289
290
291
    :shortdesc: Enable eta-reduction. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-do-eta-reduction
    :category:
292

293
    :default: on
294

295
296
    Eta-reduce lambda expressions, if doing so gets rid of a whole group of
    lambdas.
297

298
.. ghc-flag:: -fdo-lambda-eta-expansion
299
300
301
302
    :shortdesc: Enable lambda eta-expansion. Always enabled by default.
    :type: dynamic
    :reverse: -fno-do-lambda-eta-expansion
    :category:
303

304
305
306
307
308
    :default: on

    Eta-expand let-bindings to increase their arity.

.. ghc-flag:: -feager-blackholing
309
310
311
    :shortdesc: Turn on :ref:`eager blackholing <parallel-compile-options>`
    :type: dynamic
    :category:
312

313
314
    :default: off

315
316
317
    Usually GHC black-holes a thunk only when it switches threads. This
    flag makes it do so as soon as the thunk is entered. See `Haskell on
    a shared-memory
318
    multiprocessor <http://community.haskell.org/~simonmar/papers/multiproc.pdf>`__.
319

320
321
    See :ref:`parallel-compile-options` for a dicussion on its use.

322
.. ghc-flag:: -fexcess-precision
323
324
325
326
    :shortdesc: Enable excess intermediate precision
    :type: dynamic
    :reverse: -fno-excess-precision
    :category:
327

328
329
    :default: off

330
331
332
333
334
335
336
337
338
339
340
    When this option is given, intermediate floating point values can
    have a *greater* precision/range than the final type. Generally this
    is a good thing, but some programs may rely on the exact
    precision/range of ``Float``/``Double`` values and should not use
    this option for their compilation.

    Note that the 32-bit x86 native code generator only supports
    excess-precision mode, so neither ``-fexcess-precision`` nor
    ``-fno-excess-precision`` has any effect. This is a known bug, see
    :ref:`bugs-ghc`.

341
.. ghc-flag:: -fexpose-all-unfoldings
342
343
344
345
    :shortdesc: Expose all unfoldings, even for very large or recursive functions.
    :type: dynamic
    :reverse: -fno-expose-all-unfoldings
    :category:
346

347
348
    :default: off

349
350
351
352
    An experimental flag to expose all unfoldings, even for very large
    or recursive functions. This allows for all functions to be inlined
    while usually GHC would avoid inlining larger functions.

353
.. ghc-flag:: -ffloat-in
354
355
356
357
    :shortdesc: Turn on the float-in transformation. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-float-in
    :category:
358
359

    :default: on
360

361
    Float let-bindings inwards, nearer their binding
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    site. See `Let-floating: moving bindings to give faster programs
    (ICFP'96) <http://research.microsoft.com/en-us/um/people/simonpj/papers/float.ps.gz>`__.

    This optimisation moves let bindings closer to their use site. The
    benefit here is that this may avoid unnecessary allocation if the
    branch the let is now on is never executed. It also enables other
    optimisation passes to work more effectively as they have more
    information locally.

    This optimisation isn't always beneficial though (so GHC applies
    some heuristics to decide when to apply it). The details get
    complicated but a simple example is that it is often beneficial to
    move let bindings outwards so that multiple let bindings can be
    grouped into a larger single let binding, effectively batching their
    allocation and helping the garbage collector and allocator.

378
.. ghc-flag:: -ffull-laziness
379
380
381
382
383
    :shortdesc: Turn on full laziness (floating bindings outwards).
        Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-full-laziness
    :category:
384
385

    :default: on
386

387
    Run the full laziness optimisation (also known as
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
    let-floating), which floats let-bindings outside enclosing lambdas,
    in the hope they will be thereby be computed less often. See
    `Let-floating: moving bindings to give faster programs
    (ICFP'96) <http://research.microsoft.com/en-us/um/people/simonpj/papers/float.ps.gz>`__.
    Full laziness increases sharing, which can lead to increased memory
    residency.

    .. note::
       GHC doesn't implement complete full-laziness. When
       optimisation in on, and ``-fno-full-laziness`` is not given, some
       transformations that increase sharing are performed, such as
       extracting repeated computations from a loop. These are the same
       transformations that a fully lazy implementation would do, the
       difference is that GHC doesn't consistently apply full-laziness, so
       don't rely on it.

404
.. ghc-flag:: -ffun-to-thunk
405
406
407
408
409
    :shortdesc: Allow worker-wrapper to convert a function closure into a thunk
        if the function does not use any of its arguments. Off by default.
    :type: dynamic
    :reverse: -fno-fun-to-thunk
    :category:
410
411

    :default: off
412
413
414
415

    Worker-wrapper removes unused arguments, but usually we do not
    remove them all, lest it turn a function closure into a thunk,
    thereby perhaps creating a space leak and/or disrupting inlining.
416
    This flag allows worker/wrapper to remove *all* value lambdas.
417

418
.. ghc-flag:: -fignore-asserts
419
420
421
422
    :shortdesc: Ignore assertions in the source. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-ignore-asserts
    :category:
423

424
    :default: on
425

426
427
428
429
430
    Causes GHC to ignore uses of the function ``Exception.assert`` in source
    code (in other words, rewriting ``Exception.assert p e`` to ``e`` (see
    :ref:`assertions`).

.. ghc-flag:: -fignore-interface-pragmas
431
432
433
434
    :shortdesc: Ignore pragmas in interface files. Implied by :ghc-flag:`-O0` only.
    :type: dynamic
    :reverse: -fno-ignore-interface-pragmas
    :category:
435

436
437
    :default: off

438
    Tells GHC to ignore all inessential information when reading
439
    interface files. That is, even if :file:`M.hi` contains unfolding or
440
441
442
    strictness information for a function, GHC will ignore that
    information.

443
.. ghc-flag:: -flate-dmd-anal
444
445
446
447
448
    :shortdesc: Run demand analysis again, at the end of the
        simplification pipeline
    :type: dynamic
    :reverse: -fno-late-dmd-anal
    :category:
449

450
451
    :default: off

452
453
454
    Run demand analysis again, at the end of the simplification
    pipeline. We found some opportunities for discovering strictness
    that were not visible earlier; and optimisations like
455
    :ghc-flag:`-fspec-constr` can create functions with unused arguments which
456
457
458
    are eliminated by late demand analysis. Improvements are modest, but
    so is the cost. See notes on the :ghc-wiki:`Trac wiki page <LateDmd>`.

459
.. ghc-flag:: -fliberate-case
460
461
462
463
    :shortdesc: Turn on the liberate-case transformation. Implied by :ghc-flag:`-O2`.
    :type: dynamic
    :reverse: -fno-liberate-case
    :category:
464

465
466
467
468
469
470
    :default: off but enabled with :ghc-flag:`-O2`.

    Turn on the liberate-case transformation. This unrolls recursive function
    once in its own RHS, to avoid repeated case analysis of free variables. It's
    a bit like the call-pattern specialiser (:ghc-flag:`-fspec-constr`) but for
    free variables rather than arguments.
471

472
.. ghc-flag:: -fliberate-case-threshold=⟨n⟩
473
474
475
476
477
    :shortdesc: *default: 2000.* Set the size threshold for the liberate-case
        transformation to ⟨n⟩
    :type: dynamic
    :reverse: -fno-liberate-case-threshold
    :category:
478

479
    :default: 2000
480

481
    Set the size threshold for the liberate-case transformation.
482

483
.. ghc-flag:: -floopification
484
485
486
487
488
    :shortdesc: Turn saturated self-recursive tail-calls into local jumps in the
        generated assembly. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-loopification
    :category:
489
490

    :default: on
491
492
493
494
495

    When this optimisation is enabled the code generator will turn all
    self-recursive saturated tail calls into local jumps rather than
    function calls.

496
497
498
499
500
501
502
503
504
505
506
507
.. ghc-flag:: -fllvm-pass-vectors-in-regs
    :shortdesc: Pass vector value in vector registers for function calls
    :type: dynamic
    :reverse: -fno-llvm-pass-vectors-in-regs
    :category:

    :default: on

    Instructs GHC to use the platform's native vector registers to pass vector
    arguments during function calls. As with all vector support, this requires
    :ghc-flag:`-fllvm`.

508
.. ghc-flag:: -fmax-inline-alloc-size=⟨n⟩
509
510
511
512
    :shortdesc: *default: 128.* Set the maximum size of inline array allocations
        to ⟨n⟩ bytes (default: 128).
    :type: dynamic
    :category:
513
514

    :default: 128
515

516
    Set the maximum size of inline array allocations to n bytes.
517
518
519
520
    GHC will allocate non-pinned arrays of statically known size in the current
    nursery block if they're no bigger than n bytes, ignoring GC overheap. This
    value should be quite a bit smaller than the block size (typically: 4096).

521
.. ghc-flag:: -fmax-inline-memcpy-insns=⟨n⟩
522
523
524
525
    :shortdesc: *default: 32.* Inline ``memcpy`` calls if they would generate no
        more than ⟨n⟩ pseudo instructions.
    :type: dynamic
    :category:
526

527
    :default: 32
528

529
    Inline ``memcpy`` calls if they would generate no more than ⟨n⟩ pseudo-instructions.
530

531
.. ghc-flag:: -fmax-inline-memset-insns=⟨n⟩
532
533
534
535
    :shortdesc: *default: 32.* Inline ``memset`` calls if they would generate no
        more than ⟨n⟩ pseudo instructions
    :type: dynamic
    :category:
536
537
538
539

    :default: 32

    Inline ``memset`` calls if they would generate no more than n pseudo
540
541
    instructions.

542
.. ghc-flag:: -fmax-relevant-binds=⟨n⟩
543
544
545
546
    :shortdesc: *default: 6.* Set the maximum number of bindings to display in
        type error messages.
    :type: dynamic
    :reverse: -fno-max-relevant-bindings
547
    :category: verbosity
548
549

    :default: 6
550
551
552

    The type checker sometimes displays a fragment of the type
    environment in error messages, but only up to some maximum number,
553
    set by this flag. Turning it off with
554
555
556
557
558
    ``-fno-max-relevant-bindings`` gives an unlimited number.
    Syntactically top-level bindings are also usually excluded (since
    they may be numerous), but ``-fno-max-relevant-bindings`` includes
    them too.

559
.. ghc-flag:: -fmax-uncovered-patterns=⟨n⟩
560
561
562
563
    :shortdesc: *default: 4.* Set the maximum number of patterns to display in
        warnings about non-exhaustive ones.
    :type: dynamic
    :category:
564
565
566
567
568
569

    :default: 4

    Maximum number of unmatched patterns to be shown in warnings generated by
    :ghc-flag:`-Wincomplete-patterns` and :ghc-flag:`-Wincomplete-uni-patterns`.

570
.. ghc-flag:: -fmax-simplifier-iterations=⟨n⟩
571
572
573
    :shortdesc: *default: 4.* Set the max iterations for the simplifier.
    :type: dynamic
    :category:
574

575
    :default: 4
576

577
    Sets the maximal number of iterations for the simplifier.
578

579
.. ghc-flag:: -fmax-worker-args=⟨n⟩
580
581
582
583
    :shortdesc: *default: 10.* If a worker has that many arguments, none will
        be unpacked anymore.
    :type: dynamic
    :category:
584

585
586
587
588
589
    :default: 10

    If a worker has that many arguments, none will be unpacked anymore.

.. ghc-flag:: -fno-opt-coercion
590
591
592
    :shortdesc: Turn off the coercion optimiser
    :type: dynamic
    :category:
593

594
    :default: coercion optimisation enabled.
595

596
597
    Turn off the coercion optimiser.

598
.. ghc-flag:: -fno-pre-inlining
599
600
601
    :shortdesc: Turn off pre-inlining
    :type: dynamic
    :category:
602

603
    :default: pre-inlining enabled
604

605
606
    Turn off pre-inlining.

607
.. ghc-flag:: -fno-state-hack
608
609
610
611
612
    :shortdesc: Turn off the \state hack\ whereby any lambda with a real-world
        state token as argument is considered to be single-entry. Hence
        OK to inline things inside it.
    :type: dynamic
    :category:
613

614
    :default: state hack is enabled
615

616
617
    Turn off the "state hack" whereby any lambda with a ``State#`` token
    as argument is considered to be single-entry, hence it is considered
618
    okay to inline things inside it. This can improve performance of IO
619
620
    and ST monad code, but it runs the risk of reducing sharing.

621
.. ghc-flag:: -fomit-interface-pragmas
622
623
624
625
    :shortdesc: Don't generate interface pragmas. Implied by :ghc-flag:`-O0` only.
    :type: dynamic
    :reverse: -fno-omit-interface-pragmas
    :category:
626

627
    :default: Implied by :ghc-flag:`-O0`, otherwise off.
628

629
630
631
632
633
634
635
636
637
    Tells GHC to omit all inessential information from the interface
    file generated for the module being compiled (say M). This means
    that a module importing M will see only the *types* of the functions
    that M exports, but not their unfoldings, strictness info, etc.
    Hence, for example, no function exported by M will be inlined into
    an importing module. The benefit is that modules that import M will
    need to be recompiled less often (only when M's exports change their
    type, not when they change their implementation).

638
.. ghc-flag:: -fomit-yields
639
640
641
642
    :shortdesc: Omit heap checks when no allocation is being performed.
    :type: dynamic
    :reverse: -fno-omit-yields
    :category:
643

644
    :default: yield points enabled
645
646

    Tells GHC to omit heap checks when no allocation is
647
648
649
650
651
652
653
    being performed. While this improves binary sizes by about 5%, it
    also means that threads run in tight non-allocating loops will not
    get preempted in a timely fashion. If it is important to always be
    able to interrupt such threads, you should turn this optimization
    off. Consider also recompiling all libraries with this optimization
    turned off, if you need to guarantee interruptibility.

654
.. ghc-flag:: -fpedantic-bottoms
655
656
657
658
659
660
    :shortdesc: Make GHC be more precise about its treatment of bottom (but see
        also :ghc-flag:`-fno-state-hack`). In particular, GHC will not
        eta-expand through a case expression.
    :type: dynamic
    :reverse: -fno-pedantic-bottoms
    :category:
661

662
663
    :default: off

664
    Make GHC be more precise about its treatment of bottom (but see also
665
    :ghc-flag:`-fno-state-hack`). In particular, stop GHC eta-expanding through
666
667
668
    a case expression, which is good for performance, but bad if you are
    using ``seq`` on partial applications.

669
.. ghc-flag:: -fregs-graph
670
671
672
673
674
    :shortdesc: Use the graph colouring register allocator for register
        allocation in the native code generator. Implied by :ghc-flag:`-O2`.
    :type: dynamic
    :reverse: -fno-regs-graph
    :category:
675

676
677
678
679
680
681
682
683
684
685
    :default: off due to a performance regression bug (:ghc-ticket:`7679`)

    *Only applies in combination with the native code generator.* Use the graph
    colouring register allocator for register allocation in the native code
    generator. By default, GHC uses a simpler, faster linear register allocator.
    The downside being that the linear register allocator usually generates
    worse code.

    Note that the graph colouring allocator is a bit experimental and may fail
    when faced with code with high register pressure :ghc-ticket:`8657`.
686

687
.. ghc-flag:: -fregs-iterative
688
689
690
691
692
    :shortdesc: Use the iterative coalescing graph colouring register allocator
        in the native code generator.
    :type: dynamic
    :reverse: -fno-regs-iterative
    :category:
693

694
695
696
697
698
699
700
    :default: off

    *Only applies in combination with the native code generator.* Use the
    iterative coalescing graph colouring register allocator for register
    allocation in the native code generator. This is the same register allocator
    as the :ghc-flag:`-fregs-graph` one but also enables iterative coalescing
    during register allocation.
701

702
.. ghc-flag:: -fsimplifier-phases=⟨n⟩
703
704
705
706
    :shortdesc: *default: 2.* Set the number of phases for the simplifier.
        Ignored with :ghc-flag:`-O0`.
    :type: dynamic
    :category:
707

708
    :default: 2
709

710
    Set the number of phases for the simplifier. Ignored with ``-O0``.
711

712
.. ghc-flag:: -fsimpl-tick-factor=⟨n⟩
713
714
715
    :shortdesc: *default: 100.* Set the percentage factor for simplifier ticks.
    :type: dynamic
    :category:
716
717
718
719

    :default: 100

    GHC's optimiser can diverge if you write rewrite rules
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
    (:ref:`rewrite-rules`) that don't terminate, or (less satisfactorily)
    if you code up recursion through data types (:ref:`bugs-ghc`). To
    avoid making the compiler fall into an infinite loop, the optimiser
    carries a "tick count" and stops inlining and applying rewrite rules
    when this count is exceeded. The limit is set as a multiple of the
    program size, so bigger programs get more ticks. The
    ``-fsimpl-tick-factor`` flag lets you change the multiplier. The
    default is 100; numbers larger than 100 give more ticks, and numbers
    smaller than 100 give fewer.

    If the tick-count expires, GHC summarises what simplifier steps it
    has done; you can use ``-fddump-simpl-stats`` to generate a much
    more detailed list. Usually that identifies the loop quite
    accurately, because some numbers are very large.

735
.. ghc-flag:: -fspec-constr
736
737
738
739
    :shortdesc: Turn on the SpecConstr transformation. Implied by :ghc-flag:`-O2`.
    :type: dynamic
    :reverse: -fno-spec-constr
    :category:
740

741
742
743
744
    :default: off but enabled by :ghc-flag:`-O2`.

    Turn on call-pattern specialisation; see `Call-pattern specialisation for
    Haskell programs
Simon Peyton Jones's avatar
Simon Peyton Jones committed
745
    <https://www.microsoft.com/en-us/research/publication/system-f-with-type-equality-coercions-2/>`__.
746
747

    This optimisation specializes recursive functions according to their
748
    argument "shapes". This is best explained by example so consider: ::
749
750
751
752
753
754
755
756

        last :: [a] -> a
        last [] = error "last"
        last (x : []) = x
        last (x : xs) = last xs

    In this code, once we pass the initial check for an empty list we
    know that in the recursive case this pattern match is redundant. As
757
    such ``-fspec-constr`` will transform the above code to: ::
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776

        last :: [a] -> a
        last []       = error "last"
        last (x : xs) = last' x xs
            where
              last' x []       = x
              last' x (y : ys) = last' y ys

    As well avoid unnecessary pattern matching it also helps avoid
    unnecessary allocation. This applies when a argument is strict in
    the recursive call to itself but not on the initial entry. As strict
    recursive branch of the function is created similar to the above
    example.

    It is also possible for library writers to instruct GHC to perform
    call-pattern specialisation extremely aggressively. This is
    necessary for some highly optimized libraries, where we may want to
    specialize regardless of the number of specialisations, or the size
    of the code. As an example, consider a simplified use-case from the
777
    ``vector`` library: ::
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802

        import GHC.Types (SPEC(..))

        foldl :: (a -> b -> a) -> a -> Stream b -> a
        {-# INLINE foldl #-}
        foldl f z (Stream step s _) = foldl_loop SPEC z s
          where
            foldl_loop !sPEC z s = case step s of
                                    Yield x s' -> foldl_loop sPEC (f z x) s'
                                    Skip       -> foldl_loop sPEC z s'
                                    Done       -> z

    Here, after GHC inlines the body of ``foldl`` to a call site, it
    will perform call-pattern specialisation very aggressively on
    ``foldl_loop`` due to the use of ``SPEC`` in the argument of the
    loop body. ``SPEC`` from ``GHC.Types`` is specifically recognised by
    the compiler.

    (NB: it is extremely important you use ``seq`` or a bang pattern on
    the ``SPEC`` argument!)

    In particular, after inlining this will expose ``f`` to the loop
    body directly, allowing heavy specialisation over the recursive
    cases.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
803
.. ghc-flag:: -fspec-constr-keen
804
805
806
807
808
    :shortdesc: Specialize a call with an explicit constructor argument,
        even if the argument is not scrutinised in the body of the function
    :type: dynamic
    :reverse: -fno-spec-constr-keen
    :category:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
809
810
811

    :default: off

812
813
    If this flag is on, call-pattern specialisation will specialise a call
    ``(f (Just x))`` with an explicit constructor argument, even if the argument
Simon Peyton Jones's avatar
Simon Peyton Jones committed
814
815
816
817
    is not scrutinised in the body of the function. This is sometimes
    beneficial; e.g. the argument might be given to some other function
    that can itself be specialised.

818
.. ghc-flag:: -fspec-constr-count=⟨n⟩
819
820
821
822
823
824
    :shortdesc: default: 3.* Set to ⟨n⟩ the maximum number of specialisations that
        will be created for any one function by the SpecConstr
        transformation.
    :type: dynamic
    :reverse: -fno-spec-constr-count
    :category:
825
826

    :default: 3
827

828
    Set the maximum number of specialisations that will be created for
829
830
    any one function by the SpecConstr transformation.

831
.. ghc-flag:: -fspec-constr-threshold=⟨n⟩
832
833
834
835
836
    :shortdesc: *default: 2000.* Set the size threshold for the SpecConstr
        transformation to ⟨n⟩.
    :type: dynamic
    :reverse: -fno-spec-constr-threshold
    :category:
837

838
    :default: 2000
839

840
841
842
    Set the size threshold for the SpecConstr transformation.

.. ghc-flag:: -fspecialise
843
844
845
846
    :shortdesc: Turn on specialisation of overloaded functions. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-specialise
    :category:
847
848

    :default: on
849

850
    Specialise each type-class-overloaded function
851
    defined in this module for the types at which it is called in this
852
    module. If :ghc-flag:`-fcross-module-specialise` is set imported functions
853
854
855
    that have an INLINABLE pragma (:ref:`inlinable-pragma`) will be
    specialised as well.

856
.. ghc-flag:: -fspecialise-aggressively
857
858
859
860
861
    :shortdesc: Turn on specialisation of overloaded functions regardless of
        size, if unfolding is available
    :type: dynamic
    :reverse: -fno-specialise-aggressively
    :category:
862
863
864
865
866
867
868
869
870
871
872

    :default: off

    By default only type class methods and methods marked ``INLINABLE`` or
    ``INLINE`` are specialised. This flag will specialise any overloaded function
    regardless of size if its unfolding is available. This flag is not
    included in any optimisation level as it can massively increase code
    size. It can be used in conjunction with :ghc-flag:`-fexpose-all-unfoldings`
    if you want to ensure all calls are specialised.


873
.. ghc-flag:: -fcross-module-specialise
874
875
876
877
878
    :shortdesc: Turn on specialisation of overloaded functions imported from
        other modules.
    :type: dynamic
    :reverse: -fno-cross-module-specialise
    :category:
879
880

    :default: on
881

882
    Specialise ``INLINABLE`` (:ref:`inlinable-pragma`)
883
884
885
886
    type-class-overloaded functions imported from other modules for the types at
    which they are called in this module. Note that specialisation must be
    enabled (by ``-fspecialise``) for this to have any effect.

887
888
889
890
891
892
893
894
895
896
897
898
899
900
.. ghc-flag:: -flate-specialise
    :shortdesc: Run a late specialisation pass
    :type: dynamic
    :reverse: -fno-late-specialise
    :default: off

    Runs another specialisation pass towards the end of the optimisation
    pipeline. This can catch specialisation opportunities which arose from
    the previous specialisation pass or other inlining.

    You might want to use this if you are you have a type class method
    which returns a constrained type. For example, a type class where one
    of the methods implements a traversal.

901
.. ghc-flag:: -fsolve-constant-dicts
902
903
904
905
906
    :shortdesc: When solving constraints, try to eagerly solve
        super classes using available dictionaries.
    :type: dynamic
    :reverse: -fno-solve-constant-dicts
    :category:
907

908
    :default: on
909
910

    When solving constraints, try to eagerly solve
911
    super classes using available dictionaries.
912
913
914
915
916
917
918
919
920
921
922
923
924
925

    For example::

      class M a b where m :: a -> b

      type C a b = (Num a, M a b)

      f :: C Int b => b -> Int -> Int
      f _ x = x + 1

    The body of `f` requires a `Num Int` instance. We could solve this
    constraint from the context  because we have `C Int b` and that provides us
    a
    solution for `Num Int`. However, we can often produce much better code
926
    by directly solving for an available `Num Int` dictionary we might have at
927
928
929
930
931
932
933
934
935
936
    hand. This removes potentially many layers of indirection and crucially
    allows other optimisations to fire as the dictionary will be statically
    known and selector functions can be inlined.

    The optimisation also works for GADTs which bind dictionaries. If we
    statically know which class dictionary we need then we will solve it
    directly rather than indirectly using the one passed in at run time.



937
.. ghc-flag:: -fstatic-argument-transformation
938
939
940
941
    :shortdesc: Turn on the static argument transformation.
    :type: dynamic
    :reverse: -fno-static-argument-transformation
    :category:
942

943
944
    :default: off

945
946
947
948
949
    Turn on the static argument transformation, which turns a recursive
    function into a non-recursive one with a local recursive loop. See
    Chapter 7 of `Andre Santos's PhD
    thesis <http://research.microsoft.com/en-us/um/people/simonpj/papers/santos-thesis.ps.gz>`__

950
.. ghc-flag:: -fstrictness
951
952
953
954
955
    :shortdesc: Turn on strictness analysis.
        Implied by :ghc-flag:`-O`. Implies :ghc-flag:`-fworker-wrapper`
    :type: dynamic
    :reverse: -fno-strictness
    :category:
956

957
958
    :default: on

959
960
    Switch on the strictness analyser. The
    implementation is described in the paper `Theory and Practice of Demand Analysis in Haskell`<https://www.microsoft.com/en-us/research/wp-content/uploads/2017/03/demand-jfp-draft.pdf>`__.
961
962
963
964
965
966
967
968

    The strictness analyser figures out when arguments and variables in
    a function can be treated 'strictly' (that is they are always
    evaluated in the function at some point). This allow GHC to apply
    certain optimisations such as unboxing that otherwise don't apply as
    they change the semantics of the program when applied to lazy
    arguments.

969
.. ghc-flag:: -fstrictness-before=⟨n⟩
970
971
972
    :shortdesc: Run an additional strictness analysis before simplifier phase ⟨n⟩
    :type: dynamic
    :category:
973
974
975

    Run an additional strictness analysis before simplifier phase ⟨n⟩.

976
.. ghc-flag:: -funbox-small-strict-fields
977
978
979
980
981
    :shortdesc: Flatten strict constructor fields with a pointer-sized
        representation. Implied by :ghc-flag:`-O`.
    :type: dynamic
    :reverse: -fno-unbox-small-strict-fields
    :category:
982
983
984

    :default: on

985
986
987
988
    .. index::
       single: strict constructor fields
       single: constructor fields, strict

989
    This option causes all constructor fields which
990
991
992
993
994
    are marked strict (i.e. “!”) and which representation is smaller or
    equal to the size of a pointer to be unpacked, if possible. It is
    equivalent to adding an ``UNPACK`` pragma (see :ref:`unpack-pragma`)
    to every strict constructor field that fulfils the size restriction.

995
    For example, the constructor fields in the following data types ::
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015

        data A = A !Int
        data B = B !A
        newtype C = C B
        data D = D !C

    would all be represented by a single ``Int#`` (see
    :ref:`primitives`) value with ``-funbox-small-strict-fields``
    enabled.

    This option is less of a sledgehammer than
    ``-funbox-strict-fields``: it should rarely make things worse. If
    you use ``-funbox-small-strict-fields`` to turn on unboxing by
    default you can disable it for certain constructor fields using the
    ``NOUNPACK`` pragma (see :ref:`nounpack-pragma`).

    Note that for consistency ``Double``, ``Word64``, and ``Int64``
    constructor fields are unpacked on 32-bit platforms, even though
    they are technically larger than a pointer on those platforms.

1016
.. ghc-flag:: -funbox-strict-fields
1017
1018
1019
1020
    :shortdesc: Flatten strict constructor fields
    :type: dynamic
    :reverse: -fno-unbox-strict-fields
    :category:
1021

1022
1023
    :default: off

1024
1025
1026
1027
1028
    .. index::
       single: strict constructor fields
       single: constructor fields, strict

    This option causes all constructor fields which are marked strict
1029
    (i.e. ``!``) to be unpacked if possible. It is equivalent to adding an
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
    ``UNPACK`` pragma to every strict constructor field (see
    :ref:`unpack-pragma`).

    This option is a bit of a sledgehammer: it might sometimes make
    things worse. Selectively unboxing fields by using ``UNPACK``
    pragmas might be better. An alternative is to use
    ``-funbox-strict-fields`` to turn on unboxing by default but disable
    it for certain constructor fields using the ``NOUNPACK`` pragma (see
    :ref:`nounpack-pragma`).

1040
1041
1042
    Alternatively you can use :ghc-flag:`-funbox-small-strict-fields` to only
    unbox strict fields which are "small".

1043
.. ghc-flag:: -funfolding-creation-threshold=⟨n⟩
1044
1045
1046
    :shortdesc: *default: 750.* Tweak unfolding settings.
    :type: dynamic
    :category:
1047
1048
1049

    :default: 750

1050
1051
1052
1053
    .. index::
       single: inlining, controlling
       single: unfolding, controlling

1054
    Governs the maximum size that GHC will allow a
1055
1056
1057
1058
1059
    function unfolding to be. (An unfolding has a “size” that reflects
    the cost in terms of “code bloat” of expanding (aka inlining) that
    unfolding at a call site. A bigger function would be assigned a
    bigger cost.)

1060
1061
1062
1063
    Consequences:

    a. nothing larger than this will be inlined (unless it has an ``INLINE`` pragma)
    b. nothing larger than this will be spewed into an interface file.
1064

1065
1066
    Increasing this figure is more likely to result in longer compile times
    than faster code. The :ghc-flag:`-funfolding-use-threshold=⟨n⟩` is more
1067
1068
    useful.

1069
.. ghc-flag:: -funfolding-dict-discount=⟨n⟩
1070
1071
1072
    :shortdesc: *default: 30.* Tweak unfolding settings.
    :type: dynamic
    :category:
1073
1074
1075

    :default: 30

1076
1077
1078
1079
    .. index::
       single: inlining, controlling
       single: unfolding, controlling

1080
1081
    How eager should the compiler be to inline dictionaries?

1082
.. ghc-flag:: -funfolding-fun-discount=⟨n⟩
1083
1084
1085
    :shortdesc: *default: 60.* Tweak unfolding settings.
    :type: dynamic
    :category:
1086
1087

    :default: 60
1088
1089
1090
1091
1092

    .. index::
       single: inlining, controlling
       single: unfolding, controlling

1093
1094
    How eager should the compiler be to inline functions?

1095
.. ghc-flag:: -funfolding-keeness-factor=⟨n⟩
1096
1097
1098
    :shortdesc: *default: 1.5.* Tweak unfolding settings.
    :type: dynamic
    :category:
1099
1100

    :default: 1.5
1101
1102
1103
1104
1105

    .. index::
       single: inlining, controlling
       single: unfolding, controlling

1106
1107
    How eager should the compiler be to inline functions?

1108
.. ghc-flag:: -funfolding-use-threshold=⟨n⟩
1109
1110
1111
    :shortdesc: *default: 60.* Tweak unfolding settings.
    :type: dynamic
    :category:
1112
1113

    :default: 60
1114
1115
1116
1117
1118

    .. index::
       single: inlining, controlling
       single: unfolding, controlling

1119
    This is the magic cut-off figure for unfolding (aka
1120
1121
1122
1123
1124
1125
    inlining): below this size, a function definition will be unfolded
    at the call-site, any bigger and it won't. The size computed for a
    function depends on two things: the actual size of the expression
    minus any discounts that apply depending on the context into which
    the expression is to be inlined.

1126
1127
1128
1129
1130
    The difference between this and
    :ghc-flag:`-funfolding-creation-threshold=⟨n⟩` is that this one determines
    if a function definition will be inlined *at a call site*. The other option
    determines if a function definition will be kept around at all for
    potential inlining.
1131

1132
.. ghc-flag:: -fvectorisation-avoidance
1133
1134
1135
1136
    :shortdesc: Enable vectorisation avoidance. Always enabled by default.
    :type: dynamic
    :reverse: -fno-vectorisation-avoidance
    :category:
1137
1138
1139

    :default: on

1140
1141
1142
1143
1144
    .. index::
       single: -fvectorisation-avoidance

    Part of :ref:`Data Parallel Haskell (DPH) <dph>`.

1145
    Enable the *vectorisation* avoidance optimisation.
1146
1147
1148
1149
1150
1151
1152
1153
    This optimisation only works when used in combination with the
    ``-fvectorise`` transformation.

    While vectorisation of code using DPH is often a big win, it can
    also produce worse results for some kinds of code. This optimisation
    modifies the vectorisation transformation to try to determine if a
    function would be better of unvectorised and if so, do just that.

1154
.. ghc-flag:: -fvectorise
1155
1156
1157
1158
    :shortdesc: Enable vectorisation of nested data parallelism
    :type: dynamic
    :reverse: -fno-vectorise
    :category:
1159
1160

    :default: off
1161
1162
1163

    Part of :ref:`Data Parallel Haskell (DPH) <dph>`.

1164
    Enable the *vectorisation* optimisation
1165
1166
1167
1168
    transformation. This optimisation transforms the nested data
    parallelism code of programs using DPH into flat data parallelism.
    Flat data parallel programs should have better load balancing,
    enable SIMD parallelism and friendlier cache behaviour.