7.3. 最適化 (コードの改善)

-O* オプションば便利な最適化フラグの「詰め合わせ」を指定するのに使います. 個別の 最適化を有効/無効にするには,後述する -f* オプションを使います. マシン固有 の最適化を有効/無効にするには -m* オプションを使います.

こうしたオプションのほとんどは,オプションをオン/オフする論理値になっています(オフにする場合は no- が前置されます). -fspecialise は特定化を有効にし,-fno-specialise は無効にします. 同じオプションに関して複数のフラグが1つのコマンドラインにあらわれたときは左から右への順で評価されますので, -fno-specialise -fspecialise という指定では,特定化は有効になります.

-O* という型のフラグは大まかにいって -f* という型のフラグの組み合わせを指定しているものになっているということに注意をしてください. したがって -O* フラグと -f* フラグの効果はコマンドライン中にあらわれる順番に依存します.

-fno-specialise -O1 を例にとってみましょう. コマンドラインに -fno-specialise があっても,特定化(specialisation)は有効になります. これは -O1-fspecialise を有効にするので,先に指定したフラグを上書きしてしまいます. これとは対照的に -O1 -fno-specialise のようにすると予想どおり特定化は発動しません.

7.3.1. -O*: 便利な最適化フラグの「詰め合わせ」

GHCが生成するコードの質に影響を与えるオプションは 大量に あります. ほとんどの人にとっては,最適化の目標は「素早くコンパイルする」とか「電光石火のごとく走るプログラムコードを生成する」など一般的なものです. したがって,以下にしめすような最適化の「詰め合わせ」を指定(あるいは指定しない)する選択をするだけで十分です.

最適化のレベルを高くすると,モジュールを跨ぐ最適化が増えます. これは,ソースコードを変更したときにどの程度の再コンパイルする必要があるかに大きく影響します. これは開発中は最適化をしないようにすることの理由の1つです.

-O*

このフラグの意味は「速くコンパイルしてね,生成したコードのインスタンスについてはうるさいことは言わないから」です. たとえば ghc -c Foo.hs のようにします.

-O0

「すべての最適化を無効にする」という意味です. -O``オプションを全く指定しないのと同じ状態にするということです. わざわざ ``-O0 を指定するのは make が既に -O オプションを指定してしまっているときに便利です.

-O
-O1

「高品質のコードをそれほど時間をかけないで生成する」という意味です. ghc -c -O Main.lhs のように使います.

-O2

「危険のない最適化をすべて適用する.コンパイルにかなりの時間を書けてもよい」という意味です.

ここで回避しようとしている「危険な」最適化とは,運が悪ければ,実行時における時間・空間性能を 悪化させる 可能性があるということです. 通常これらの最適化は個別に指定します.

-Odph

すべての -O2 の最適化を有効にした上で -fmax-simplifier-iterations=20-fsimplifier-phases=3 を設定します. Data Parallel Haskell (DPH) を使うときように設計されました.

日常の作業で -O* フラグを使うことはありません. それなりの速度が必要なときには -O を使います. たとえば,何かを計測したいときなどです. ちょっと休憩したいときには -O2 を使い(たっぷりのコーヒーブレイクに行き)ます.

-O (など)の「実際の意味」を知りたければ -v を付ければいいでしょう. びっくりして,後ずさりすることになるでしょうね.

7.3.2. -f*: プラットフォーム非依存のフラグ

これらのフラグは個々の最適化を有効/無効にするのに使います. -O を使えば,「デフォルトで有効」となっているフラグをすべて有効にできます. したがって,明示的に指定する必要はないはずです. -fwombat というフラグの否定は -fno-wombat です.概略の一覧表は Individual optimisations を参照してください.

-fcase-merge
Default:有効

直接入れ子になった case 式の検査対象が同じ変数である場合,1つにまとめます. たとえば,

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

は以下のよう変換する.

case x of
   Red -> e1
   Blue -> e2
   Green -> e2
-fcall-arity
Default:有効

コール・アリティ解析を有効にします.

-fcmm-elim-common-blocks
Default:有効

コード生成器における共通ブロック除去を有効にします. この最適化の目的は,同一の Cmm ブロックを探し,それを除去します.

-fcmm-sink
Default:有効

コード生成器におけるシンキング(コード位置を後ろにずらすこと)のパスを有効にします. この最適化の目的は Cmm の同一のブロックを探すことです. その重複を除去すれば変数束縛を使う場所に近づけられます. このパスではリテラルやレジスタなどの単純な式を埋め込みます.

-fcpr-off

デマンド解析器における CPR 解析を無効にする.

-fcse
Default:有効

共通部分式除去の最適化を有効にします. 共通式としてまとめたくないような unsafePerformIO 式を使っている場合にはこれを無効にするのが便利です.

-fdicts-cheap

かなり実験的なフラグで,辞書を値にもつような式のコストを最適化器が安く見積るようにします.

-fdicts-strict

辞書を正格にします.

-fdmd-tx-dict-sel

オプション ``-O0`` , ``-O`` , ``-O2`` のもとではデフォルトで有効

辞書選択子ように特別な要求変換子を使います.

-fdo-eta-reduction
Default:有効

λ抽象式をη簡約することで,複数のλ抽象式をまとめて除去できるなら,そうします.

-fdo-lambda-eta-expansion
Default:有効

アリティを増やすために let 束縛をη展開します.

-feager-blackholing

通常 GHC はスレッドを切り替える場合にのみサンクをブラックホール化します. このフラグは,サンクに入ってすぐにこれを行うようにします. 以下を参照してください. Haskell on a shared-memory multiprocessor.

-fexcess-precision

このオプションを指定すると,中間の浮動小数点数が最終的な型よりも 大きな 精度/範囲をもつことを許すことになります. このことは一般的には良いことです. しかし Float/Double 値がその精度/範囲に正確におさまっていることに依存するプログラムが存在することもあり, そのようなプログラムにはこのオプションを指定してコンパイルしてはいけません.

32-bit x86 のネイティブコード生成器は excess-precision モードしかサポートしておらず -fexcess-precision-fno-excess-precision も効果を持ちません.これは既知のバグです. Bugs in GHC を参照してください.

-fexpose-all-unfoldings

実験的なフラグです.非常に大きな関数や再帰関数も含め,すべての展開を露出します. 通常GHCは大きい関数をインライン化することを避けますが,このフラグによって,全ての関数がインライン化可能になります.

-ffloat-in
Default:有効

let 束縛を内側,利用位置に近づく方向に移動します. Let-floating: moving bindings to give faster programs (ICFP‘96) を参照してください.

この最適化は let 束縛を仕様の位置に近づけます. こうすることの利点は,let の移動先の選択肢が実行されない場合,不要なメモリ領域確保を防ぐことができる点です. また,局所的により多くの情報が得られることになるので,他の最適化パスがより効率よく機能できることになります.

この最適化は常によい方向の効果があるというわけではありません. そういうわけで,GHC はこれを適用するかどうかをある種のヒューリスティクスを使って決定しています. 詳細は複雑ですが,この最適化がよい効果をもたらさない単純な例としては,let 束縛を外側に移動することで, 複数の束縛を1つの大きな束縛にまとめ,メモリ領域の確保を一度に行うことで,ガーベッジコレクタとアロケータが楽になるという場合です.

-ffull-laziness
Default:有効

完全遅延性最適化(let-floating ともいいます)を走らせます. これは let 束縛を計算が少くなるようにと願って,それを囲むλ抽象の外へ移動させることです. これについては Let-floating: moving bindings to give faster programs (ICFP‘96) を参照してください.共有を促進する完全遅延性はメモリの使用量を増加させることになります.

Note

GHC は完全遅延性を完全には実装していません. 最適化が有効で -fno-full-laziness が指定されていなければ, 共有を促進するある種の変換が実施されます. たとえば,ループの中から繰り返し計算される部分を抽出するといった変換です. この変換は完全遅延の実装で行われるのと同じものですが,GHC は常に完全遅延性を適用するとは限らないので,これに頼ってはいけません.

-ffun-to-thunk
Default:無効

worker-wrapper は使われていない引数を削除しますが,通常はクロージャをサンクにしてしまわないように,全部を削除することはしません. そんなことをしてしまうと,スペースリークしたり,インライン化の妨げになるからです. このフラグは worker/wrapper が すべての λ抽象値を削除できるようにします.

-fignore-asserts
Default:有効

ソースコード中で Exception.assert を使っていても,GHC はこれを無視し(すなわち Exception.assert p ee に書き換え)ます(Assertions を参照してください).

-fignore-interface-pragmas

インターフェイスファイルを読み込むときに不必要な情報はすべて無視するよう GHC に指示します. すなわち M.hi にある関数の展開情報や正格性情報があっても,GHC はこれらの情報を無視します.

-flate-dmd-anal

単純化パイプラインの最後に再度,要求解析(demand analysys)を走らせます. 前段階では見えなかった正格性を発見する場合があり -fspec-constr などの最適化によって作られた関数の未使用引数をこの後段階で取り除けることが判っています. 改善はささやかなものですが,コストもわずかです. Trac wiki page にある注も参照してください.

-fliberate-case

デフォルトでは無効,-O2で有効 liberate-case変換を有効にします. これは再帰関数をその右辺で1回展開して,自由変数がくりかえしcaseで検査されるのを回避します. これは,呼び出しパターンの特殊化(-fspec-constr)に似ていますが -fliberate-case は引数ではなく自由変数を対象にしています.

-fliberate-case-threshold=⟨n⟩
Default:2000

Set the size threshold for the liberate-case transformation.

-floopification
Default:on

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

-fmax-inline-alloc-size=⟨n⟩
Default:128

Set the maximum size of inline array allocations to n bytes. 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).

-fmax-inline-memcpy-insn=⟨n⟩
Default:32

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

-fmax-inline-memset-insns=⟨n⟩
Default:32

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

-fmax-relevant-binds=⟨n⟩
-fno-max-relevant-bindings
Default:6

The type checker sometimes displays a fragment of the type environment in error messages, but only up to some maximum number, set by this flag. Turning it off with -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.

-fmax-simplifier-iterations=⟨n⟩
Default:4

Sets the maximal number of iterations for the simplifier.

-fmax-worker-args=⟨n⟩
Default:10

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

-fno-opt-coercion

Turn off the coercion optimiser.

-fno-pre-inlining

Turn off pre-inlining.

-fno-state-hack

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

-fomit-interface-pragmas

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).

-fomit-yields
Default:on

Tells GHC to omit heap checks when no allocation is 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.

-fpedantic-bottoms

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

-fregs-graph

Off by default due to a performance regression bug. 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.

-fregs-iterative

Off by default, 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 -fregs-graph one but also enables iterative coalescing during register allocation.

-fsimplifier-phases=⟨n⟩
Default:2

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

-fsimpl-tick-factor=⟨n⟩
Default:100

GHC’s optimiser can diverge if you write rewrite rules (Rewrite rules) that don’t terminate, or (less satisfactorily) if you code up recursion through data types (Bugs in 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.

-fspec-constr

Off by default, but enabled by -O2. Turn on call-pattern specialisation; see Call-pattern specialisation for Haskell programs.

This optimisation specializes recursive functions according to their argument “shapes”. This is best explained by example so consider:

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 such -fspec-constr will transform the above code to:

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 vector library:

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.

-fspec-constr-count=⟨n⟩
Default:3

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

-fspec-constr-threshold=⟨n⟩
Default:2000

Set the size threshold for the SpecConstr transformation.

-fspecialise
Default:on

Specialise each type-class-overloaded function defined in this module for the types at which it is called in this module. If -fcross-module-specialise is set imported functions that have an INLINABLE pragma (INLINABLE pragma) will be specialised as well.

-fcross-module-specialise
Default:on

Specialise INLINABLE (INLINABLE pragma) 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.

-fstatic-argument-transformation

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

-fstrictness
Default:on

Switch on the strictness analyser. There is a very old paper about GHC’s strictness analyser, Measuring the effectiveness of a simple strictness analyser, but the current one is quite a bit different.

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.

-fstrictness-before=⟨n⟩

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

-funbox-small-strict-fields
Default:on

This option causes all constructor fields which 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 UNPACK pragma) to every strict constructor field that fulfils the size restriction.

For example, the constructor fields in the following data types

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 Unboxed types and primitive operations) 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 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.

-funbox-strict-fields

This option causes all constructor fields which are marked strict (i.e. !) to be unpacked if possible. It is equivalent to adding an UNPACK pragma to every strict constructor field (see 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 NOUNPACK pragma).

-funfolding-creation-threshold=⟨n⟩
Default:750

Governs the maximum size that GHC will allow a 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.)

Consequences:

  1. nothing larger than this will be inlined (unless it has an INLINE pragma)
  2. nothing larger than this will be spewed into an interface file.

Increasing this figure is more likely to result in longer compile times than faster code. The -funfolding-use-threshold is more useful.

-funfolding-dict-discount=⟨n⟩
Default:30

How eager should the compiler be to inline dictionaries?

-funfolding-fun-discount=⟨n⟩
Default:60

How eager should the compiler be to inline functions?

-funfolding-keeness-factor=⟨n⟩
Default:1.5

How eager should the compiler be to inline functions?

-funfolding-use-threshold=⟨n⟩
Default:60

This is the magic cut-off figure for unfolding (aka 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.

The difference between this and -funfolding-creation-threshold 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.

-fvectorisation-avoidance
Default:on

Part of Data Parallel Haskell (DPH).

Enable the vectorisation avoidance optimisation. 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.

-fvectorise
Default:off

Part of Data Parallel Haskell (DPH).

Enable the vectorisation optimisation 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.