1{
2 version,
3 sha256,
4 url ? "https://downloads.haskell.org/ghc/${version}/ghc-${version}-src.tar.xz",
5}:
6
7{
8 lib,
9 stdenv,
10 pkgsBuildTarget,
11 pkgsHostTarget,
12 buildPackages,
13 targetPackages,
14
15 # build-tools
16 bootPkgs,
17 autoconf,
18 automake,
19 coreutils,
20 fetchpatch,
21 fetchurl,
22 perl,
23 python3,
24 m4,
25 sphinx,
26 xattr,
27 autoSignDarwinBinariesHook,
28 bash,
29
30 libiconv ? null,
31 ncurses,
32 glibcLocales ? null,
33
34 # GHC can be built with system libffi or a bundled one.
35 libffi ? null,
36
37 useLLVM ? !(import ./common-have-ncg.nix { inherit lib stdenv version; }),
38
39 # LLVM is conceptually a run-time-only dependency, but for
40 # non-x86, we need LLVM to bootstrap later stages, so it becomes a
41 # build-time dependency too.
42 buildTargetLlvmPackages,
43 llvmPackages,
44
45 # If enabled, GHC will be built with the GPL-free but slightly slower native
46 # bignum backend instead of the faster but GPLed gmp backend.
47 enableNativeBignum ?
48 !(lib.meta.availableOn stdenv.hostPlatform gmp && lib.meta.availableOn stdenv.targetPlatform gmp),
49 gmp,
50
51 # If enabled, use -fPIC when compiling static libs.
52 enableRelocatedStaticLibs ? stdenv.targetPlatform != stdenv.hostPlatform,
53
54 # Exceeds Hydra output limit (at the time of writing ~3GB) when cross compiled to riscv64.
55 # A riscv64 cross-compiler fits into the limit comfortably.
56 enableProfiledLibs ? !stdenv.hostPlatform.isRiscV64,
57
58 # Whether to build dynamic libs for the standard library (on the target
59 # platform). Static libs are always built.
60 enableShared ? with stdenv.targetPlatform; !isWindows && !useiOSPrebuilt && !isStatic,
61
62 # Whether to build terminfo.
63 enableTerminfo ?
64 !(
65 stdenv.targetPlatform.isWindows
66 # terminfo can't be built for cross
67 || (stdenv.buildPlatform != stdenv.hostPlatform)
68 || (stdenv.hostPlatform != stdenv.targetPlatform)
69 ),
70
71 # What flavour to build. An empty string indicates no
72 # specific flavour and falls back to ghc default values.
73 ghcFlavour ? lib.optionalString (stdenv.targetPlatform != stdenv.hostPlatform) (
74 if useLLVM then "perf-cross" else "perf-cross-ncg"
75 ),
76
77 # Whether to build sphinx documentation.
78 enableDocs ? (
79 # Docs disabled if we are building on musl because it's a large task to keep
80 # all `sphinx` dependencies building in this environment.
81 !stdenv.buildPlatform.isMusl
82 ),
83
84 enableHaddockProgram ?
85 # Disabled for cross; see note [HADDOCK_DOCS].
86 (stdenv.buildPlatform == stdenv.hostPlatform && stdenv.targetPlatform == stdenv.hostPlatform),
87
88 # Whether to disable the large address space allocator
89 # necessary fix for iOS: https://www.reddit.com/r/haskell/comments/4ttdz1/building_an_osxi386_to_iosarm64_cross_compiler/d5qvd67/
90 disableLargeAddressSpace ? stdenv.targetPlatform.isiOS,
91
92 # Whether to build an unregisterised version of GHC.
93 # GHC will normally auto-detect whether it can do a registered build, but this
94 # option will force it to do an unregistered build when set to true.
95 # See https://gitlab.haskell.org/ghc/ghc/-/wikis/building/unregisterised
96 # Registerised RV64 compiler produces programs that segfault
97 # See https://gitlab.haskell.org/ghc/ghc/-/issues/23957
98 enableUnregisterised ? stdenv.hostPlatform.isRiscV64 || stdenv.targetPlatform.isRiscV64,
99}:
100
101assert !enableNativeBignum -> gmp != null;
102
103# Cross cannot currently build the `haddock` program for silly reasons,
104# see note [HADDOCK_DOCS].
105assert
106 (stdenv.buildPlatform != stdenv.hostPlatform || stdenv.targetPlatform != stdenv.hostPlatform)
107 -> !enableHaddockProgram;
108
109# GHC does not support building when all 3 platforms are different.
110assert stdenv.buildPlatform == stdenv.hostPlatform || stdenv.hostPlatform == stdenv.targetPlatform;
111
112let
113 inherit (stdenv) buildPlatform hostPlatform targetPlatform;
114
115 # TODO(@Ericson2314) Make unconditional
116 targetPrefix = lib.optionalString (targetPlatform != hostPlatform) "${targetPlatform.config}-";
117
118 buildMK = ''
119 BuildFlavour = ${ghcFlavour}
120 ifneq \"\$(BuildFlavour)\" \"\"
121 include mk/flavours/\$(BuildFlavour).mk
122 endif
123 BUILD_SPHINX_HTML = ${if enableDocs then "YES" else "NO"}
124 BUILD_SPHINX_PDF = NO
125
126 WITH_TERMINFO = ${if enableTerminfo then "YES" else "NO"}
127 ''
128 +
129 # Note [HADDOCK_DOCS]:
130 # Unfortunately currently `HADDOCK_DOCS` controls both whether the `haddock`
131 # program is built (which we generally always want to have a complete GHC install)
132 # and whether it is run on the GHC sources to generate hyperlinked source code
133 # (which is impossible for cross-compilation); see:
134 # https://gitlab.haskell.org/ghc/ghc/-/issues/20077
135 # This implies that currently a cross-compiled GHC will never have a `haddock`
136 # program, so it can never generate haddocks for any packages.
137 # If this is solved in the future, we'd like to unconditionally
138 # build the haddock program (removing the `enableHaddockProgram` option).
139 ''
140 HADDOCK_DOCS = ${if enableHaddockProgram then "YES" else "NO"}
141 # Build haddocks for boot packages with hyperlinking
142 EXTRA_HADDOCK_OPTS += --hyperlinked-source --quickjump
143
144 DYNAMIC_GHC_PROGRAMS = ${if enableShared then "YES" else "NO"}
145 BIGNUM_BACKEND = ${if enableNativeBignum then "native" else "gmp"}
146 ''
147 + lib.optionalString (targetPlatform != hostPlatform) ''
148 Stage1Only = ${if targetPlatform.system == hostPlatform.system then "NO" else "YES"}
149 CrossCompilePrefix = ${targetPrefix}
150 ''
151 + lib.optionalString (!enableProfiledLibs) ''
152 BUILD_PROF_LIBS = NO
153 ''
154 +
155 # -fexternal-dynamic-refs apparently (because it's not clear from the documentation)
156 # makes the GHC RTS able to load static libraries, which may be needed for TemplateHaskell.
157 # This solution was described in https://www.tweag.io/blog/2020-09-30-bazel-static-haskell
158 lib.optionalString enableRelocatedStaticLibs ''
159 GhcLibHcOpts += -fPIC -fexternal-dynamic-refs
160 GhcRtsHcOpts += -fPIC -fexternal-dynamic-refs
161 ''
162 + lib.optionalString targetPlatform.useAndroidPrebuilt ''
163 EXTRA_CC_OPTS += -std=gnu99
164 '';
165
166 # Splicer will pull out correct variations
167 libDeps =
168 platform:
169 lib.optional enableTerminfo ncurses
170 ++ [ libffi ]
171 ++ lib.optional (!enableNativeBignum) gmp
172 ++ lib.optional (platform.libc != "glibc" && !targetPlatform.isWindows) libiconv;
173
174 # TODO(@sternenseemann): is buildTarget LLVM unnecessary?
175 # GHC doesn't seem to have {LLC,OPT}_HOST
176 toolsForTarget = [
177 pkgsBuildTarget.targetPackages.stdenv.cc
178 ]
179 ++ lib.optional useLLVM buildTargetLlvmPackages.llvm;
180
181 buildCC = buildPackages.stdenv.cc;
182 targetCC = builtins.head toolsForTarget;
183 installCC = pkgsHostTarget.targetPackages.stdenv.cc;
184
185 # toolPath calculates the absolute path to the name tool associated with a
186 # given `stdenv.cc` derivation, i.e. it picks the correct derivation to take
187 # the tool from (cc, cc.bintools, cc.bintools.bintools) and adds the correct
188 # subpath of the tool.
189 toolPath =
190 name: cc:
191 let
192 tools =
193 {
194 "cc" = cc;
195 "c++" = cc;
196 as = cc.bintools;
197
198 ar = cc.bintools;
199 ranlib = cc.bintools;
200 nm = cc.bintools;
201 readelf = cc.bintools;
202 objdump = cc.bintools;
203
204 ld = cc.bintools;
205 "ld.gold" = cc.bintools;
206
207 otool = cc.bintools.bintools;
208
209 # GHC needs install_name_tool on all darwin platforms. The same one can
210 # be used on both platforms. It is safe to use with linker-generated
211 # signatures because it will update the signatures automatically after
212 # modifying the target binary.
213 install_name_tool = cc.bintools.bintools;
214
215 # strip on darwin is wrapped to enable deterministic mode.
216 strip =
217 # TODO(@sternenseemann): also use wrapper if linker == "bfd" or "gold"
218 if stdenv.targetPlatform.isDarwin then cc.bintools else cc.bintools.bintools;
219
220 # clang is used as an assembler on darwin with the LLVM backend
221 clang = cc;
222 }
223 .${name};
224 in
225 "${tools}/bin/${tools.targetPrefix}${name}";
226
227 # Use gold either following the default, or to avoid the BFD linker due to some bugs / perf issues.
228 # But we cannot avoid BFD when using musl libc due to https://sourceware.org/bugzilla/show_bug.cgi?id=23856
229 # see #84670 and #49071 for more background.
230 useLdGold =
231 targetPlatform.linker == "gold"
232 || (
233 targetPlatform.linker == "bfd"
234 && (targetCC.bintools.bintools.hasGold or false)
235 && !targetPlatform.isMusl
236 );
237
238 # Makes debugging easier to see which variant is at play in `nix-store -q --tree`.
239 variantSuffix = lib.concatStrings [
240 (lib.optionalString stdenv.hostPlatform.isMusl "-musl")
241 (lib.optionalString enableNativeBignum "-native-bignum")
242 ];
243
244 # These libraries are library dependencies of the standard libraries bundled
245 # by GHC (core libs) users will link their compiled artifacts again. Thus,
246 # they should be taken from targetPackages.
247 #
248 # We need to use pkgsHostTarget if we are cross compiling a native GHC compiler,
249 # though (when native compiling GHC, pkgsHostTarget == targetPackages):
250 #
251 # 1. targetPackages would be empty(-ish) in this situation since we can't
252 # execute cross compiled compilers in order to obtain the libraries
253 # that would be in targetPackages.
254 # 2. pkgsHostTarget is fine to use since hostPlatform == targetPlatform in this
255 # situation.
256 # 3. The core libs used by the final GHC (stage 2) for user artifacts are also
257 # used to build stage 2 GHC itself, i.e. the core libs are both host and
258 # target.
259 targetLibs = {
260 inherit (if hostPlatform != targetPlatform then targetPackages else pkgsHostTarget)
261 gmp
262 libffi
263 ncurses
264 ;
265 };
266
267in
268
269stdenv.mkDerivation (
270 rec {
271 pname = "${targetPrefix}ghc${variantSuffix}";
272 inherit version;
273
274 src = fetchurl {
275 inherit url sha256;
276 };
277
278 enableParallelBuilding = true;
279
280 outputs = [
281 "out"
282 "doc"
283 ];
284
285 patches = [
286 # Determine size of time related types using hsc2hs instead of assuming CLong.
287 # Prevents failures when e.g. stat(2)ing on 32bit systems with 64bit time_t etc.
288 # https://github.com/haskell/ghcup-hs/issues/1107
289 # https://gitlab.haskell.org/ghc/ghc/-/issues/25095
290 # Note that in normal situations this shouldn't be the case since nixpkgs
291 # doesn't set -D_FILE_OFFSET_BITS=64 and friends (yet).
292 (fetchpatch {
293 name = "unix-fix-ctimeval-size-32-bit.patch";
294 url = "https://github.com/haskell/unix/commit/8183e05b97ce870dd6582a3677cc82459ae566ec.patch";
295 sha256 = "17q5yyigqr5kxlwwzb95sx567ysfxlw6bp3j4ji20lz0947aw6gv";
296 stripLen = 1;
297 extraPrefix = "libraries/unix/";
298 })
299 ]
300 ++ lib.optionals (lib.versionOlder version "9.4") [
301 # fix hyperlinked haddock sources: https://github.com/haskell/haddock/pull/1482
302 (fetchpatch {
303 url = "https://patch-diff.githubusercontent.com/raw/haskell/haddock/pull/1482.patch";
304 sha256 = "sha256-8w8QUCsODaTvknCDGgTfFNZa8ZmvIKaKS+2ZJZ9foYk=";
305 extraPrefix = "utils/haddock/";
306 stripLen = 1;
307 })
308 ]
309
310 ++ lib.optionals (lib.versionOlder version "9.4.6") [
311 # Fix docs build with sphinx >= 6.0
312 # https://gitlab.haskell.org/ghc/ghc/-/issues/22766
313 (fetchpatch {
314 name = "ghc-docs-sphinx-6.0.patch";
315 url = "https://gitlab.haskell.org/ghc/ghc/-/commit/10e94a556b4f90769b7fd718b9790d58ae566600.patch";
316 sha256 = "0kmhfamr16w8gch0lgln2912r8aryjky1hfcda3jkcwa5cdzgjdv";
317 })
318 ]
319
320 ++ [
321 # Fix docs build with Sphinx >= 7 https://gitlab.haskell.org/ghc/ghc/-/issues/24129
322 ./docs-sphinx-7.patch
323 ]
324
325 ++ lib.optionals (lib.versionOlder version "9.2.2") [
326 # Add flag that fixes C++ exception handling; opt-in. Merged in 9.4 and 9.2.2.
327 # https://gitlab.haskell.org/ghc/ghc/-/merge_requests/7423
328 (fetchpatch {
329 name = "ghc-9.0.2-fcompact-unwind.patch";
330 # Note that the test suite is not packaged.
331 url = "https://gitlab.haskell.org/ghc/ghc/-/commit/c6132c782d974a7701e7f6447bdcd2bf6db4299a.patch?merge_request_iid=7423";
332 sha256 = "sha256-b4feGZIaKDj/UKjWTNY6/jH4s2iate0wAgMxG3rAbZI=";
333 })
334 ]
335
336 ++ lib.optionals (lib.versionAtLeast version "9.2") [
337 # Don't generate code that doesn't compile when --enable-relocatable is passed to Setup.hs
338 # Can be removed if the Cabal library included with ghc backports the linked fix
339 (fetchpatch {
340 url = "https://github.com/haskell/cabal/commit/6c796218c92f93c95e94d5ec2d077f6956f68e98.patch";
341 stripLen = 1;
342 extraPrefix = "libraries/Cabal/";
343 sha256 = "sha256-yRQ6YmMiwBwiYseC5BsrEtDgFbWvst+maGgDtdD0vAY=";
344 })
345 ]
346
347 ++ lib.optionals (version == "9.4.6") [
348 # Work around a type not being defined when including Rts.h in bytestring's cbits
349 # due to missing feature macros. See https://gitlab.haskell.org/ghc/ghc/-/issues/23810.
350 ./9.4.6-bytestring-posix-source.patch
351 ]
352
353 ++ lib.optionals (stdenv.targetPlatform.isDarwin && stdenv.targetPlatform.isAarch64) [
354 # Prevent the paths module from emitting symbols that we don't use
355 # when building with separate outputs.
356 #
357 # These cause problems as they're not eliminated by GHC's dead code
358 # elimination on aarch64-darwin. (see
359 # https://github.com/NixOS/nixpkgs/issues/140774 for details).
360 (
361 if lib.versionAtLeast version "9.2" then
362 ./Cabal-at-least-3.6-paths-fix-cycle-aarch64-darwin.patch
363 else
364 ./Cabal-3.2-3.4-paths-fix-cycle-aarch64-darwin.patch
365 )
366 ]
367
368 # Fixes stack overrun in rts which crashes an process whenever
369 # freeHaskellFunPtr is called with nixpkgs' hardening flags.
370 # https://gitlab.haskell.org/ghc/ghc/-/issues/25485
371 # https://gitlab.haskell.org/ghc/ghc/-/merge_requests/13599
372 # TODO: patch doesn't apply for < 9.4, but may still be necessary?
373 ++ lib.optionals (lib.versionAtLeast version "9.4") [
374 (fetchpatch {
375 name = "ghc-rts-adjustor-fix-i386-stack-overrun.patch";
376 url = "https://gitlab.haskell.org/ghc/ghc/-/commit/39bb6e583d64738db51441a556d499aa93a4fc4a.patch";
377 sha256 = "0w5fx413z924bi2irsy1l4xapxxhrq158b5gn6jzrbsmhvmpirs0";
378 })
379 ]
380
381 # Before GHC 9.6, GHC, when used to compile C sources (i.e. to drive the CC), would first
382 # invoke the C compiler to generate assembly and later call the assembler on the result of
383 # that operation. Unfortunately, that is brittle in a lot of cases, e.g. when using mismatched
384 # CC / assembler (https://gitlab.haskell.org/ghc/ghc/-/merge_requests/12005). This issue
385 # does not affect us. However, LLVM 18 introduced a check in clang that makes sure no
386 # non private labels occur between .cfi_startproc and .cfi_endproc which causes the
387 # assembly that the same version (!) of clang generates from rts/StgCRun.c to be rejected.
388 # This causes GHC to fail compilation on mach-o platforms ever since we upgraded to
389 # LLVM 19.
390 #
391 # clang compiles the same file without issues whithout the roundtrip via assembly. Thus,
392 # the solution is to backport those changes from GHC 9.6 that skip the intermediate
393 # assembly step.
394 #
395 # https://gitlab.haskell.org/ghc/ghc/-/issues/25608#note_622589
396 # https://gitlab.haskell.org/ghc/ghc/-/merge_requests/6877
397 ++ (
398 if lib.versionAtLeast version "9.4" then
399 [
400 # Need to use this patch so the next one applies, passes file location info to the cc phase
401 (fetchpatch {
402 name = "ghc-add-location-to-cc-phase.patch";
403 url = "https://gitlab.haskell.org/ghc/ghc/-/commit/4a7256a75af2fc0318bef771a06949ffb3939d5a.patch";
404 hash = "sha256-DnTI+i1zMebeWvw75D59vMaEEBb2Nr9HusxTyhmdy2M=";
405 })
406 # Makes Cc phase directly generate object files instead of assembly
407 (fetchpatch {
408 name = "ghc-cc-directly-emit-object.patch";
409 url = "https://gitlab.haskell.org/ghc/ghc/-/commit/96811ba491495b601ec7d6a32bef8563b0292109.patch";
410 hash = "sha256-G8u7/MK/tGOEN8Wxccxj/YIOP7mL2G9Co1WKdHXOo6I=";
411 })
412 ]
413 else
414 [
415 # TODO(@sternenseemann): backport changes to GHC < 9.4 if possible
416 ]
417 );
418
419 postPatch = "patchShebangs .";
420
421 # GHC needs the locale configured during the Haddock phase.
422 LANG = "en_US.UTF-8";
423
424 # GHC is a bit confused on its cross terminology.
425 # TODO(@sternenseemann): investigate coreutils dependencies and pass absolute paths
426 preConfigure = ''
427 for env in $(env | grep '^TARGET_' | sed -E 's|\+?=.*||'); do
428 export "''${env#TARGET_}=''${!env}"
429 done
430 # Stage0 (build->build) which builds stage 1
431 export GHC="${bootPkgs.ghc}/bin/ghc"
432 # GHC is a bit confused on its cross terminology, as these would normally be
433 # the *host* tools.
434 export CC="${toolPath "cc" targetCC}"
435 export CXX="${toolPath "c++" targetCC}"
436 # Use gold to work around https://sourceware.org/bugzilla/show_bug.cgi?id=16177
437 export LD="${toolPath "ld${lib.optionalString useLdGold ".gold"}" targetCC}"
438 export AS="${toolPath "as" targetCC}"
439 export AR="${toolPath "ar" targetCC}"
440 export NM="${toolPath "nm" targetCC}"
441 export RANLIB="${toolPath "ranlib" targetCC}"
442 export READELF="${toolPath "readelf" targetCC}"
443 export STRIP="${toolPath "strip" targetCC}"
444 export OBJDUMP="${toolPath "objdump" targetCC}"
445 ''
446 + lib.optionalString (stdenv.targetPlatform.linker == "cctools") ''
447 export OTOOL="${toolPath "otool" targetCC}"
448 export INSTALL_NAME_TOOL="${toolPath "install_name_tool" targetCC}"
449 ''
450 + lib.optionalString useLLVM ''
451 export LLC="${lib.getBin buildTargetLlvmPackages.llvm}/bin/llc"
452 export OPT="${lib.getBin buildTargetLlvmPackages.llvm}/bin/opt"
453 ''
454 + lib.optionalString (useLLVM && stdenv.targetPlatform.isDarwin) ''
455 # LLVM backend on Darwin needs clang: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/codegens.html#llvm-code-generator-fllvm
456 # The executable we specify via $CLANG is used as an assembler (exclusively, it seems, but this isn't
457 # clarified in any user facing documentation). As such, it'll be called on assembly produced by $CC
458 # which usually comes from the darwin stdenv. To prevent a situation where $CLANG doesn't understand
459 # the assembly it is given, we need to make sure that it matches the LLVM version of $CC if possible.
460 # It is unclear (at the time of writing 2024-09-01) whether $CC should match the LLVM version we use
461 # for llc and opt which would require using a custom darwin stdenv for targetCC.
462 export CLANG="${
463 if targetCC.isClang then
464 toolPath "clang" targetCC
465 else
466 "${buildTargetLlvmPackages.clang}/bin/${buildTargetLlvmPackages.clang.targetPrefix}clang"
467 }"
468 ''
469 + ''
470 # No need for absolute paths since these tools only need to work during the build
471 export CC_STAGE0="$CC_FOR_BUILD"
472 export LD_STAGE0="$LD_FOR_BUILD"
473 export AR_STAGE0="$AR_FOR_BUILD"
474
475 echo -n "${buildMK}" > mk/build.mk
476 ''
477 + lib.optionalString (lib.versionOlder version "9.2" || lib.versionAtLeast version "9.4") ''
478 sed -i -e 's|-isysroot /Developer/SDKs/MacOSX10.5.sdk||' configure
479 ''
480 + lib.optionalString (stdenv.hostPlatform.isLinux && hostPlatform.libc == "glibc") ''
481 export LOCALE_ARCHIVE="${glibcLocales}/lib/locale/locale-archive"
482 ''
483 + lib.optionalString (!stdenv.hostPlatform.isDarwin) ''
484 export NIX_LDFLAGS+=" -rpath $out/lib/ghc-${version}"
485 ''
486 + lib.optionalString stdenv.hostPlatform.isDarwin ''
487 export NIX_LDFLAGS+=" -no_dtrace_dof"
488 ''
489 + lib.optionalString (stdenv.hostPlatform.isDarwin && lib.versionAtLeast version "9.2") ''
490
491 # GHC tries the host xattr /usr/bin/xattr by default which fails since it expects python to be 2.7
492 export XATTR=${lib.getBin xattr}/bin/xattr
493 ''
494 + lib.optionalString targetPlatform.useAndroidPrebuilt ''
495 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
496 ''
497 + lib.optionalString targetPlatform.isMusl ''
498 echo "patching llvm-targets for musl targets..."
499 echo "Cloning these existing '*-linux-gnu*' targets:"
500 grep linux-gnu llvm-targets | sed 's/^/ /'
501 echo "(go go gadget sed)"
502 sed -i 's,\(^.*linux-\)gnu\(.*\)$,\0\n\1musl\2,' llvm-targets
503 echo "llvm-targets now contains these '*-linux-musl*' targets:"
504 grep linux-musl llvm-targets | sed 's/^/ /'
505
506 echo "And now patching to preserve '-musleabi' as done with '-gnueabi'"
507 # (aclocal.m4 is actual source, but patch configure as well since we don't re-gen)
508 for x in configure aclocal.m4; do
509 substituteInPlace $x \
510 --replace '*-android*|*-gnueabi*)' \
511 '*-android*|*-gnueabi*|*-musleabi*)'
512 done
513 ''
514 # HACK: allow bootstrapping with GHC 8.10 which works fine, as we don't have
515 # binary 9.0 packaged. Bootstrapping with 9.2 is broken without hadrian.
516 + lib.optionalString (lib.versions.majorMinor version == "9.4") ''
517 substituteInPlace configure --replace \
518 'MinBootGhcVersion="9.0"' \
519 'MinBootGhcVersion="8.10"'
520 '';
521
522 # Although it is usually correct to pass --host, we don't do that here because
523 # GHC's usage of build, host, and target is non-standard.
524 # See https://gitlab.haskell.org/ghc/ghc/-/wikis/building/cross-compiling
525 # TODO(@Ericson2314): Always pass "--target" and always prefix.
526 configurePlatforms = [
527 "build"
528 ]
529 ++ lib.optional (buildPlatform != hostPlatform || targetPlatform != hostPlatform) "target";
530
531 # `--with` flags for libraries needed for RTS linker
532 configureFlags = [
533 "--datadir=$doc/share/doc/ghc"
534 ]
535 ++ lib.optionals enableTerminfo [
536 "--with-curses-includes=${lib.getDev targetLibs.ncurses}/include"
537 "--with-curses-libraries=${lib.getLib targetLibs.ncurses}/lib"
538 ]
539 ++ lib.optionals (libffi != null) [
540 "--with-system-libffi"
541 "--with-ffi-includes=${targetLibs.libffi.dev}/include"
542 "--with-ffi-libraries=${targetLibs.libffi.out}/lib"
543 ]
544 ++ lib.optionals (targetPlatform == hostPlatform && !enableNativeBignum) [
545 "--with-gmp-includes=${targetLibs.gmp.dev}/include"
546 "--with-gmp-libraries=${targetLibs.gmp.out}/lib"
547 ]
548 ++
549 lib.optionals
550 (targetPlatform == hostPlatform && hostPlatform.libc != "glibc" && !targetPlatform.isWindows)
551 [
552 "--with-iconv-includes=${libiconv}/include"
553 "--with-iconv-libraries=${libiconv}/lib"
554 ]
555 ++ lib.optionals (targetPlatform != hostPlatform) [
556 "--enable-bootstrap-with-devel-snapshot"
557 ]
558 ++ lib.optionals useLdGold [
559 "CFLAGS=-fuse-ld=gold"
560 "CONF_GCC_LINKER_OPTS_STAGE1=-fuse-ld=gold"
561 "CONF_GCC_LINKER_OPTS_STAGE2=-fuse-ld=gold"
562 ]
563 ++ lib.optionals (disableLargeAddressSpace) [
564 "--disable-large-address-space"
565 ]
566 ++ lib.optionals enableUnregisterised [
567 "--enable-unregisterised"
568 ];
569
570 # Make sure we never relax`$PATH` and hooks support for compatibility.
571 strictDeps = true;
572
573 # Don’t add -liconv to LDFLAGS automatically so that GHC will add it itself.
574 dontAddExtraLibs = true;
575
576 nativeBuildInputs = [
577 perl
578 autoconf
579 automake
580 m4
581 python3
582 bootPkgs.alex
583 bootPkgs.happy
584 bootPkgs.hscolour
585 bootPkgs.ghc-settings-edit
586 ]
587 ++ lib.optionals (stdenv.hostPlatform.isDarwin && stdenv.hostPlatform.isAarch64) [
588 autoSignDarwinBinariesHook
589 ]
590 ++ lib.optionals enableDocs [
591 sphinx
592 ]
593 ++ lib.optionals (stdenv.hostPlatform.isDarwin && lib.versions.majorMinor version == "9.0") [
594 # TODO(@sternenseemann): backport addition of XATTR env var like
595 # https://gitlab.haskell.org/ghc/ghc/-/merge_requests/6447
596 xattr
597 ];
598
599 # Everything the stage0 compiler needs to build stage1: CC, bintools, extra libs.
600 # See also GHC, {CC,LD,AR}_STAGE0 in preConfigure.
601 depsBuildBuild = [
602 # N.B. We do not declare bootPkgs.ghc in any of the stdenv.mkDerivation
603 # dependency lists to prevent the bintools setup hook from adding ghc's
604 # lib directory to the linker flags. Instead we tell configure about it
605 # via the GHC environment variable.
606 buildCC
607 # stage0 builds terminfo unconditionally, so we always need ncurses
608 ncurses
609 ];
610 # For building runtime libs
611 depsBuildTarget = toolsForTarget;
612
613 # Prevent stage0 ghc from leaking into the final result. This was an issue
614 # with GHC 9.6.
615 disallowedReferences = [
616 bootPkgs.ghc
617 ];
618
619 buildInputs = [ bash ] ++ (libDeps hostPlatform);
620
621 depsTargetTarget = map lib.getDev (libDeps targetPlatform);
622 depsTargetTargetPropagated = map (lib.getOutput "out") (libDeps targetPlatform);
623
624 # required, because otherwise all symbols from HSffi.o are stripped, and
625 # that in turn causes GHCi to abort
626 stripDebugFlags = [ "-S" ] ++ lib.optional (!targetPlatform.isDarwin) "--keep-file-symbols";
627
628 checkTarget = "test";
629
630 # GHC cannot currently produce outputs that are ready for `-pie` linking.
631 # Thus, disable `pie` hardening, otherwise `recompile with -fPIE` errors appear.
632 # See:
633 # * https://github.com/NixOS/nixpkgs/issues/129247
634 # * https://gitlab.haskell.org/ghc/ghc/-/issues/19580
635 hardeningDisable = [
636 "format"
637 "pie"
638 ];
639
640 # big-parallel allows us to build with more than 2 cores on
641 # Hydra which already warrants a significant speedup
642 requiredSystemFeatures = [ "big-parallel" ];
643
644 # Install occasionally fails due to a race condition in minimal builds.
645 # > /nix/store/wyzpysxwgs3qpvmylm9krmfzh2plicix-coreutils-9.7/bin/install -c -m 755 -d "/nix/store/xzb3390rhvhg2a0cvzmrvjspw1d8nf8h-ghc-riscv64-unknown-linux-gnu-9.4.8/bin"
646 # > install: cannot create regular file '/nix/store/xzb3390rhvhg2a0cvzmrvjspw1d8nf8h-ghc-riscv64-unknown-linux-gnu-9.4.8/lib/ghc-9.4.8': No such file or directory
647 preInstall = ''
648 mkdir -p "$out/lib/${passthru.haskellCompilerName}"
649 '';
650
651 postInstall = ''
652 settingsFile="$out/lib/${targetPrefix}${passthru.haskellCompilerName}/settings"
653
654 # Make the installed GHC use the host->target tools.
655 ghc-settings-edit "$settingsFile" \
656 "C compiler command" "${toolPath "cc" installCC}" \
657 "Haskell CPP command" "${toolPath "cc" installCC}" \
658 "C++ compiler command" "${toolPath "c++" installCC}" \
659 "ld command" "${toolPath "ld${lib.optionalString useLdGold ".gold"}" installCC}" \
660 "Merge objects command" "${toolPath "ld${lib.optionalString useLdGold ".gold"}" installCC}" \
661 "ar command" "${toolPath "ar" installCC}" \
662 "ranlib command" "${toolPath "ranlib" installCC}"
663 ''
664 + lib.optionalString (stdenv.targetPlatform.linker == "cctools") ''
665 ghc-settings-edit "$settingsFile" \
666 "otool command" "${toolPath "otool" installCC}" \
667 "install_name_tool command" "${toolPath "install_name_tool" installCC}"
668 ''
669 + lib.optionalString useLLVM ''
670 ghc-settings-edit "$settingsFile" \
671 "LLVM llc command" "${lib.getBin llvmPackages.llvm}/bin/llc" \
672 "LLVM opt command" "${lib.getBin llvmPackages.llvm}/bin/opt"
673 ''
674 + lib.optionalString (useLLVM && stdenv.targetPlatform.isDarwin) ''
675 ghc-settings-edit "$settingsFile" \
676 "LLVM clang command" "${
677 # See comment for CLANG in preConfigure
678 if installCC.isClang then
679 toolPath "clang" installCC
680 else
681 "${llvmPackages.clang}/bin/${llvmPackages.clang.targetPrefix}clang"
682 }"
683 ''
684 + ''
685
686 # Install the bash completion file.
687 install -D -m 444 utils/completion/ghc.bash $out/share/bash-completion/completions/${targetPrefix}ghc
688 '';
689
690 passthru = {
691 inherit bootPkgs targetPrefix;
692
693 inherit llvmPackages;
694 inherit enableShared;
695
696 # This is used by the haskell builder to query
697 # the presence of the haddock program.
698 hasHaddock = enableHaddockProgram;
699
700 # Our Cabal compiler name
701 haskellCompilerName = "ghc-${version}";
702
703 bootstrapAvailable = lib.meta.availableOn stdenv.buildPlatform bootPkgs.ghc;
704 };
705
706 meta = {
707 homepage = "http://haskell.org/ghc";
708 description = "Glasgow Haskell Compiler";
709 maintainers = with lib.maintainers; [
710 guibou
711 ];
712 teams = [ lib.teams.haskell ];
713 timeout = 24 * 3600;
714 platforms = lib.platforms.all;
715 inherit (bootPkgs.ghc.meta) license;
716 };
717
718 }
719 // lib.optionalAttrs targetPlatform.useAndroidPrebuilt {
720 dontStrip = true;
721 dontPatchELF = true;
722 noAuditTmpdir = true;
723 }
724)