btrbk: add mainProgram (#356350)
[NixPkgs.git] / pkgs / development / compilers / ghc / common-hadrian.nix
blobb062a2d514d4bd46016bbad14f3b2f0625db7e1c
1 { version
2 , rev ? null
3 , sha256
4 , url ?
5     if rev != null
6     then "https://gitlab.haskell.org/ghc/ghc.git"
7     else "https://downloads.haskell.org/ghc/${version}/ghc-${version}-src.tar.xz"
8 , postFetch ? null
9 }:
11 { lib
12 , stdenv
13 , stdenvNoCC
14 , pkgsBuildTarget
15 , pkgsHostTarget
16 , buildPackages
17 , targetPackages
18 , fetchpatch
20 # build-tools
21 , bootPkgs
22 , autoconf
23 , automake
24 , coreutils
25 , fetchurl
26 , fetchgit
27 , perl
28 , python3
29 , m4
30 , sphinx
31 , xattr
32 , autoSignDarwinBinariesHook
33 , bash
34 , srcOnly
36 , libiconv ? null, ncurses
37 , glibcLocales ? null
39 , # GHC can be built with system libffi or a bundled one.
40   libffi ? null
42 , useLLVM ? !(stdenv.targetPlatform.isx86
43               || stdenv.targetPlatform.isPower
44               || stdenv.targetPlatform.isSparc
45               || stdenv.targetPlatform.isAarch64
46               || stdenv.targetPlatform.isGhcjs)
47 , # LLVM is conceptually a run-time-only dependency, but for
48   # non-x86, we need LLVM to bootstrap later stages, so it becomes a
49   # build-time dependency too.
50   buildTargetLlvmPackages
51 , llvmPackages
53 , # If enabled, GHC will be built with the GPL-free but slightly slower native
54   # bignum backend instead of the faster but GPLed gmp backend.
55   enableNativeBignum ? !(lib.meta.availableOn stdenv.hostPlatform gmp
56                          && lib.meta.availableOn stdenv.targetPlatform gmp)
57                        || stdenv.targetPlatform.isGhcjs
58 , gmp
60 , # If enabled, use -fPIC when compiling static libs.
61   enableRelocatedStaticLibs ? stdenv.targetPlatform != stdenv.hostPlatform
63   # Exceeds Hydra output limit (at the time of writing ~3GB) when cross compiled to riscv64.
64   # A riscv64 cross-compiler fits into the limit comfortably.
65 , enableProfiledLibs ? !stdenv.hostPlatform.isRiscV64
67 , # Whether to build dynamic libs for the standard library (on the target
68   # platform). Static libs are always built.
69   enableShared ? with stdenv.targetPlatform; !isWindows && !useiOSPrebuilt && !isStatic && !isGhcjs
71 , # Whether to build terminfo.
72   # FIXME(@sternenseemann): This actually doesn't influence what hadrian does,
73   # just what buildInputs etc. looks like. It would be best if we could actually
74   # tell it what to do like it was possible with make.
75   enableTerminfo ? !(stdenv.targetPlatform.isWindows
76                      || stdenv.targetPlatform.isGhcjs
77                      # terminfo can't be built for cross
78                      || (stdenv.buildPlatform != stdenv.hostPlatform)
79                      || (stdenv.hostPlatform != stdenv.targetPlatform))
81 , # Libdw.c only supports x86_64, i686 and s390x as of 2022-08-04
82   enableDwarf ? (stdenv.targetPlatform.isx86 ||
83                  (stdenv.targetPlatform.isS390 && stdenv.targetPlatform.is64bit)) &&
84                 lib.meta.availableOn stdenv.hostPlatform elfutils &&
85                 lib.meta.availableOn stdenv.targetPlatform elfutils &&
86                 # HACK: elfutils is marked as broken on static platforms
87                 # which availableOn can't tell.
88                 !stdenv.targetPlatform.isStatic &&
89                 !stdenv.hostPlatform.isStatic
90 , elfutils
92 , # What flavour to build. Flavour string may contain a flavour and flavour
93   # transformers as accepted by hadrian.
94   ghcFlavour ?
95     let
96       # TODO(@sternenseemann): does using the static flavour make sense?
97       baseFlavour = "release";
98       # Note: in case hadrian's flavour transformers cease being expressive
99       # enough for us, we'll need to resort to defining a "nixpkgs" flavour
100       # in hadrianUserSettings and using that instead.
101       transformers =
102         lib.optionals useLLVM [ "llvm" ]
103         ++ lib.optionals (!enableShared) [
104           "no_dynamic_libs"
105           "no_dynamic_ghc"
106         ]
107         ++ lib.optionals (!enableProfiledLibs) [ "no_profiled_libs" ]
108         # While split sections are now enabled by default in ghc 8.8 for windows,
109         # they seem to lead to `too many sections` errors when building base for
110         # profiling.
111         ++ lib.optionals (!stdenv.targetPlatform.isWindows) [ "split_sections" ]
112       ;
113     in
114       baseFlavour + lib.concatMapStrings (t: "+${t}") transformers
116 , # Contents of the UserSettings.hs file to use when compiling hadrian.
117   hadrianUserSettings ? ''
118     module UserSettings (
119         userFlavours, userPackages, userDefaultFlavour,
120         verboseCommand, buildProgressColour, successColour, finalStage
121         ) where
123     import Flavour.Type
124     import Expression
125     import {-# SOURCE #-} Settings.Default
127     -- no way to set this via the command line
128     finalStage :: Stage
129     finalStage = ${
130       # Always build the stage 2 compiler if possible.
131       # TODO(@sternensemann): unify condition with make-built GHCs
132       if stdenv.hostPlatform.canExecute stdenv.targetPlatform
133       then "Stage2" # native compiler or “native” cross e.g. pkgsStatic
134       else "Stage1" # cross compiler
135     }
137     userDefaultFlavour :: String
138     userDefaultFlavour = "release"
140     userFlavours :: [Flavour]
141     userFlavours = []
143     -- Disable Colours
144     buildProgressColour :: BuildProgressColour
145     buildProgressColour = mkBuildProgressColour (Dull Reset)
146     successColour :: SuccessColour
147     successColour = mkSuccessColour (Dull Reset)
149     -- taken from src/UserSettings.hs unchanged, need to be there
150     userPackages :: [Package]
151     userPackages = []
152     verboseCommand :: Predicate
153     verboseCommand = do
154         verbosity <- expr getVerbosity
155         return $ verbosity >= Verbose
156   ''
158 , ghcSrc ?
159     srcOnly {
160       name = "ghc-${version}"; # -source appended by srcOnly
161       src =
162         (if rev != null then fetchgit else fetchurl) ({
163           inherit url sha256;
164         } // lib.optionalAttrs (rev != null) {
165           inherit rev;
166         } // lib.optionalAttrs (postFetch != null) {
167           inherit postFetch;
168         });
170       patches =
171         let
172           # Disable haddock generating pretty source listings to stay under 3GB on aarch64-linux
173           enableHyperlinkedSource =
174             lib.versionAtLeast version "9.8" ||
175             !(stdenv.hostPlatform.isAarch64 && stdenv.hostPlatform.isLinux);
176         in
177         [
178           # Fix docs build with Sphinx >= 7 https://gitlab.haskell.org/ghc/ghc/-/issues/24129
179           (if lib.versionAtLeast version "9.8"
180            then ./docs-sphinx-7-ghc98.patch
181            else ./docs-sphinx-7.patch )
182         ]
183         ++ lib.optionals (lib.versionAtLeast version "9.6" && lib.versionOlder version "9.6.6") [
184           (fetchpatch {
185             name = "fix-fully_static.patch";
186             url = "https://gitlab.haskell.org/ghc/ghc/-/commit/1bb24432ff77e11a0340a7d8586e151e15bba2a1.diff";
187             hash = "sha256-MpvTmFFsNiPDoOp9BhZyWeapeibQ77zgEV+xzZ1UAXs=";
188           })
189         ]
190         ++ lib.optionals (lib.versionAtLeast version "9.6" && lib.versionOlder version "9.8") [
191           # Fix unlit being installed under a different name than is used in the
192           # settings file: https://gitlab.haskell.org/ghc/ghc/-/issues/23317
193           (fetchpatch {
194             name = "ghc-9.6-fix-unlit-path.patch";
195             url = "https://gitlab.haskell.org/ghc/ghc/-/commit/8fde4ac84ec7b1ead238cb158bbef48555d12af9.patch";
196             hash = "sha256-3+CyRBpebEZi8YpS22SsdGQHqi0drR7cCKPtKbR3zyE=";
197           })
198         ]
199         ++ lib.optionals (stdenv.targetPlatform.isDarwin && stdenv.targetPlatform.isAarch64) [
200           # Prevent the paths module from emitting symbols that we don't use
201           # when building with separate outputs.
202           #
203           # These cause problems as they're not eliminated by GHC's dead code
204           # elimination on aarch64-darwin. (see
205           # https://github.com/NixOS/nixpkgs/issues/140774 for details).
206           (if lib.versionOlder version "9.10"
207            then ./Cabal-at-least-3.6-paths-fix-cycle-aarch64-darwin.patch
208            else ./Cabal-3.12-paths-fix-cycle-aarch64-darwin.patch)
209         ]
210         # Prevents passing --hyperlinked-source to haddock. This is a custom
211         # workaround as we wait for this to be configurable via userSettings or
212         # similar. https://gitlab.haskell.org/ghc/ghc/-/issues/23625
213         ++ lib.optionals (!enableHyperlinkedSource) [
214           # TODO(@sternenseemann): Doesn't apply for GHC >= 9.8
215           ../../tools/haskell/hadrian/disable-hyperlinked-source.patch
216         ]
217         # Incorrect bounds on Cabal in hadrian
218         # https://gitlab.haskell.org/ghc/ghc/-/issues/24100
219         ++ lib.optionals (lib.elem version [ "9.8.1" "9.8.2" ]) [
220           ../../tools/haskell/hadrian/hadrian-9.8.1-allow-Cabal-3.10.patch
221         ];
223       stdenv = stdenvNoCC;
224     }
226   # GHC's build system hadrian built from the GHC-to-build's source tree
227   # using our bootstrap GHC.
228 , hadrian ? import ../../tools/haskell/hadrian/make-hadrian.nix { inherit bootPkgs lib; } {
229     inherit ghcSrc;
230     ghcVersion = version;
231     userSettings = hadrianUserSettings;
232   }
234 , #  Whether to build sphinx documentation.
235   # TODO(@sternenseemann): Hadrian ignores the --docs flag if finalStage = Stage1
236   enableDocs ? (
237     # Docs disabled if we are building on musl because it's a large task to keep
238     # all `sphinx` dependencies building in this environment.
239     !stdenv.buildPlatform.isMusl
240   )
242 , # Whether to disable the large address space allocator
243   # necessary fix for iOS: https://www.reddit.com/r/haskell/comments/4ttdz1/building_an_osxi386_to_iosarm64_cross_compiler/d5qvd67/
244   disableLargeAddressSpace ? stdenv.targetPlatform.isiOS
246 , # Whether to build an unregisterised version of GHC.
247   # GHC will normally auto-detect whether it can do a registered build, but this
248   # option will force it to do an unregistered build when set to true.
249   # See https://gitlab.haskell.org/ghc/ghc/-/wikis/building/unregisterised
250   enableUnregisterised ? false
253 assert !enableNativeBignum -> gmp != null;
255 # GHC does not support building when all 3 platforms are different.
256 assert stdenv.buildPlatform == stdenv.hostPlatform || stdenv.hostPlatform == stdenv.targetPlatform;
258 # It is currently impossible to cross-compile GHC with Hadrian.
259 assert stdenv.buildPlatform == stdenv.hostPlatform;
262   inherit (stdenv) buildPlatform hostPlatform targetPlatform;
264   # TODO(@Ericson2314) Make unconditional
265   targetPrefix = lib.optionalString
266     (targetPlatform != hostPlatform)
267     "${targetPlatform.config}-";
269   hadrianSettings =
270     # -fexternal-dynamic-refs apparently (because it's not clear from the
271     # documentation) makes the GHC RTS able to load static libraries, which may
272     # be needed for TemplateHaskell. This solution was described in
273     # https://www.tweag.io/blog/2020-09-30-bazel-static-haskell
274     lib.optionals enableRelocatedStaticLibs [
275       "*.*.ghc.*.opts += -fPIC -fexternal-dynamic-refs"
276     ]
277     ++ lib.optionals targetPlatform.useAndroidPrebuilt [
278       "*.*.ghc.c.opts += -optc-std=gnu99"
279     ];
281   # Splicer will pull out correct variations
282   libDeps = platform: lib.optional enableTerminfo ncurses
283     ++ lib.optionals (!targetPlatform.isGhcjs) [libffi]
284     # Bindist configure script fails w/o elfutils in linker search path
285     # https://gitlab.haskell.org/ghc/ghc/-/issues/22081
286     ++ lib.optional enableDwarf elfutils
287     ++ lib.optional (!enableNativeBignum) gmp
288     ++ lib.optional (platform.libc != "glibc" && !targetPlatform.isWindows && !targetPlatform.isGhcjs) libiconv;
290   # TODO(@sternenseemann): is buildTarget LLVM unnecessary?
291   # GHC doesn't seem to have {LLC,OPT}_HOST
292   toolsForTarget = [
293     (if targetPlatform.isGhcjs
294      then pkgsBuildTarget.emscripten
295      else pkgsBuildTarget.targetPackages.stdenv.cc)
296   ] ++ lib.optional useLLVM buildTargetLlvmPackages.llvm;
298   buildCC = buildPackages.stdenv.cc;
299   targetCC = builtins.head toolsForTarget;
300   installCC =
301     if targetPlatform.isGhcjs
302     then pkgsHostTarget.emscripten
303     else pkgsHostTarget.targetPackages.stdenv.cc;
305   # toolPath calculates the absolute path to the name tool associated with a
306   # given `stdenv.cc` derivation, i.e. it picks the correct derivation to take
307   # the tool from (cc, cc.bintools, cc.bintools.bintools) and adds the correct
308   # subpath of the tool.
309   toolPath = name: cc:
310     let
311       tools = {
312         "cc" = cc;
313         "c++" = cc;
314         as = cc.bintools;
316         ar = cc.bintools;
317         ranlib = cc.bintools;
318         nm = cc.bintools;
319         readelf = cc.bintools;
320         objdump = cc.bintools;
322         ld = cc.bintools;
323         "ld.gold" = cc.bintools;
325         otool = cc.bintools.bintools;
327         # GHC needs install_name_tool on all darwin platforms. The same one can
328         # be used on both platforms. It is safe to use with linker-generated
329         # signatures because it will update the signatures automatically after
330         # modifying the target binary.
331         install_name_tool = cc.bintools.bintools;
333         # strip on darwin is wrapped to enable deterministic mode.
334         strip =
335           # TODO(@sternenseemann): also use wrapper if linker == "bfd" or "gold"
336           if stdenv.targetPlatform.isDarwin
337           then cc.bintools
338           else cc.bintools.bintools;
340         # clang is used as an assembler on darwin with the LLVM backend
341         clang = cc;
342       }.${name};
343     in
344     "${tools}/bin/${tools.targetPrefix}${name}";
346   # Use gold either following the default, or to avoid the BFD linker due to some bugs / perf issues.
347   # But we cannot avoid BFD when using musl libc due to https://sourceware.org/bugzilla/show_bug.cgi?id=23856
348   # see #84670 and #49071 for more background.
349   useLdGold = targetPlatform.linker == "gold" ||
350     (targetPlatform.linker == "bfd" && (targetCC.bintools.bintools.hasGold or false) && !targetPlatform.isMusl);
352   # Makes debugging easier to see which variant is at play in `nix-store -q --tree`.
353   variantSuffix = lib.concatStrings [
354     (lib.optionalString stdenv.hostPlatform.isMusl "-musl")
355     (lib.optionalString enableNativeBignum "-native-bignum")
356   ];
358   # These libraries are library dependencies of the standard libraries bundled
359   # by GHC (core libs) users will link their compiled artifacts again. Thus,
360   # they should be taken from targetPackages.
361   #
362   # We need to use pkgsHostTarget if we are cross compiling a native GHC compiler,
363   # though (when native compiling GHC, pkgsHostTarget == targetPackages):
364   #
365   # 1. targetPackages would be empty(-ish) in this situation since we can't
366   #    execute cross compiled compilers in order to obtain the libraries
367   #    that would be in targetPackages.
368   # 2. pkgsHostTarget is fine to use since hostPlatform == targetPlatform in this
369   #    situation.
370   # 3. The core libs used by the final GHC (stage 2) for user artifacts are also
371   #    used to build stage 2 GHC itself, i.e. the core libs are both host and
372   #    target.
373   targetLibs = {
374     inherit
375       (if hostPlatform != targetPlatform then targetPackages else pkgsHostTarget)
376       elfutils
377       gmp
378       libffi
379       ncurses;
380   };
382   # Our Cabal compiler name
383   haskellCompilerName = "ghc-${version}";
387 stdenv.mkDerivation ({
388   pname = "${targetPrefix}ghc${variantSuffix}";
389   inherit version;
391   src = ghcSrc;
393   enableParallelBuilding = true;
395   postPatch = ''
396     patchShebangs --build .
397   '';
399   # GHC needs the locale configured during the Haddock phase.
400   LANG = "en_US.UTF-8";
402   # GHC is a bit confused on its cross terminology.
403   # TODO(@sternenseemann): investigate coreutils dependencies and pass absolute paths
404   preConfigure = ''
405     for env in $(env | grep '^TARGET_' | sed -E 's|\+?=.*||'); do
406       export "''${env#TARGET_}=''${!env}"
407     done
408     # No need for absolute paths since these tools only need to work during the build
409     export CC_STAGE0="$CC_FOR_BUILD"
410     export LD_STAGE0="$LD_FOR_BUILD"
411     export AR_STAGE0="$AR_FOR_BUILD"
413     # Stage0 (build->build) which builds stage 1
414     export GHC="${bootPkgs.ghc}/bin/ghc"
415     # GHC is a bit confused on its cross terminology, as these would normally be
416     # the *host* tools.
417     export CC="${toolPath "cc" targetCC}"
418     export CXX="${toolPath "c++" targetCC}"
419     # Use gold to work around https://sourceware.org/bugzilla/show_bug.cgi?id=16177
420     export LD="${toolPath "ld${lib.optionalString useLdGold ".gold"}" targetCC}"
421     export AS="${toolPath "as" targetCC}"
422     export AR="${toolPath "ar" targetCC}"
423     export NM="${toolPath "nm" targetCC}"
424     export RANLIB="${toolPath "ranlib" targetCC}"
425     export READELF="${toolPath "readelf" targetCC}"
426     export STRIP="${toolPath "strip" targetCC}"
427     export OBJDUMP="${toolPath "objdump" targetCC}"
428   '' + lib.optionalString (stdenv.targetPlatform.linker == "cctools") ''
429     export OTOOL="${toolPath "otool" targetCC}"
430     export INSTALL_NAME_TOOL="${toolPath "install_name_tool" targetCC}"
431   '' + lib.optionalString useLLVM ''
432     export LLC="${lib.getBin buildTargetLlvmPackages.llvm}/bin/llc"
433     export OPT="${lib.getBin buildTargetLlvmPackages.llvm}/bin/opt"
434   '' + lib.optionalString (useLLVM && stdenv.targetPlatform.isDarwin) ''
435     # LLVM backend on Darwin needs clang: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/codegens.html#llvm-code-generator-fllvm
436     # The executable we specify via $CLANG is used as an assembler (exclusively, it seems, but this isn't
437     # clarified in any user facing documentation). As such, it'll be called on assembly produced by $CC
438     # which usually comes from the darwin stdenv. To prevent a situation where $CLANG doesn't understand
439     # the assembly it is given, we need to make sure that it matches the LLVM version of $CC if possible.
440     # It is unclear (at the time of writing 2024-09-01)  whether $CC should match the LLVM version we use
441     # for llc and opt which would require using a custom darwin stdenv for targetCC.
442     export CLANG="${
443       if targetCC.isClang
444       then toolPath "clang" targetCC
445       else "${buildTargetLlvmPackages.clang}/bin/${buildTargetLlvmPackages.clang.targetPrefix}clang"
446     }"
447   '' +
448   lib.optionalString (stdenv.hostPlatform.isLinux && hostPlatform.libc == "glibc") ''
449     export LOCALE_ARCHIVE="${glibcLocales}/lib/locale/locale-archive"
450   '' + lib.optionalString (!stdenv.hostPlatform.isDarwin) ''
451     export NIX_LDFLAGS+=" -rpath $out/lib/ghc-${version}"
452   '' + lib.optionalString stdenv.hostPlatform.isDarwin ''
453     export NIX_LDFLAGS+=" -no_dtrace_dof"
455     # GHC tries the host xattr /usr/bin/xattr by default which fails since it expects python to be 2.7
456     export XATTR=${lib.getBin xattr}/bin/xattr
457   ''
458   # If we are not using release tarballs, some files need to be generated using
459   # the boot script.
460   + lib.optionalString (rev != null) ''
461     echo ${version} > VERSION
462     echo ${rev} > GIT_COMMIT_ID
463     ./boot
464   ''
465   + lib.optionalString targetPlatform.useAndroidPrebuilt ''
466     sed -i -e '5i ,("armv7a-unknown-linux-androideabi", ("e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64", "cortex-a8", ""))' llvm-targets
467   '' + lib.optionalString targetPlatform.isMusl ''
468       echo "patching llvm-targets for musl targets..."
469       echo "Cloning these existing '*-linux-gnu*' targets:"
470       grep linux-gnu llvm-targets | sed 's/^/  /'
471       echo "(go go gadget sed)"
472       sed -i 's,\(^.*linux-\)gnu\(.*\)$,\0\n\1musl\2,' llvm-targets
473       echo "llvm-targets now contains these '*-linux-musl*' targets:"
474       grep linux-musl llvm-targets | sed 's/^/  /'
476       echo "And now patching to preserve '-musleabi' as done with '-gnueabi'"
477       # (aclocal.m4 is actual source, but patch configure as well since we don't re-gen)
478       for x in configure aclocal.m4; do
479         substituteInPlace $x \
480           --replace '*-android*|*-gnueabi*)' \
481                     '*-android*|*-gnueabi*|*-musleabi*)'
482       done
483   ''
484   # Need to make writable EM_CACHE for emscripten. The path in EM_CACHE must be absolute.
485   # https://gitlab.haskell.org/ghc/ghc/-/wikis/javascript-backend#configure-fails-with-sub-word-sized-atomic-operations-not-available
486   + lib.optionalString targetPlatform.isGhcjs ''
487     export EM_CACHE="$(realpath $(mktemp -d emcache.XXXXXXXXXX))"
488     cp -Lr ${targetCC /* == emscripten */}/share/emscripten/cache/* "$EM_CACHE/"
489     chmod u+rwX -R "$EM_CACHE"
490   ''
491   # Create bash array hadrianFlagsArray for use in buildPhase. Do it in
492   # preConfigure, so overrideAttrs can be used to modify it effectively.
493   # hadrianSettings are passed via the command line so they are more visible
494   # in the build log.
495   + ''
496     hadrianFlagsArray=(
497       "-j$NIX_BUILD_CORES"
498       ${lib.escapeShellArgs hadrianSettings}
499     )
500   '';
502   ${if targetPlatform.isGhcjs then "configureScript" else null} = "emconfigure ./configure";
503   # GHC currently ships an edited config.sub so ghcjs is accepted which we can not rollback
504   ${if targetPlatform.isGhcjs then "dontUpdateAutotoolsGnuConfigScripts" else null} = true;
506   # TODO(@Ericson2314): Always pass "--target" and always prefix.
507   configurePlatforms = [ "build" "host" ]
508     ++ lib.optional (targetPlatform != hostPlatform) "target";
510   # `--with` flags for libraries needed for RTS linker
511   configureFlags = [
512     "--datadir=$doc/share/doc/ghc"
513   ] ++ lib.optionals enableTerminfo [
514     "--with-curses-includes=${lib.getDev targetLibs.ncurses}/include"
515     "--with-curses-libraries=${lib.getLib targetLibs.ncurses}/lib"
516   ] ++ lib.optionals (libffi != null && !targetPlatform.isGhcjs) [
517     "--with-system-libffi"
518     "--with-ffi-includes=${targetLibs.libffi.dev}/include"
519     "--with-ffi-libraries=${targetLibs.libffi.out}/lib"
520   ] ++ lib.optionals (targetPlatform == hostPlatform && !enableNativeBignum) [
521     "--with-gmp-includes=${targetLibs.gmp.dev}/include"
522     "--with-gmp-libraries=${targetLibs.gmp.out}/lib"
523   ] ++ lib.optionals (targetPlatform == hostPlatform && hostPlatform.libc != "glibc" && !targetPlatform.isWindows) [
524     "--with-iconv-includes=${libiconv}/include"
525     "--with-iconv-libraries=${libiconv}/lib"
526   ] ++ lib.optionals (targetPlatform != hostPlatform) [
527     "--enable-bootstrap-with-devel-snapshot"
528   ] ++ lib.optionals useLdGold [
529     "CFLAGS=-fuse-ld=gold"
530     "CONF_GCC_LINKER_OPTS_STAGE1=-fuse-ld=gold"
531     "CONF_GCC_LINKER_OPTS_STAGE2=-fuse-ld=gold"
532   ] ++ lib.optionals (disableLargeAddressSpace) [
533     "--disable-large-address-space"
534   ] ++ lib.optionals enableDwarf [
535     "--enable-dwarf-unwind"
536     "--with-libdw-includes=${lib.getDev targetLibs.elfutils}/include"
537     "--with-libdw-libraries=${lib.getLib targetLibs.elfutils}/lib"
538   ] ++ lib.optionals targetPlatform.isDarwin [
539     # Darwin uses llvm-ar. GHC will try to use `-L` with `ar` when it is `llvm-ar`
540     # but it doesn’t currently work because Cabal never uses `-L` on Darwin. See:
541     # https://gitlab.haskell.org/ghc/ghc/-/issues/23188
542     # https://github.com/haskell/cabal/issues/8882
543     "fp_cv_prog_ar_supports_dash_l=no"
544   ] ++ lib.optionals enableUnregisterised [
545     "--enable-unregisterised"
546   ];
548   # Make sure we never relax`$PATH` and hooks support for compatibility.
549   strictDeps = true;
551   # Don’t add -liconv to LDFLAGS automatically so that GHC will add it itself.
552   dontAddExtraLibs = true;
554   nativeBuildInputs = [
555     perl hadrian bootPkgs.alex bootPkgs.happy bootPkgs.hscolour
556     # autoconf and friends are necessary for hadrian to create the bindist
557     autoconf automake m4
558     # Python is used in a few scripts invoked by hadrian to generate e.g. rts headers.
559     python3
560     # Tool used to update GHC's settings file in postInstall
561     bootPkgs.ghc-settings-edit
562   ] ++ lib.optionals (stdenv.hostPlatform.isDarwin && stdenv.hostPlatform.isAarch64) [
563     autoSignDarwinBinariesHook
564   ] ++ lib.optionals enableDocs [
565     sphinx
566   ];
568   # For building runtime libs
569   depsBuildTarget = toolsForTarget;
570   # Everything the stage0 compiler needs to build stage1: CC, bintools, extra libs.
571   # See also GHC, {CC,LD,AR}_STAGE0 in preConfigure.
572   depsBuildBuild = [
573     # N.B. We do not declare bootPkgs.ghc in any of the stdenv.mkDerivation
574     # dependency lists to prevent the bintools setup hook from adding ghc's
575     # lib directory to the linker flags. Instead we tell configure about it
576     # via the GHC environment variable.
577     buildCC
578     # stage0 builds terminfo unconditionally, so we always need ncurses
579     ncurses
580   ];
582   # Prevent stage0 ghc from leaking into the final result. This was an issue
583   # with GHC 9.6.
584   disallowedReferences = [
585     bootPkgs.ghc
586   ];
588   buildInputs = [ bash ] ++ (libDeps hostPlatform);
590   depsTargetTarget = map lib.getDev (libDeps targetPlatform);
591   depsTargetTargetPropagated = map (lib.getOutput "out") (libDeps targetPlatform);
593   hadrianFlags = [
594     "--flavour=${ghcFlavour}"
595     "--bignum=${if enableNativeBignum then "native" else "gmp"}"
596     "--docs=${if enableDocs then "no-sphinx-pdfs" else "no-sphinx"}"
597   ];
599   buildPhase = ''
600     runHook preBuild
602     # hadrianFlagsArray is created in preConfigure
603     echo "hadrianFlags: $hadrianFlags ''${hadrianFlagsArray[@]}"
605     # We need to go via the bindist for installing
606     hadrian $hadrianFlags "''${hadrianFlagsArray[@]}" binary-dist-dir
608     runHook postBuild
609   '';
611   # required, because otherwise all symbols from HSffi.o are stripped, and
612   # that in turn causes GHCi to abort
613   stripDebugFlags = [ "-S" ] ++ lib.optional (!targetPlatform.isDarwin) "--keep-file-symbols";
615   checkTarget = "test";
617   hardeningDisable =
618     [ "format" ]
619     # In nixpkgs, musl based builds currently enable `pie` hardening by default
620     # (see `defaultHardeningFlags` in `make-derivation.nix`).
621     # But GHC cannot currently produce outputs that are ready for `-pie` linking.
622     # Thus, disable `pie` hardening, otherwise `recompile with -fPIE` errors appear.
623     # See:
624     # * https://github.com/NixOS/nixpkgs/issues/129247
625     # * https://gitlab.haskell.org/ghc/ghc/-/issues/19580
626     ++ lib.optional stdenv.targetPlatform.isMusl "pie";
628   # big-parallel allows us to build with more than 2 cores on
629   # Hydra which already warrants a significant speedup
630   requiredSystemFeatures = [ "big-parallel" ];
632   outputs = [ "out" "doc" ];
634   # We need to configure the bindist *again* before installing
635   # https://gitlab.haskell.org/ghc/ghc/-/issues/22058
636   # TODO(@sternenseemann): it would be nice if the bindist could be an intermediate
637   # derivation, but since it is > 2GB even on x86_64-linux, not a good idea?
638   preInstall = ''
639     pushd _build/bindist/*
641   ''
642   # the bindist configure script uses different env variables than the GHC configure script
643   # see https://github.com/NixOS/nixpkgs/issues/267250 and https://gitlab.haskell.org/ghc/ghc/-/issues/24211
644   + lib.optionalString (stdenv.targetPlatform.linker == "cctools") ''
645     export InstallNameToolCmd=$INSTALL_NAME_TOOL
646     export OtoolCmd=$OTOOL
647   ''
648   + ''
649     $configureScript $configureFlags "''${configureFlagsArray[@]}"
650   '';
652   postInstall = ''
653     # leave bindist directory
654     popd
656     settingsFile="$out/lib/${targetPrefix}${haskellCompilerName}/lib/settings"
658     # Make the installed GHC use the host->target tools.
659     ghc-settings-edit "$settingsFile" \
660       "C compiler command" "${toolPath "cc" installCC}" \
661       "Haskell CPP command" "${toolPath "cc" installCC}" \
662       "C++ compiler command" "${toolPath "c++" installCC}" \
663       "ld command" "${toolPath "ld${lib.optionalString useLdGold ".gold"}" installCC}" \
664       "Merge objects command" "${toolPath "ld${lib.optionalString useLdGold ".gold"}" installCC}" \
665       "ar command" "${toolPath "ar" installCC}" \
666       "ranlib command" "${toolPath "ranlib" installCC}"
667   ''
668   + lib.optionalString (stdenv.targetPlatform.linker == "cctools") ''
669     ghc-settings-edit "$settingsFile" \
670       "otool command" "${toolPath "otool" installCC}" \
671       "install_name_tool command" "${toolPath "install_name_tool" installCC}"
672   ''
673   + lib.optionalString useLLVM ''
674     ghc-settings-edit "$settingsFile" \
675       "LLVM llc command" "${lib.getBin llvmPackages.llvm}/bin/llc" \
676       "LLVM opt command" "${lib.getBin llvmPackages.llvm}/bin/opt"
677   ''
678   + lib.optionalString (useLLVM && stdenv.targetPlatform.isDarwin) ''
679     ghc-settings-edit "$settingsFile" \
680       "LLVM clang command" "${
681         # See comment for CLANG in preConfigure
682         if installCC.isClang
683         then toolPath "clang" installCC
684         else "${llvmPackages.clang}/bin/${llvmPackages.clang.targetPrefix}clang"
685       }"
686   ''
687   + ''
689     # Install the bash completion file.
690     install -Dm 644 utils/completion/ghc.bash $out/share/bash-completion/completions/${targetPrefix}ghc
691   '';
693   passthru = {
694     inherit bootPkgs targetPrefix haskellCompilerName;
696     inherit llvmPackages;
697     inherit enableShared;
699     # Expose hadrian used for bootstrapping, for debugging purposes
700     inherit hadrian;
702     # TODO(@sternenseemann): there's no stage0:exe:haddock target by default,
703     # so haddock isn't available for GHC cross-compilers. Can we fix that?
704     hasHaddock = stdenv.hostPlatform == stdenv.targetPlatform;
705   };
707   meta = {
708     homepage = "http://haskell.org/ghc";
709     description = "Glasgow Haskell Compiler";
710     maintainers = with lib.maintainers; [
711       guibou
712     ] ++ lib.teams.haskell.members;
713     timeout = 24 * 3600;
714     platforms = lib.platforms.all;
715     inherit (bootPkgs.ghc.meta) license;
716   };
718   dontStrip = targetPlatform.useAndroidPrebuilt || targetPlatform.isWasm;
719 } // lib.optionalAttrs targetPlatform.useAndroidPrebuilt {
720   dontPatchELF = true;
721   noAuditTmpdir = true;