~jojo/Carth

ref: 5cca538db17255b5554fd756768d45be1ada8a7a Carth/src/Codegen.hs -rw-r--r-- 26.4 KiB
5cca538dJoJo Remove interpreter. Won't be compatible with foreign functions 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
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
803
804
805
806
{-# LANGUAGE OverloadedStrings, LambdaCase, TemplateHaskell, TupleSections
  , FlexibleContexts #-}

module Codegen (codegen) where

import LLVM.Prelude (ShortByteString)
import LLVM.AST
import LLVM.AST.Typed
import LLVM.AST.Type hiding (ptr)
import LLVM.AST.DataLayout
import qualified LLVM.AST.Type as LLType
import qualified LLVM.AST.CallingConvention as LLCallConv
import qualified LLVM.AST.Linkage as LLLink
import qualified LLVM.AST.Visibility as LLVis
import qualified LLVM.AST.Constant as LLConst
import qualified LLVM.AST.Float as LLFloat
import qualified LLVM.AST.Global as LLGlob
import qualified LLVM.AST.AddrSpace as LLAddr
import qualified LLVM.AST.FunctionAttribute as LLFnAttr
import LLVM.Internal.DataLayout (withFFIDataLayout)
import LLVM.Internal.FFI.DataLayout (getTypeAllocSize)
import qualified LLVM.Internal.FFI.PtrHierarchy as LLPtrHierarchy
import LLVM.Internal.Coding (encodeM)
import LLVM.Internal.EncodeAST (EncodeAST, defineType)
import LLVM.Internal.Type (createNamedType, setNamedType)
import qualified Foreign.Ptr
import qualified Data.Text.Prettyprint.Doc as Prettyprint
import qualified Codec.Binary.UTF8.String as UTF8.String
import LLVM.Pretty ()
import Data.String
import System.FilePath
import Control.Monad.Writer
import Control.Monad.State
import Control.Monad.Reader
import qualified Data.Char
import Data.Bool
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import qualified Data.Set as Set
import Data.Word
import Data.Foldable
import Data.List
import Data.Composition
import Control.Applicative
import Control.Lens
    (makeLenses, modifying, scribe, (<<+=), use, uses, assign, views, locally)

import Misc
import FreeVars
import qualified MonoAst
import MonoAst hiding (Type, Const)
import Selections


type FFIType = Foreign.Ptr.Ptr LLPtrHierarchy.Type

-- | An instruction that returns a value. The name refers to the fact that a
--   mathematical function always returns a value, but an imperative procedure
--   may only produce side effects.
data FunInstruction = WithRetType Instruction Type

-- TODO: Either treat globals and locals separately - Globals behing pointers,
--       locals not - or treat them the same - stack alloc space for locals.
--       Update: They are both behind pointers now, right? So we could just have
--       a single map?
data Env = Env
    { _localEnv :: Map TypedVar Operand
    , _globalEnv :: Map TypedVar Operand
    }
makeLenses ''Env

data St = St
    { _currentBlockLabel :: Name
    , _currentBlockInstrs :: [Named Instruction]
    , _registerCount :: Word
    }
makeLenses ''St

type Gen' = StateT St (ReaderT Env EncodeAST)

-- | The output of generating a function
data Out = Out
    { _outBlocks :: [BasicBlock]
    , _outStrings :: [(Name, String)]
    , _outFuncs :: [(Name, [TypedVar], TypedVar, Expr)]
    }
makeLenses ''Out

type Gen = WriterT Out Gen'


instance Semigroup Out where
    Out bs1 ss1 fs1 <> Out bs2 ss2 fs2 =
        Out (bs1 <> bs2) (ss1 <> ss2) (fs1 <> fs2)
instance Monoid Out where
    mempty = Out [] [] []

instance Pretty Type where
    pretty' _ = show . Prettyprint.pretty
instance Pretty Name where
    pretty' _ = show . Prettyprint.pretty
instance Pretty Module where
    pretty' _ = show . Prettyprint.pretty


codegen :: FilePath -> Program -> EncodeAST Module
codegen moduleFilePath (Program main (Defs defs) tdefs) = do
    tdefs' <- defineDataTypes tdefs
    let defs' = (TypedVar "main" mainType, main) : Map.toList defs
        genGlobDefs = withGlobDefSigs
            defs'
            (liftA2 (:) genOuterMain (fmap join (mapM genGlobDef defs')))
    globDefs <- runGen' genGlobDefs
    pure Module
        { moduleName = fromString ((takeBaseName moduleFilePath))
        , moduleSourceFileName = fromString moduleFilePath
        , moduleDataLayout = Just cfg_dataLayout
        , moduleTargetTriple = Nothing
        , moduleDefinitions = tdefs' ++ genBuiltins ++ globDefs
        }

-- TODO: Consider separating sizeof calculations to a separate pass preceeding
--       Codegen, so that IO/EncodeAST may be limited to a more overviewable and
--       very self-contained module.
--
-- | Convert data-type definitions from `MonoAst` format to LLVM format, and
--   then both add them to the `EncodeAST` environment so `sizeof` can see them
--   later, and return them as `Definition`s so that they may be exported in the
--   Module AST.
--
--   Note that this method may be inefficient, since we define the data-types
--   twice. The first time manually within this module in order to be able to do
--   `sizeof`, and the second time implicitly within `withModuleFromAST`
--   somewhere when actually compiling the whole module with the LLVM library.
--
--   A data-type is a tagged union, and is represented in LLVM as a struct where
--   the first element is the variant-index as an i64, and the rest of the
--   elements are the field-types of the largest variant wrt allocation size.
defineDataTypes :: TypeDefs -> EncodeAST [Definition]
defineDataTypes tds = do
    -- Forward declare to allow for recursion and unordered defs
    lhss <- forM tds $ \(tc, _) -> do
        let n = mkName (mangleTConst tc)
        (lhs, n') <- createNamedType n
        defineType n n' lhs
        pure (n, lhs)
    forM (zip lhss tds) $ \((n, lhs), (_, vs)) -> do
        let ts = map toLlvmVariantType vs
        sizedTs <- mapM (\t -> fmap (, t) (sizeof t)) ts
        let (_, tmax) = maximum sizedTs
        setNamedType lhs tmax
        pure (TypeDefinition n (Just tmax))

runGen' :: Gen' a -> EncodeAST a
runGen' g = runReaderT
    (evalStateT g initSt)
    Env { _localEnv = Map.empty, _globalEnv = Map.empty }

initSt :: St
initSt = St
    { _currentBlockLabel = "entry"
    , _currentBlockInstrs = []
    , _registerCount = 0
    }

genBuiltins :: [Definition]
genBuiltins = map
    (GlobalDefinition . ($ []))
    [ simpleFunc
        (mkName "malloc")
        [parameter (mkName "size") i64]
        (LLType.ptr typeUnit)
    , simpleFunc (mkName "print-int") [parameter (mkName "n") i64] typeUnit
    ]

genOuterMain :: Gen' Definition
genOuterMain = do
    assign currentBlockLabel (mkName "entry")
    assign currentBlockInstrs []
    (_, Out basicBlocks _ _) <- semiExecRetGen $ do
        f <- lookupVar (TypedVar "main" mainType)
        _ <- app f (ConstantOperand litUnit)
        pure (ConstantOperand (litI32 0))
    pure (GlobalDefinition (simpleFunc (mkName "main") [] i32 basicBlocks))

genGlobDef :: (TypedVar, Expr) -> Gen' [Definition]
genGlobDef (v, e) = case e of
    Fun p (body, _) ->
        fmap (map GlobalDefinition) (genClosureWrappedFunDef v p body)
    _ -> nyi $ "Global non-function defs: " ++ show e

genClosureWrappedFunDef :: TypedVar -> TypedVar -> Expr -> Gen' [Global]
genClosureWrappedFunDef var p body = do
    let name = mangleName var
    fName <- newName'' (unName name `mappend` fromString "_func")
    (f, gs) <- genFunDef' (fName, [], p, body)
    let fRef = LLConst.GlobalReference (LLType.ptr (typeOf f)) fName
    let capturesType = LLType.ptr typeUnit
    let captures = LLConst.Null capturesType
    let closure = litStruct [captures, fRef]
    let closureDef = simpleGlobVar name (typeOf closure) closure
    pure (closureDef : f : gs)

genFunDef :: (Name, [TypedVar], TypedVar, Expr) -> Gen' [Global]
genFunDef = fmap (uncurry (:)) . genFunDef'

genFunDef' :: (Name, [TypedVar], TypedVar, Expr) -> Gen' (Global, [Global])
genFunDef' (name, fvs, (TypedVar p pt), body) = do
    assign currentBlockLabel (mkName "entry")
    assign currentBlockInstrs []

    capturesName <- newName' "captures"
    let capturesType = LLType.ptr typeUnit
    let capturesRef = LocalReference capturesType capturesName

    let ptv = TypedVar p pt
    let pt' = toLlvmType pt
    p' <- newName' p
    let pRef = LocalReference pt' p'

    (rt, Out basicBlocks globStrings lambdaFuncs) <- semiExecRetGen
        (withLocal ptv pRef (genExtractCaptures capturesRef fvs (genExpr body)))

    let ss = map globStrVar globStrings
    ls <- concat <$> mapM genFunDef lambdaFuncs

    let fParams = [parameter capturesName capturesType, parameter p' pt']
    let f = simpleFunc name fParams rt basicBlocks

    pure (f, ss ++ ls)

genExtractCaptures :: Operand -> [TypedVar] -> Gen a -> Gen a
genExtractCaptures capturesPtrGeneric fvs ga = if null fvs
    then ga
    else do
        let capturesType = typeCaptures fvs
        capturesPtr <- emitAnon
            (bitcast capturesPtrGeneric (LLType.ptr capturesType))
        captures <- emitAnon (load capturesPtr)
        captureVals <- mapM
            (\(TypedVar x _, i) -> emitReg' x (extractvalue captures [i]))
            (zip fvs [0 ..])
        withLocals (zip fvs captureVals) ga

genExpr :: Expr -> Gen Operand
genExpr = \case
    Lit c -> fmap ConstantOperand (genConst c)
    Var (TypedVar x t) -> lookupVar (TypedVar x t)
    App f e -> genApp f e
    If p c a -> genIf p c a
    Fun p b -> genLambda p b
    Let ds b -> genLet ds b
    Match e cs tbody -> genMatch e cs (toLlvmType tbody)
    Ction c -> genCtion c

toLlvmDataType :: MonoAst.TConst -> Type
toLlvmDataType = typeNamed . mangleTConst

toLlvmVariantType :: [MonoAst.Type] -> Type
toLlvmVariantType = typeStruct . (i64 :) . map toLlvmType

-- | Convert to the LLVM representation of a type in an expression-context.
toLlvmType :: MonoAst.Type -> Type
toLlvmType = \case
    TPrim tc -> case tc of
        TUnit -> typeUnit
        TInt -> i64
        TDouble -> double
        TChar -> i32
        TStr -> LLType.ptr i8
        TBool -> typeBool
    TFun a r -> typeStruct
        [ LLType.ptr typeUnit
        , LLType.ptr (typeClosureFun (toLlvmType a) (toLlvmType r))
        ]
    TConst t -> typeNamed (mangleTConst t)

genConst :: MonoAst.Const -> Gen LLConst.Constant
genConst = \case
    Unit -> pure litUnit
    Int n -> pure $ litI64 n
    Double x -> pure $ litDouble x
    Char c -> pure $ litI32 (Data.Char.ord c)
    Str s -> do
        var <- newName "strlit"
        scribe outStrings [(var, s)]
        pure $ LLConst.GlobalReference (LLType.ptr i8) var
    Bool b -> pure $ litBool b

lookupVar :: TypedVar -> Gen Operand
lookupVar x = do
    mayLocal <- views localEnv (Map.lookup x)
    mayGlobPtr <- views globalEnv (Map.lookup x)
    case (mayLocal, mayGlobPtr) of
        (Just local, _) -> emitAnon $ load local
        (Nothing, Just globPtr) -> emitAnon $ load globPtr
        (Nothing, Nothing) -> ice $ "Undefined variable " ++ show x

genApp :: Expr -> Expr -> Gen Operand
genApp fe ae = do
    a <- genExpr ae
    case fe of
        Var (TypedVar "print-int" _) ->
            emitAnon (callExtern "print-int" typeUnit [a])
        _ -> do
            closure <- genExpr fe
            app closure a

app :: Operand -> Operand -> Gen Operand
app closure arg = do
    captures <- emitReg' "captures" (extractvalue closure [0])
    f <- emitReg' "function" (extractvalue closure [1])
    emitAnon $ call f [captures, arg]

genIf :: Expr -> Expr -> Expr -> Gen Operand
genIf pred conseq alt = do
    conseqL <- newName "consequent"
    altL <- newName "alternative"
    nextL <- newName "next"
    predV <- genExpr pred
    commitToNewBlock (condbr predV conseqL altL) conseqL
    conseqV <- genExpr conseq
    fromConseqL <- use currentBlockLabel
    commitToNewBlock (br nextL) altL
    altV <- genExpr alt
    fromAltL <- use currentBlockLabel
    commitToNewBlock (br nextL) nextL
    emitAnon (phi [(conseqV, fromConseqL), (altV, fromAltL)])

genLet :: Defs -> Expr -> Gen Operand
genLet (Defs ds) b = do
    let (vs, es) = unzip (Map.toList ds)
    let (ns, ts) = unzip (map (\(TypedVar n t) -> (n, t)) vs)
    ns' <- mapM newName ns
    let ts' = map toLlvmType ts
    withDefSigs (zip vs ns') (mapM genDef (zip3 ns' ts' es) *> genExpr b)

-- TODO: Change global defs to a new type that can be generated by llvm.  As it
--       is now, global non-function variables can't be straight-forwardly
--       generated in general. Either, initialization is delayed until program
--       start, or an interpretation step is added between monomorphization and
--       codegen that evaluates all expressions in relevant contexts, like
--       constexprs.
genDef :: (Name, Type, Expr) -> Gen Operand
genDef (n, t, e) = genVar n t (genExpr e)

genMatch :: Expr -> DecisionTree -> Type -> Gen Operand
genMatch m dt tbody = do
    m' <- genExpr m
    genDecisionTree tbody dt (newSelections m')

genDecisionTree :: Type -> DecisionTree -> Selections Operand -> Gen Operand
genDecisionTree tbody = \case
    MonoAst.DSwitch selector cs def -> genDecisionSwitch selector cs def tbody
    MonoAst.DLeaf l -> genDecisionLeaf l

genDecisionSwitch
    :: MonoAst.Access
    -> Map VariantIx DecisionTree
    -> DecisionTree
    -> Type
    -> Selections Operand
    -> Gen Operand
genDecisionSwitch selector cs def tbody selections = do
    let (variantIxs, variantDts) = unzip (Map.toAscList cs)
    variantLs <- mapM (newName . (++ "_") . ("variant_" ++) . show) variantIxs
    let dests = zip (map litU64 variantIxs) variantLs
    defaultL <- newName "default"
    nextL <- newName "next"
    (m, selections') <- genSelect selector selections
    mVariantIx <- emitReg' "found_variant_ix" (extractvalueFromNamed m i64 [0])
    commitToNewBlock (switch mVariantIx defaultL dests) defaultL
    v <- genDecisionTree tbody def selections'
    let genCase l dt = do
            commitToNewBlock (br nextL) l
            genDecisionTree tbody dt selections'
    vs <- zipWithM genCase variantLs variantDts
    commitToNewBlock (br nextL) nextL
    emitAnon (phi (zip (v : vs) (defaultL : variantLs)))

genDecisionLeaf
    :: (MonoAst.VarBindings, Expr) -> Selections Operand -> Gen Operand
genDecisionLeaf (bs, e) selections =
    flip withLocals (genExpr e) =<< genSelectVarBindings selections bs

genSelect :: Access -> Selections Operand -> Gen (Operand, Selections Operand)
genSelect = select genAs genSub

genSelectVarBindings
    :: Selections Operand -> VarBindings -> Gen [(TypedVar, Operand)]
genSelectVarBindings = selectVarBindings genAs genSub

genAs :: [MonoAst.Type] -> Operand -> Gen Operand
genAs ts matchee = do
    let tvariant = toLlvmVariantType ts
    let tgeneric = typeOf matchee
    pGeneric <- emitReg' "ction_ptr_generic" (alloca tgeneric)
    emit (store matchee pGeneric)
    p <- emitReg' "ction_ptr" (bitcast pGeneric (LLType.ptr tvariant))
    emitReg' "ction" (load p)

genSub :: Word32 -> Operand -> Gen Operand
genSub i matchee = emitReg' "submatchee" (extractvalue matchee (pure (i + 1)))

genCtion :: MonoAst.Ction -> Gen Operand
genCtion (i, tdef, as) = do
    let i' = litU64' i
    as' <- mapM genExpr as
    s <- genStruct (i' : as')
    let t = typeOf s
    let tgeneric = toLlvmDataType tdef
    pGeneric <- emitReg' "ction_ptr_generic" (alloca tgeneric)
    p <- emitReg' "ction_ptr" (bitcast pGeneric (LLType.ptr t))
    emit (store s p)
    emitReg' "ction_generic" (load pGeneric)

-- | A lambda is a pair of a captured environment and a function.  The captured
--   environment must be on the heap, since the closure value needs to be of
--   some specific size, regardless of what the closure captures, so that
--   closures of same types but different captures can be used interchangeably.
--
--   The first parameter of the function is a pointer to an environment of
--   captures and the second parameter is the lambda parameter.
--
--   Inside of the function, first all the captured variables are extracted from
--   the environment, then the body of the function is run.
genLambda :: TypedVar -> (Expr, MonoAst.Type) -> Gen Operand
genLambda p@(TypedVar px pt) (b, bt) = do
    let fvs = Set.toList (Set.delete (TypedVar px pt) (freeVars b))
    captures <- genBoxGeneric =<< genStruct =<< sequence (map lookupVar fvs)
    fname <- newName "lambda_func"
    let ft = typeClosureFun (toLlvmType pt) (toLlvmType bt)
    let f = ConstantOperand (LLConst.GlobalReference (LLType.ptr ft) fname)
    scribe outFuncs [(fname, fvs, p, b)]
    genStruct [captures, f]

genStruct :: [Operand] -> Gen Operand
genStruct xs = do
    let t = typeStruct (map typeOf xs)
    foldlM
        (\s (i, x) -> emitReg' "acc" (insertvalue s x [i]))
        (undef t)
        (zip [0 ..] xs)

genBoxGeneric :: Operand -> Gen Operand
genBoxGeneric x = do
    let t = typeOf x
    ptrGeneric <- genMalloc =<< genSizeof t
    ptr <- emitAnon (bitcast ptrGeneric (LLType.ptr t))
    emit (store x ptr)
    pure ptrGeneric

genMalloc :: Operand -> Gen Operand
genMalloc size = emitAnon (callExtern "malloc" (LLType.ptr typeUnit) [size])

semiExecRetGen :: Gen Operand -> Gen' (Type, Out)
semiExecRetGen gx = runWriterT $ do
    x <- gx
    commitFinalFuncBlock (ret x)
    pure (typeOf x)

globStrVar :: (Name, String) -> Global
globStrVar (name, str) =
    let bytes = UTF8.String.encode str
    in
        simpleGlobVar
            name
            (ArrayType (fromIntegral (length bytes)) i8)
            (LLConst.Array i8 (map (litI8) bytes))

simpleFunc :: Name -> [Parameter] -> Type -> [BasicBlock] -> Global
simpleFunc = ($ []) .** simpleFunc'

simpleFunc'
    :: Name
    -> [Parameter]
    -> Type
    -> [LLFnAttr.FunctionAttribute]
    -> [BasicBlock]
    -> Global
simpleFunc' n ps rt fnAttrs bs = Function
    { LLGlob.linkage = LLLink.External
    , LLGlob.visibility = LLVis.Default
    , LLGlob.dllStorageClass = Nothing
    , LLGlob.callingConvention = cfg_callConv
    , LLGlob.returnAttributes = []
    , LLGlob.returnType = rt
    , LLGlob.name = n
    , LLGlob.parameters = (ps, False)
    , LLGlob.functionAttributes = map Right fnAttrs
    , LLGlob.section = Nothing
    , LLGlob.comdat = Nothing
    , LLGlob.alignment = 0
    , LLGlob.garbageCollectorName = Nothing
    , LLGlob.prefix = Nothing
    , LLGlob.basicBlocks = bs
    , LLGlob.personalityFunction = Nothing
    , LLGlob.metadata = []
    }

simpleGlobVar :: Name -> Type -> LLConst.Constant -> Global
simpleGlobVar name t init = GlobalVariable
    { LLGlob.name = name
    , LLGlob.linkage = LLLink.External
    , LLGlob.visibility = LLVis.Default
    , LLGlob.dllStorageClass = Nothing
    , LLGlob.threadLocalMode = Nothing
    , LLGlob.addrSpace = LLAddr.AddrSpace 0
    , LLGlob.unnamedAddr = Nothing
    , LLGlob.isConstant = True
    , LLGlob.type' = t
    , LLGlob.initializer = Just init
    , LLGlob.section = Nothing
    , LLGlob.comdat = Nothing
    , LLGlob.alignment = 0
    , LLGlob.metadata = []
    }

parameter :: Name -> Type -> LLGlob.Parameter
parameter p pt = LLGlob.Parameter pt p []

genSizeof :: Type -> Gen Operand
genSizeof = fmap litU64' . lift . lift . lift . sizeof

withGlobDefSigs :: MonadReader Env m => [(TypedVar, Expr)] -> m a -> m a
withGlobDefSigs = augment globalEnv . Map.fromList . map
    (\(v@(TypedVar _ t), _) ->
        ( v
        , ConstantOperand
            (LLConst.GlobalReference (LLType.ptr (toLlvmType t)) (mangleName v))
        )
    )

withDefSigs :: [(TypedVar, Name)] -> Gen a -> Gen a
withDefSigs = augment localEnv . Map.fromList . map
    (\(v@(TypedVar _ t), n') ->
        (v, LocalReference (LLType.ptr (toLlvmType t)) n')
    )

withLocals :: [(TypedVar, Operand)] -> Gen a -> Gen a
withLocals = flip (foldr (uncurry withLocal))

-- | Takes a local, stack allocated value, and runs a generator in the
--   environment with the variable
withLocal :: TypedVar -> Operand -> Gen a -> Gen a
withLocal x v gen = do
    vPtr <- genVar' x (pure v)
    withVar x vPtr gen

-- | Takes a local value, allocates a variable for it, and runs a generator in
--   the environment with the variable
withVar :: TypedVar -> Operand -> Gen a -> Gen a
withVar x v = locally localEnv (Map.insert x v)

genVar :: Name -> Type -> Gen Operand -> Gen Operand
genVar n t gen = do
    ptr <- emitReg n (alloca t)
    val <- gen
    emit (store val ptr)
    pure ptr

genVar' :: TypedVar -> Gen Operand -> Gen Operand
genVar' (TypedVar x t) gen = do
    n <- newName x
    ptr <- genVar n (toLlvmType t) gen
    pure ptr

emit :: Instruction -> Gen ()
emit instr = emit' (Do instr)

emit' :: (Named Instruction) -> Gen ()
emit' = modifying currentBlockInstrs . (:)

emitReg :: Name -> FunInstruction -> Gen Operand
emitReg reg (WithRetType instr rt) = do
    emit' (reg := instr)
    pure (LocalReference rt reg)

emitReg' :: String -> FunInstruction -> Gen Operand
emitReg' s instr = newName s >>= flip emitReg instr

emitAnon :: FunInstruction -> Gen Operand
emitAnon instr = newAnonRegister >>= flip emitReg instr

commitFinalFuncBlock :: Terminator -> Gen ()
commitFinalFuncBlock t = commitToNewBlock
    t
    (ice "Continued gen after final block of function was already commited")

commitToNewBlock :: Terminator -> Name -> Gen ()
commitToNewBlock t l = do
    n <- use currentBlockLabel
    is <- uses currentBlockInstrs reverse
    scribe outBlocks [BasicBlock n is (Do t)]
    assign currentBlockLabel l
    assign currentBlockInstrs []

newAnonRegister :: Gen Name
newAnonRegister = fmap UnName (registerCount <<+= 1)

newName :: String -> Gen Name
newName = lift . newName'

newName' :: String -> Gen' Name
newName' s = fmap (mkName . (s ++) . show) (registerCount <<+= 1)

newName'' :: ShortByteString -> Gen' Name
newName'' s =
    fmap (Name . (mappend s) . fromString . show) (registerCount <<+= 1)

-- TODO: Shouldn't need a return type parameter. Should look at global list of
--       hidden builtins or something.
callExtern :: String -> Type -> [Operand] -> FunInstruction
callExtern f rt as = WithRetType (callExtern'' f rt as) rt

callExtern'' :: String -> Type -> [Operand] -> Instruction
callExtern'' f rt as = Call
    { tailCallKind = Just Tail
    , callingConvention = cfg_callConv
    , returnAttributes = []
    , function = Right $ ConstantOperand $ LLConst.GlobalReference
        (LLType.ptr (FunctionType rt (map typeOf as) False))
        (mkName f)
    , arguments = map (, []) as
    , functionAttributes = []
    , metadata = []
    }

undef :: Type -> Operand
undef = ConstantOperand . LLConst.Undef

condbr :: Operand -> Name -> Name -> Terminator
condbr c t f = CondBr c t f []

br :: Name -> Terminator
br = flip Br []

ret :: Operand -> Terminator
ret = flip Ret [] . Just

switch :: Operand -> Name -> [(LLConst.Constant, Name)] -> Terminator
switch x def cs = Switch x def cs []

bitcast :: Operand -> Type -> FunInstruction
bitcast x t = WithRetType (BitCast x t []) t

insertvalue :: Operand -> Operand -> [Word32] -> FunInstruction
insertvalue s e is = WithRetType (InsertValue s e is []) (typeOf s)

extractvalue :: Operand -> [Word32] -> FunInstruction
extractvalue struct is = WithRetType
    (ExtractValue { aggregate = struct, indices' = is, metadata = [] })
    (getIndexed (typeOf struct) is)

extractvalueFromNamed :: Operand -> Type -> [Word32] -> FunInstruction
extractvalueFromNamed struct t is = WithRetType
    (ExtractValue { aggregate = struct, indices' = is, metadata = [] })
    t

store :: Operand -> Operand -> Instruction
store srcVal destPtr = Store
    { volatile = False
    , address = destPtr
    , value = srcVal
    , maybeAtomicity = Nothing
    , alignment = 0
    , metadata = []
    }

load :: Operand -> FunInstruction
load p = WithRetType
    (Load
        { volatile = False
        , address = p
        , maybeAtomicity = Nothing
        , alignment = 0
        , metadata = []
        }
    )
    (getPointee (typeOf p))

phi :: [(Operand, Name)] -> FunInstruction
phi = \case
    [] -> ice "phi was given empty list of cases"
    cs@((op, _) : _) -> let t = typeOf op in WithRetType (Phi t cs []) t

call :: Operand -> [Operand] -> FunInstruction
call f as = WithRetType
    (Call
        { tailCallKind = Just Tail
        , callingConvention = cfg_callConv
        , returnAttributes = []
        , function = Right f
        , arguments = map (, []) as
        , functionAttributes = []
        , metadata = []
        }
    )
    (getFunRet (getPointee (typeOf f)))

alloca :: Type -> FunInstruction
alloca t = WithRetType (Alloca t Nothing 0 []) (LLType.ptr t)

litU64' :: Word64 -> Operand
litU64' = ConstantOperand . litU64

litU64 :: Word64 -> LLConst.Constant
litU64 = litI64 . fromIntegral

litI64 :: Int -> LLConst.Constant
litI64 = LLConst.Int 64 . toInteger

litI32 :: Int -> LLConst.Constant
litI32 = LLConst.Int 32 . toInteger

litI8 :: Integral n => n -> LLConst.Constant
litI8 = LLConst.Int 32 . toInteger

litBool :: Bool -> LLConst.Constant
litBool = LLConst.Int 1 . bool 1 0

litDouble :: Double -> LLConst.Constant
litDouble = LLConst.Float . LLFloat.Double

litStruct :: [LLConst.Constant] -> LLConst.Constant
litStruct = LLConst.Struct Nothing False

litUnit :: LLConst.Constant
litUnit = litStruct []

typeClosureFun :: Type -> Type -> Type
typeClosureFun pt rt = FunctionType
    { resultType = rt
    , argumentTypes = [LLType.ptr (typeCaptures []), pt]
    , isVarArg = False
    }

typeCaptures :: [TypedVar] -> Type
typeCaptures = typeStruct . map (\(TypedVar _ t) -> toLlvmType t)

typeNamed :: String -> Type
typeNamed = NamedTypeReference . mkName

typeStruct :: [Type] -> Type
typeStruct ts = StructureType { isPacked = False, elementTypes = ts }

typeBool :: Type
typeBool = i1

typeUnit :: Type
typeUnit = StructureType { isPacked = False, elementTypes = [] }

getFunRet :: Type -> Type
getFunRet = \case
    FunctionType rt _ _ -> rt
    t -> ice $ "Tried to get return type of non-function type " ++ pretty t

getPointee :: Type -> Type
getPointee = \case
    LLType.PointerType t _ -> t
    t -> ice $ "Tried to get pointee of non-function type " ++ pretty t

getMembers :: Type -> [Type]
getMembers = \case
    StructureType _ members -> members
    t -> ice $ "Tried to get member types of non-struct type " ++ pretty t

getIndexed :: Type -> [Word32] -> Type
getIndexed = foldl' (\t i -> getMembers t !! (fromIntegral i))

mangleName :: TypedVar -> Name
mangleName (TypedVar x t) = mkName (x ++ ":" ++ mangleType t)

mangleType :: MonoAst.Type -> String
mangleType = \case
    TPrim c -> pretty c
    TFun p r -> mangleTConst ("->", [p, r])
    TConst tc -> mangleTConst tc

mangleTConst :: TConst -> String
mangleTConst (c, ts) =
    concat ["(", c, ";", intercalate "," (map mangleType ts), ")"]

unName :: Name -> ShortByteString
unName = \case
    Name s -> s
    UnName n -> fromString (show n)

sizeof :: Type -> EncodeAST Word64
sizeof t = do
    t' <- toFFIType t
    liftIO (withFFIDataLayout cfg_dataLayout $ \dl -> getTypeAllocSize dl t')

-- Note: encodeM requires named-types to be defined in the EncodeAST monad
--       already, which makes sense as e.g. getTypeAllocSize wouldn't make sense
--       to run before all types are defined. As such, make sure to define
--       all type-definitions in the EncodeAST monad first via llvm-hs internal
--       functions createNamedType => defineType => setNamedType.
toFFIType :: Type -> EncodeAST FFIType
toFFIType = encodeM

cfg_dataLayout :: DataLayout
cfg_dataLayout = defaultDataLayout LittleEndian

cfg_callConv :: LLCallConv.CallingConvention
cfg_callConv = LLCallConv.C