-
Notifications
You must be signed in to change notification settings - Fork 7
/
Metadata.hs
1228 lines (1065 loc) · 51.5 KB
/
Metadata.hs
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
module Data.LLVM.BitCode.IR.Metadata (
parseMetadataBlock
, parseMetadataKindEntry
, PartialUnnamedMd(..)
, finalizePartialUnnamedMd
, finalizePValMd
, dedupMetadata
, InstrMdAttachments
, PFnMdAttachments
, PKindMd
, PGlobalAttachments
) where
import Data.LLVM.BitCode.Bitstream
import Data.LLVM.BitCode.IR.Constants
import Data.LLVM.BitCode.Match
import Data.LLVM.BitCode.Parse
import Data.LLVM.BitCode.Record
import Text.LLVM.AST
import Text.LLVM.Labels
import qualified Codec.Binary.UTF8.String as UTF8 (decode)
import Control.Applicative ((<|>))
import Control.Exception (throw)
import Control.Monad (foldM, guard, mplus, when)
import Data.Bits (shiftR, testBit, shiftL, (.&.), (.|.), bit, complement)
import Data.Data (Data)
import Data.Typeable (Typeable)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as Char8 (unpack)
import Data.Either (partitionEithers)
import Data.Functor.Compose (Compose(..), getCompose)
import Data.Generics.Uniplate.Data
import qualified Data.IntMap as IntMap
import Data.List (mapAccumL, foldl')
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, mapMaybe)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Word (Word8,Word32,Word64)
import GHC.Generics (Generic)
import GHC.Stack (HasCallStack, callStack)
import Data.Bifunctor (bimap)
-- Parsing State ---------------------------------------------------------------
data MetadataTable = MetadataTable
{ mtEntries :: MdTable
, mtNextNode :: !Int
, mtNodes :: IntMap.IntMap (Bool, Bool, Int)
-- ^ The entries in the map are: is the entry function local,
-- is the entry distinct, and the implicit id for the node.
} deriving (Show)
emptyMetadataTable ::
Int {- ^ globals seen so far -} ->
MdTable -> MetadataTable
emptyMetadataTable globals es = MetadataTable
{ mtEntries = es
, mtNextNode = globals
, mtNodes = IntMap.empty
}
metadata :: PValMd -> Typed PValue
metadata = Typed (PrimType Metadata) . ValMd
addMetadata :: PValMd -> MetadataTable -> (Int,MetadataTable)
addMetadata val mt = (ix, mt { mtEntries = es' })
where
(ix,es') = addValue' (metadata val) (mtEntries mt)
addMdValue :: Typed PValue -> MetadataTable -> MetadataTable
addMdValue tv mt = mt { mtEntries = addValue tv' (mtEntries mt) }
where
-- explicitly make a metadata value out of a normal value
tv' = Typed { typedType = PrimType Metadata
, typedValue = ValMd (ValMdValue tv)
}
nameNode :: Bool -> Bool -> Int -> MetadataTable -> MetadataTable
nameNode fnLocal isDistinct ix mt = mt
{ mtNodes = IntMap.insert ix (fnLocal,isDistinct,mtNextNode mt) (mtNodes mt)
, mtNextNode = mtNextNode mt + 1
}
addString :: String -> PartialMetadata -> PartialMetadata
addString str pm =
let (ix, mt) = addMetadata (ValMdString str) (pmEntries pm)
in pm { pmEntries = mt
, pmStrings = Map.insert ix str (pmStrings pm)
}
addStrings :: [String] -> PartialMetadata -> PartialMetadata
addStrings strs pm = foldl' (flip addString) pm strs
addLoc :: Bool -> PDebugLoc -> MetadataTable -> MetadataTable
addLoc isDistinct loc mt = nameNode False isDistinct ix mt'
where
(ix,mt') = addMetadata (ValMdLoc loc) mt
addDebugInfo
:: Bool
-> DebugInfo' Int
-> MetadataTable
-> MetadataTable
addDebugInfo isDistinct di mt = nameNode False isDistinct ix mt'
where
(ix,mt') = addMetadata (ValMdDebugInfo di) mt
-- | Add a new node, that might be distinct.
addNode :: Bool -> [Maybe PValMd] -> MetadataTable -> MetadataTable
addNode isDistinct vals mt = nameNode False isDistinct ix mt'
where
(ix,mt') = addMetadata (ValMdNode vals) mt
addOldNode :: Bool -> [Typed PValue] -> MetadataTable -> MetadataTable
addOldNode fnLocal vals mt = nameNode fnLocal False ix mt'
where
(ix,mt') = addMetadata (ValMdNode [ Just (ValMdValue tv) | tv <- vals ]) mt
mdForwardRef :: [String] -> MetadataTable -> Int -> PValMd
mdForwardRef cxt mt ix = fromMaybe fallback nodeRef
where
nodeRef = reference `fmap` IntMap.lookup ix (mtNodes mt)
fallback = case forwardRef cxt ix (mtEntries mt) of
Typed { typedValue = ValMd md } -> md
tv -> ValMdValue tv
reference (False, _, r) = ValMdRef r
reference (_ , _, r) =
let explanation = "Illegal forward reference into function-local metadata."
in throw (BadValueRef callStack cxt explanation r)
mdForwardRefOrNull :: [String] -> MetadataTable -> Int -> Maybe PValMd
mdForwardRefOrNull cxt mt ix | ix > 0 = Just (mdForwardRef cxt mt (ix - 1))
| otherwise = Nothing
mdNodeRef :: HasCallStack
=> [String] -> MetadataTable -> Int -> Int
mdNodeRef cxt mt ix = maybe except prj (IntMap.lookup ix (mtNodes mt))
where explanation = "Bad forward reference into mtNodes"
except = throw (BadValueRef callStack cxt explanation ix)
prj (_, _, x) = x
mdString :: HasCallStack
=> [String] -> PartialMetadata -> Int -> String
mdString cxt partialMeta ix =
let explanation = "Null value when metadata string was expected"
in fromMaybe (throw (BadValueRef callStack cxt explanation ix))
(mdStringOrNull cxt partialMeta ix)
-- | This preferentially fetches the string from the strict string table
-- (@pmStrings@), but will return a forward reference when it can't find it there.
mdStringOrNull :: HasCallStack
=> [String]
-> PartialMetadata
-> Int
-> Maybe String
mdStringOrNull cxt partialMeta ix =
Map.lookup (ix - 1) (pmStrings partialMeta) <|>
case mdForwardRefOrNull cxt (pmEntries partialMeta) ix of
Nothing -> Nothing
Just (ValMdString str) -> Just str
Just _ ->
let explanation = "Non-string metadata when string was expected"
in throw (BadTypeRef callStack cxt explanation ix)
mdStringOrEmpty :: HasCallStack
=> [String]
-> PartialMetadata
-> Int
-> String
mdStringOrEmpty cxt partialMeta = fromMaybe "" . mdStringOrNull cxt partialMeta
mkMdRefTable :: MetadataTable -> MdRefTable
mkMdRefTable mt = IntMap.mapMaybe step (mtNodes mt)
where
step (fnLocal,_,ix) = do
guard (not fnLocal)
return ix
data PartialMetadata = PartialMetadata
{ pmEntries :: MetadataTable
, pmNamedEntries :: Map.Map String [Int]
, pmNextName :: Maybe String
, pmInstrAttachments :: InstrMdAttachments
, pmFnAttachments :: PFnMdAttachments
, pmGlobalAttachments:: PGlobalAttachments
, pmStrings :: Map Int String
-- ^ Forward references to metadata strings are never actually
-- forward references, string blocks (@METADATA_STRINGS@) always come first.
-- So references to them don't need to be inside the @MonadFix@ like
-- references into other 'pmEntries', allowing them to be strict.
--
-- See this comment:
-- - https://github.com/llvm-mirror/llvm/blob/release_40/lib/Bitcode/Reader/MetadataLoader.cpp#L913
-- - https://github.com/llvm-mirror/llvm/blob/release_60/lib/Bitcode/Reader/MetadataLoader.cpp#L1017
} deriving (Show)
emptyPartialMetadata ::
Int {- ^ globals seen so far -} ->
MdTable -> PartialMetadata
emptyPartialMetadata globals es = PartialMetadata
{ pmEntries = emptyMetadataTable globals es
, pmNamedEntries = Map.empty
, pmNextName = Nothing
, pmInstrAttachments = Map.empty
, pmFnAttachments = Map.empty
, pmGlobalAttachments = Map.empty
, pmStrings = Map.empty
}
updateMetadataTable :: (MetadataTable -> MetadataTable)
-> (PartialMetadata -> PartialMetadata)
updateMetadataTable f pm = pm { pmEntries = f (pmEntries pm) }
addGlobalAttachments ::
Symbol {- ^ name of the global to attach to ^ -} ->
(Map.Map KindMd PValMd) {- ^ metadata references to attach ^ -} ->
(PartialMetadata -> PartialMetadata)
addGlobalAttachments sym mds pm =
pm { pmGlobalAttachments = Map.insert sym mds (pmGlobalAttachments pm)
}
setNextName :: String -> PartialMetadata -> PartialMetadata
setNextName name pm = pm { pmNextName = Just name }
addFnAttachment :: PFnMdAttachments -> PartialMetadata -> PartialMetadata
addFnAttachment att pm =
-- left-biased union, since the parser overwrites metadata as it encounters it
pm { pmFnAttachments = Map.union att (pmFnAttachments pm) }
addInstrAttachment :: Int -> [(KindMd,PValMd)]
-> PartialMetadata -> PartialMetadata
addInstrAttachment instr md pm =
pm { pmInstrAttachments = Map.insert instr md (pmInstrAttachments pm) }
nameMetadata :: [Int] -> PartialMetadata -> Parse PartialMetadata
nameMetadata val pm = case pmNextName pm of
Just name -> return $! pm
{ pmNextName = Nothing
, pmNamedEntries = Map.insert name val (pmNamedEntries pm)
}
Nothing -> fail "Expected a metadata name"
-- De-duplicating ---------------------------------------------------------------
-- | This function generically traverses the given unnamed metadata values.
-- When it encounters one with a 'PValMd' inside of it, it looks up that
-- value in the list. If found, it replaces the value with a reference to it.
--
-- Such de-duplication is necessary because the @fallback@ of
-- 'mdForwardRefOrNull' is often called when it is in fact unnecessary, just
-- because the appropriate references aren't available yet.
--
-- This function is concise at the cost of efficiency: In the worst case, every
-- metadata node contains a reference to every other metadata node, and the
-- cost is O(n^2*log(n)) where
-- * n^2 comes from looking at every 'PValMd' inside every 'PartialUnnamedMd'
-- * log(n) is the cost of looking them up in a 'Map'.
dedupMetadata :: Seq PartialUnnamedMd -> Seq PartialUnnamedMd
dedupMetadata pumd = helper (mkPartialUnnamedMdMap pumd) <$> pumd
where helper pumdMap pum =
let pumdMap' = Map.delete (pumValues pum) pumdMap -- don't self-reference
in pum { pumValues = maybeTransform pumdMap' (pumValues pum) }
-- | We avoid erroneously recursing into ValMdValues and exit early on
-- a few other constructors de-duplication wouldn't affect.
maybeTransform :: Map PValMd Int -> PValMd -> PValMd
maybeTransform pumdMap v@(ValMdNode _) = transform (trans pumdMap) v
maybeTransform pumdMap v@(ValMdLoc _) = transform (trans pumdMap) v
maybeTransform pumdMap v@(ValMdDebugInfo _) = transform (trans pumdMap) v
maybeTransform _ v = v
trans :: Map PValMd Int -> PValMd -> PValMd
trans pumdMap v = case Map.lookup v pumdMap of
Just idex -> ValMdRef idex
Nothing -> v
mkPartialUnnamedMdMap :: Seq PartialUnnamedMd -> Map PValMd Int
mkPartialUnnamedMdMap =
foldl' (\mp part -> Map.insert (pumValues part) (pumIndex part) mp) Map.empty
-- Finalizing ---------------------------------------------------------------
namedEntries :: PartialMetadata -> Seq NamedMd
namedEntries = Seq.fromList
. map (uncurry NamedMd)
. Map.toList
. pmNamedEntries
data PartialUnnamedMd = PartialUnnamedMd
{ pumIndex :: Int
, pumValues :: PValMd
, pumDistinct :: Bool
} deriving (Data, Eq, Ord, Generic, Show, Typeable)
finalizePartialUnnamedMd :: PartialUnnamedMd -> Finalize UnnamedMd
finalizePartialUnnamedMd pum = mkUnnamedMd `fmap` finalizePValMd (pumValues pum)
where
mkUnnamedMd v = UnnamedMd
{ umIndex = pumIndex pum
, umValues = v
, umDistinct = pumDistinct pum
}
finalizePValMd :: PValMd -> Finalize ValMd
finalizePValMd = relabel (const requireBbEntryName)
-- | Partition unnamed entries into global and function local unnamed entries.
unnamedEntries :: PartialMetadata -> (Seq PartialUnnamedMd, Seq PartialUnnamedMd)
unnamedEntries pm = bimap Seq.fromList Seq.fromList (partitionEithers (mapMaybe resolveNode (IntMap.toList (mtNodes mt))))
where
mt = pmEntries pm
-- TODO: is this silently eating errors with metadata that's not in the
-- value table (when the lookupValueTableAbs fails)?
resolveNode :: (Int, (Bool, Bool, Int))
-> Maybe (Either PartialUnnamedMd PartialUnnamedMd)
resolveNode (ref,(fnLocal,d,ix)) =
((if fnLocal then Right else Left) <$> lookupNode ref d ix)
lookupNode :: Int -> Bool -> Int -> Maybe PartialUnnamedMd
lookupNode ref d ix = do
tv <- lookupValueTableAbs ref (mtEntries mt)
case tv of
Typed { typedValue = ValMd v } -> do
guard (not (mustAppearInline v))
pure $! PartialUnnamedMd
{ pumIndex = ix
, pumValues = v
, pumDistinct = d
}
_ -> error "Impossible: Only ValMds are stored in mtEntries"
-- DIExpressions and DIArgLists are always printed inline and should never be
-- printed in the global list of unnamed metadata. See
-- https://github.com/llvm/llvm-project/blob/65600cb2a7e940babf6c493503b9d3fd19f8cb06/llvm/lib/IR/AsmWriter.cpp#L1242-L1245
mustAppearInline :: PValMd -> Bool
mustAppearInline (ValMdDebugInfo (DebugInfoExpression{})) = True
mustAppearInline (ValMdDebugInfo (DebugInfoArgList{})) = True
mustAppearInline _ = False
type InstrMdAttachments = Map.Map Int [(KindMd,PValMd)]
type PKindMd = Int
type PFnMdAttachments = Map.Map PKindMd PValMd
type PGlobalAttachments = Map.Map Symbol (Map.Map KindMd PValMd)
type ParsedMetadata =
( Seq NamedMd
, (Seq PartialUnnamedMd, Seq PartialUnnamedMd)
, InstrMdAttachments
, PFnMdAttachments
, PGlobalAttachments
)
parsedMetadata :: PartialMetadata -> ParsedMetadata
parsedMetadata pm =
( namedEntries pm
, unnamedEntries pm
, pmInstrAttachments pm
, pmFnAttachments pm
, pmGlobalAttachments pm
)
-- Applicative composition ------------------------------------------------------------
-- Some utilities for dealing with composition of applicatives
-- | These are useful for avoiding writing 'Compose'
(<$$>) :: forall f g a b. (Functor f, Functor g)
=> (a -> b) -> (f (g a)) -> Compose f g b
h <$$> x = h <$> Compose x
-- | These are useful for avoiding writing 'pure'
-- (i.e. only some parts of your long applicative chain use both effects)
(<<*>) :: forall f g a b. (Applicative f, Applicative g)
=> Compose f g (a -> b) -> (f a) -> Compose f g b
h <<*> x = h <*> Compose (pure <$> x)
-- Metadata Parsing ------------------------------------------------------------
parseMetadataBlock ::
Int {- ^ globals seen so far -} ->
ValueTable -> [Entry] -> Parse ParsedMetadata
parseMetadataBlock globals vt es = label "METADATA_BLOCK" $ do
ms <- getMdTable
let pm0 = emptyPartialMetadata globals ms
rec pm <- foldM (parseMetadataEntry vt (pmEntries pm)) pm0 es
let entries = pmEntries pm
setMdTable (mtEntries entries)
setMdRefs (mkMdRefTable entries)
return (parsedMetadata pm)
-- | Parse an entry in the metadata block.
--
-- XXX this currently relies on the constant block having been parsed already.
-- Though most bitcode examples I've seen are ordered this way, it would be nice
-- to not have to rely on it.
--
-- Based on the function 'parseOneMetadata' in the LLVM source.
parseMetadataEntry :: ValueTable -> MetadataTable -> PartialMetadata -> Entry
-> Parse PartialMetadata
parseMetadataEntry vt mt pm (fromEntry -> Just r) =
let msg = [ "Are you sure you're using a supported version of LLVM/Clang?"
, "Check here: https://github.com/GaloisInc/llvm-pretty-bc-parser"
]
assertRecordSizeBetween lb ub =
let len = length (recordFields r)
in when (len < lb || ub < len) $
fail $ unlines $ [ "Invalid record size: " ++ show len
, "Expected size between " ++ show lb ++ " and " ++ show ub
] ++ msg
assertRecordSizeIn ns =
let len = length (recordFields r)
in when (not (len `elem` ns)) $
fail $ unlines $ [ "Invalid record size: " ++ show len
, "Expected one of: " ++ show ns
] ++ msg
assertRecordSizeAtLeast lb =
let len = length (recordFields r)
in when (len < lb) $
fail $ unlines $ [ "Invalid record size: " ++ show len
, "Expected size of " ++ show lb ++ " or greater"
] ++ msg
in case recordCode r of
-- [values]
1 -> label "METADATA_STRING" $ do
str <- fmap UTF8.decode (parseFields r 0 char) `mplus` parseField r 0 string
return $! addString str pm
-- [type num, value num]
2 -> label "METADATA_VALUE" $ do
assertRecordSizeIn [2]
let field = parseField r
ty <- getType =<< field 0 numeric
when (ty == PrimType Metadata || ty == PrimType Void)
(fail "invalid record")
cxt <- getContext
ix <- field 1 numeric
let tv = forwardRef cxt ix vt
return $! updateMetadataTable (addMdValue tv) pm
-- [n x md num]
3 -> label "METADATA_NODE" (parseMetadataNode False mt r pm)
-- [values]
4 -> label "METADATA_NAME" $ do
name <- fmap UTF8.decode (parseFields r 0 char) `mplus` parseField r 0 cstring
return $! setNextName name pm
-- [n x md num]
5 -> label "METADATA_DISTINCT_NODE" (parseMetadataNode True mt r pm)
-- [n x [id, name]]
6 -> label "METADATA_KIND" $ do
kind <- parseField r 0 numeric
name <- UTF8.decode <$> parseFields r 1 char
addKind kind name
return pm
-- [distinct, line, col, scope, inlined-at?]
7 -> label "METADATA_LOCATION" $ do
-- TODO: broken in 3.7+; needs to be a DILocation rather than an
-- MDLocation, but there appears to be no difference in the
-- bitcode. /sigh/
assertRecordSizeIn [5, 6]
let field = parseField r
cxt <- getContext
isDistinct <- field 0 nonzero
loc <- DebugLoc
<$> field 1 numeric -- dlLine
<*> field 2 numeric -- dlCol
<*> (mdForwardRef cxt mt <$> field 3 numeric) -- dlScope
<*> (mdForwardRefOrNull cxt mt <$> field 4 numeric) -- dlIA
<*> if length (recordFields r) <= 5
then pure False
else parseField r 5 nonzero -- dlImplicit
return $! updateMetadataTable (addLoc isDistinct loc) pm
-- [n x (type num, value num)]
8 -> label "METADATA_OLD_NODE" (parseMetadataOldNode False vt mt r pm)
-- [n x (type num, value num)]
9 -> label "METADATA_OLD_FN_NODE" (parseMetadataOldNode True vt mt r pm)
-- [n x mdnodes]
10 -> label "METADATA_NAMED_NODE" $ do
mdIds <- parseFields r 0 numeric
cxt <- getContext
let ids = map (mdNodeRef cxt mt) mdIds
nameMetadata ids pm
-- [m x [value, [n x [id, mdnode]]]
11 -> label "METADATA_ATTACHMENT" $ do
let recordSize = length (recordFields r)
when (recordSize == 0)
(fail "Invalid record")
if recordSize `mod` 2 == 0
then label "function attachment" $ do
att <- Map.fromList <$> parseAttachment r 0
return $! addFnAttachment att pm
else label "instruction attachment" $ do
inst <- parseField r 0 numeric
patt <- parseAttachment r 1
att <- mapM (\(k,md) -> (,md) <$> getKind k) patt
return $! addInstrAttachment inst att pm
12 -> label "METADATA_GENERIC_DEBUG" $ do
--isDistinct <- parseField r 0 numeric
--tag <- parseField r 1 numeric
--version <- parseField r 2 numeric
--header <- parseField r 3 string
-- TODO: parse all remaining fields
fail "not yet implemented"
13 -> label "METADATA_SUBRANGE" $ do
assertRecordSizeIn [3, 5]
field0 <- parseField r 0 unsigned
let isDistinct = field0 /= 0
-- format = field0 `shiftR` 1
-- TODO: use the format to determine how to parse remaining fields.
-- The current parsing is likely to give the wrong results for bitcode
-- files generated by newer Clang versions, but it won't crash.
diNode <- DISubrange
<$> parseField r 1 numeric -- disrCount
<*> parseField r 2 signedInt64 -- disrLowerBound
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoSubrange diNode)) pm
-- [isBigInt|isUnsigned|distinct, value, name]
14 -> label "METADATA_ENUMERATOR" $ do
assertRecordSizeAtLeast 3
ctx <- getContext
flags <- parseField r 0 numeric
let isDistinct = testBit (flags :: Int) 0
isUnsigned = testBit (flags :: Int) 1
isBigInt = testBit (flags :: Int) 2
name <- mdString ctx pm <$> parseField r 2 numeric
value <-
if isBigInt
-- LLVM 12 or later
then parseWideInteger r 3
-- Pre-LLVM 12
else toInteger <$> parseField r 1 signedInt64
let diEnum = DebugInfoEnumerator name value isUnsigned
return $! updateMetadataTable (addDebugInfo isDistinct diEnum) pm
15 -> label "METADATA_BASIC_TYPE" $ do
assertRecordSizeIn [6, 7]
ctx <- getContext
isDistinct <- parseField r 0 nonzero
dibt <- DIBasicType
<$> parseField r 1 numeric -- dibtTag
<*> (mdString ctx pm <$> parseField r 2 numeric) -- dibtName
<*> parseField r 3 numeric -- dibtSize
<*> parseField r 4 numeric -- dibtAlign
<*> parseField r 5 numeric -- dibtEncoding
<*> if length (recordFields r) <= 6
then pure Nothing
else Just <$> parseField r 6 numeric -- dibtFlags
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoBasicType dibt)) pm
-- [distinct, filename, directory]
16 -> label "METADATA_FILE" $ do
assertRecordSizeIn [3, 5]
ctx <- getContext
isDistinct <- parseField r 0 nonzero
diFile <- DIFile
<$> (mdStringOrEmpty ctx pm <$> parseField r 1 numeric) -- difFilename
<*> (mdStringOrEmpty ctx pm <$> parseField r 2 numeric) -- difDirectory
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoFile diFile)) pm
17 -> label "METADATA_DERIVED_TYPE" $ do
assertRecordSizeBetween 12 14
ctx <- getContext
isDistinct <- parseField r 0 nonzero
didt <- DIDerivedType
<$> parseField r 1 numeric -- didtTag
<*> (mdStringOrNull ctx pm <$> parseField r 2 numeric) -- didtName
<*> (mdForwardRefOrNull ctx mt <$> parseField r 3 numeric) -- didtFile
<*> parseField r 4 numeric -- didtLine
<*> (mdForwardRefOrNull ctx mt <$> parseField r 5 numeric) -- didtScope
<*> (mdForwardRefOrNull ctx mt <$> parseField r 6 numeric) -- didtBaseType
<*> parseField r 7 numeric -- didtSize
<*> parseField r 8 numeric -- didtAlign
<*> parseField r 9 numeric -- didtOffset
<*> parseField r 10 numeric -- didtFlags
<*> (mdForwardRefOrNull ctx mt <$> parseField r 11 numeric) -- didtExtraData
<*> (if length (recordFields r) <= 12
then pure Nothing
else Just <$> parseField r 12 numeric) -- didtDwarfAddressSpace
<*> (if length (recordFields r) <= 13
then pure Nothing
else mdForwardRefOrNull ctx mt <$> parseField r 13 numeric) -- didtAnnotations
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoDerivedType didt)) pm
18 -> label "METADATA_COMPOSITE_TYPE" $ do
assertRecordSizeBetween 16 22
ctx <- getContext
isDistinct <- parseField r 0 nonzero
dict <- DICompositeType
<$> parseField r 1 numeric -- dictTag
<*> (mdStringOrNull ctx pm <$> parseField r 2 numeric) -- dictName
<*> (mdForwardRefOrNull ctx mt <$> parseField r 3 numeric) -- dictFile
<*> parseField r 4 numeric -- dictLine
<*> (mdForwardRefOrNull ctx mt <$> parseField r 5 numeric) -- dictScope
<*> (mdForwardRefOrNull ctx mt <$> parseField r 6 numeric) -- dictBaseType
<*> parseField r 7 numeric -- dictSize
<*> parseField r 8 numeric -- dictAlign
<*> parseField r 9 numeric -- dictOffset
<*> parseField r 10 numeric -- dictFlags
<*> (mdForwardRefOrNull ctx mt <$> parseField r 11 numeric) -- dictElements
<*> parseField r 12 numeric -- dictRuntimeLang
<*> (mdForwardRefOrNull ctx mt <$> parseField r 13 numeric) -- dictVTableHolder
<*> (mdForwardRefOrNull ctx mt <$> parseField r 14 numeric) -- dictTemplateParams
<*> (mdStringOrNull ctx pm <$> parseField r 15 numeric) -- dictIdentifier
<*> (if length (recordFields r) <= 16
then pure Nothing
else mdForwardRefOrNull ctx mt <$> parseField r 16 numeric) -- dictDiscriminator
<*> (if length (recordFields r) <= 17
then pure Nothing
else mdForwardRefOrNull ctx mt <$> parseField r 17 numeric) -- dictDataLocation
<*> (if length (recordFields r) <= 18
then pure Nothing
else mdForwardRefOrNull ctx mt <$> parseField r 18 numeric) -- dictAssociated
<*> (if length (recordFields r) <= 19
then pure Nothing
else mdForwardRefOrNull ctx mt <$> parseField r 19 numeric) -- dictAllocated
<*> (if length (recordFields r) <= 20
then pure Nothing
else mdForwardRefOrNull ctx mt <$> parseField r 20 numeric) -- dictRank
<*> (if length (recordFields r) <= 21
then pure Nothing
else mdForwardRefOrNull ctx mt <$> parseField r 21 numeric) -- dictAnnotations
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoCompositeType dict)) pm
19 -> label "METADATA_SUBROUTINE_TYPE" $ do
assertRecordSizeBetween 3 4
ctx <- getContext
isDistinct <- parseField r 0 nonzero
dist <- DISubroutineType
<$> parseField r 1 numeric -- distFlags
<*> (mdForwardRefOrNull ctx mt <$> parseField r 2 numeric) -- distTypeArray
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoSubroutineType dist)) pm
20 -> label "METADATA_COMPILE_UNIT" $ do
assertRecordSizeBetween 14 22
let recordSize = length (recordFields r)
ctx <- getContext
isDistinct <- parseField r 0 nonzero
dicu <- DICompileUnit
<$> parseField r 1 numeric -- dicuLanguage
<*> (mdForwardRefOrNull ctx mt <$> parseField r 2 numeric) -- dicuFile
<*> (mdStringOrNull ctx pm <$> parseField r 3 numeric) -- dicuProducer
<*> parseField r 4 nonzero -- dicuIsOptimized
<*> (mdStringOrNull ctx pm <$> parseField r 5 numeric) -- dicuFlags
<*> parseField r 6 numeric -- dicuRuntimeVersion
<*> (mdStringOrNull ctx pm <$> parseField r 7 numeric) -- dicuSplitDebugFilename
<*> parseField r 8 numeric -- dicuEmissionKind
<*> (mdForwardRefOrNull ctx mt <$> parseField r 9 numeric) -- dicuEnums
<*> (mdForwardRefOrNull ctx mt <$> parseField r 10 numeric) -- dicuRetainedTypes
<*> (mdForwardRefOrNull ctx mt <$> parseField r 11 numeric) -- dicuSubprograms
<*> (mdForwardRefOrNull ctx mt <$> parseField r 12 numeric) -- dicuGlobals
<*> (mdForwardRefOrNull ctx mt <$> parseField r 13 numeric) -- dicuImports
<*> (if recordSize <= 15
then pure Nothing
else mdForwardRefOrNull ctx mt <$> parseField r 15 numeric) -- dicuMacros
<*> (if recordSize <= 14
then pure 0
else parseField r 14 numeric)
<*> (if recordSize <= 16
then pure True
else parseField r 16 nonzero)
<*> (if recordSize <= 17
then pure False
else parseField r 17 nonzero) -- dicuDebugInfoForProf
<*> (if recordSize <= 18
then pure 0
else parseField r 18 numeric) -- dicuNameTableKind
<*> (if recordSize <= 19
then pure False
else parseField r 19 nonzero) -- dicuRangesBaseAddress
<*> (if recordSize <= 20
then pure Nothing
else mdStringOrNull ctx pm <$> parseField r 20 numeric) -- dicuSysRoot
<*> (if recordSize <= 21
then pure Nothing
else mdStringOrNull ctx pm <$> parseField r 21 numeric) -- dicuSDK
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoCompileUnit dicu)) pm
21 -> label "METADATA_SUBPROGRAM" $ do
-- this one is a bit funky:
-- https://github.com/llvm/llvm-project/blob/release/10.x/llvm/lib/Bitcode/Reader/MetadataLoader.cpp#L1486
assertRecordSizeBetween 18 21
-- A "version" is encoded in the high-order bits of the isDistinct field.
version <- parseField r 0 numeric
let hasSPFlags = (version .&. (0x4 :: Word64)) /= 0;
(diFlags0, spFlags0) <-
if hasSPFlags then
(,) <$> parseField r 11 numeric <*> parseField r 9 numeric
else
(,) <$> parseField r (11 + 2) numeric <*> pure 0
let diFlagMainSubprogram = bit 21 :: Word32
hasOldMainSubprogramFlag = (diFlags0 .&. diFlagMainSubprogram) /= 0
-- CF https://github.com/llvm/llvm-project/blob/release/10.x/llvm/include/llvm/IR/DebugInfoFlags.def
spFlagIsLocal = bit 2
spFlagIsDefinition = bit 3
spFlagIsOptimized = bit 4
spFlagIsMain = bit 8
diFlags :: Word32
diFlags
| hasOldMainSubprogramFlag = diFlags0 .&. complement diFlagMainSubprogram
| otherwise = diFlags0
spFlags :: Word32
spFlags
| hasOldMainSubprogramFlag = spFlags0 .|. spFlagIsMain
| otherwise = spFlags0
-- TODO, isMain isn't exposed via DISubprogram
(isLocal, isDefinition, isOptimized, virtuality, _isMain) <-
if hasSPFlags then
let spIsLocal = spFlags .&. spFlagIsLocal /= 0
spIsDefinition = spFlags .&. spFlagIsDefinition /= 0
spIsOptimized = spFlags .&. spFlagIsOptimized /= 0
spIsMain = spFlags .&. spFlagIsMain /= 0
spVirtuality :: Word8
spVirtuality = fromIntegral (spFlags .&. 0x3)
in return (spIsLocal, spIsDefinition, spIsOptimized, spVirtuality, spIsMain)
else
do (,,,,) <$>
parseField r 7 nonzero <*> -- isLocal
parseField r 8 nonzero <*> -- isDefinition
parseField r 14 nonzero <*> -- isOptimized
parseField r 11 numeric <*> -- virtuality
pure hasOldMainSubprogramFlag -- isMain
let recordSize = length (recordFields r)
isDistinct = (version .&. 0x1 /= 0) || (spFlags .&. spFlagIsDefinition /= 0)
hasUnit = version .&. 0x2 /= 0
offsetA
| not hasSPFlags = 2
| otherwise = 0
offsetB
| not hasSPFlags && recordSize >= 19 = 3
| not hasSPFlags = 2
| otherwise = 0
-- this doesn't seem to be used in our parser...
--hasFn
-- | not hasSPFlags && recordSize >= 19 = not hasUnit
-- | otherwise = False
hasThisAdjustment
| not hasSPFlags = recordSize >= 20
| otherwise = True
hasThrownTypes
| not hasSPFlags = recordSize >= 21
| otherwise = True
hasAnnotations
| not hasSPFlags = False
| otherwise = recordSize >= 19
-- Some additional sanity checking
when (not hasSPFlags && hasUnit)
(assertRecordSizeBetween 19 21)
when (hasSPFlags && not hasUnit)
(fail "DISubprogram record has subprogram flags, but does not have unit. Invalid record.")
ctx <- getContext
-- Forward references that depend on the 'version'
let optFwdRef b n =
if b
then mdForwardRefOrNull ctx mt <$> parseField r n numeric
else pure Nothing
disp <- DISubprogram
<$> (mdForwardRefOrNull ctx mt <$> parseField r 1 numeric) -- dispScope
<*> (mdStringOrNull ctx pm <$> parseField r 2 numeric) -- dispName
<*> (mdStringOrNull ctx pm <$> parseField r 3 numeric) -- dispLinkageName
<*> (mdForwardRefOrNull ctx mt <$> parseField r 4 numeric) -- dispFile
<*> parseField r 5 numeric -- dispLine
<*> (mdForwardRefOrNull ctx mt <$> parseField r 6 numeric) -- dispType
<*> pure isLocal -- dispIsLocal
<*> pure isDefinition -- dispIsDefinition
<*> parseField r (7 + offsetA) numeric -- dispScopeLine
<*> (mdForwardRefOrNull ctx mt <$> parseField r (8 + offsetA) numeric) -- dispContainingType
<*> pure virtuality -- dispVirtuality
<*> parseField r (10 + offsetA) numeric -- dispVirtualIndex
<*> (if hasThisAdjustment
then parseField r (16 + offsetB) numeric
else return 0) -- dispThisAdjustment
<*> pure diFlags -- dispFlags
<*> pure isOptimized -- dispIsOptimized
<*> (optFwdRef hasUnit (12 + offsetB)) -- dispUnit
<*> (mdForwardRefOrNull ctx mt <$> parseField r (13 + offsetB) numeric) -- dispTemplateParams
<*> (mdForwardRefOrNull ctx mt <$> parseField r (14 + offsetB) numeric) -- dispDeclaration
<*> (mdForwardRefOrNull ctx mt <$> parseField r (15 + offsetB) numeric) -- dispVariables
<*> (optFwdRef hasThrownTypes (17 + offsetB)) -- dispThrownTypes
<*> (optFwdRef hasAnnotations (18 + offsetB)) -- dispAnnotations
-- TODO: in the LLVM parser, it then goes into the metadata table
-- and updates function entries to point to subprograms. Is that
-- neccessary for us?
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoSubprogram disp)) pm
22 -> label "METADATA_LEXICAL_BLOCK" $ do
assertRecordSizeIn [5]
cxt <- getContext
isDistinct <- parseField r 0 nonzero
dilb <- DILexicalBlock
<$> (mdForwardRefOrNull cxt mt <$> parseField r 1 numeric) -- dilbScope
<*> (mdForwardRefOrNull cxt mt <$> parseField r 2 numeric) -- dilbFile
<*> parseField r 3 numeric -- dilbLine
<*> parseField r 4 numeric -- dilbColumn
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoLexicalBlock dilb)) pm
23 -> label "METADATA_LEXICAL_BLOCK_FILE" $ do
assertRecordSizeIn [4]
cxt <- getContext
isDistinct <- parseField r 0 nonzero
dilbf <- getCompose $ DILexicalBlockFile -- Composing (Parse . Maybe)
<$$> (mdForwardRefOrNull cxt mt <$> parseField r 1 numeric)
<<*> (mdForwardRefOrNull cxt mt <$> parseField r 2 numeric) -- dilbfFile
<<*> (parseField r 3 numeric) -- dilbfDiscriminator
case dilbf of
Just dilbf' ->
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoLexicalBlockFile dilbf')) pm
Nothing -> fail "Invalid record: scope field not present"
24 -> label "METADATA_NAMESPACE" $ do
assertRecordSizeIn [3, 5]
let isNew =
case length (recordFields r) of
3 -> True
5 -> False
_ -> error "Impossible (METADATA_NAMESPACE)" -- see assertion
let nameIdx = if isNew then 2 else 3
cxt <- getContext
isDistinct <- parseField r 0 nonzero
dins <- DINameSpace
<$> (mdStringOrNull cxt pm <$> parseField r nameIdx numeric) -- dinsName
<*> (mdForwardRef cxt mt <$> parseField r 1 numeric) -- dinsScope
<*> (if isNew
then return (ValMdString "")
else mdForwardRef cxt mt <$> parseField r 2 numeric) -- dinsFile
<*> if isNew then return 0 else parseField r 4 numeric -- dinsLine
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoNameSpace dins)) pm
25 -> label "METADATA_TEMPLATE_TYPE" $ do
assertRecordSizeIn [3, 4]
let recordLength = length (recordFields r)
let hasIsDefault | recordLength == 3 = False
| recordLength == 4 = True
| otherwise = error "Impossible (METADATA_TEMPLATE_TYPE)" -- see assertion
cxt <- getContext
isDistinct <- parseField r 0 nonzero
dittp <- DITemplateTypeParameter
<$> (mdStringOrNull cxt pm <$> parseField r 1 numeric) -- dittpName
<*> (mdForwardRefOrNull cxt mt <$> parseField r 2 numeric) -- dittpType
<*> (if hasIsDefault then Just <$> parseField r 3 boolean else pure Nothing) -- dittpIsDefault
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoTemplateTypeParameter dittp)) pm
26 -> label "METADATA_TEMPLATE_VALUE" $ do
assertRecordSizeIn [5, 6]
let recordLength = length (recordFields r)
let hasIsDefault | recordLength == 5 = False
| recordLength == 6 = True
| otherwise = error "Impossible (METADATA_TEMPLATE_TYPE)" -- see assertion
cxt <- getContext
isDistinct <- parseField r 0 nonzero
ditvp <- DITemplateValueParameter
<$> ( parseField r 1 numeric) -- ditvpTag
<*> (mdStringOrNull cxt pm <$> parseField r 2 numeric) -- ditvpName
<*> (mdForwardRefOrNull cxt mt <$> parseField r 3 numeric) -- ditvpName
<*> (if hasIsDefault then Just <$> parseField r 4 boolean else pure Nothing) -- ditvpIsDefault
<*> (mdForwardRef cxt mt <$> parseField r (if hasIsDefault then 5 else 4) numeric) -- ditvpValue
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoTemplateValueParameter ditvp)) pm
27 -> label "METADATA_GLOBAL_VAR" $ do
assertRecordSizeBetween 11 13
ctx <- getContext
field0 <- parseField r 0 numeric
let isDistinct = testBit field0 0
_version = shiftR field0 1 :: Int
digv <- DIGlobalVariable
<$> (mdForwardRefOrNull ctx mt <$> parseField r 1 numeric) -- digvScope
<*> (mdStringOrNull ctx pm <$> parseField r 2 numeric) -- digvName
<*> (mdStringOrNull ctx pm <$> parseField r 3 numeric) -- digvLinkageName
<*> (mdForwardRefOrNull ctx mt <$> parseField r 4 numeric) -- digvFile
<*> parseField r 5 numeric -- digvLine
<*> (mdForwardRefOrNull ctx mt <$> parseField r 6 numeric) -- digvType
<*> parseField r 7 nonzero -- digvIsLocal
<*> parseField r 8 nonzero -- digvIsDefinition
<*> (mdForwardRefOrNull ctx mt <$> parseField r 9 numeric) -- digvVariable
<*> (mdForwardRefOrNull ctx mt <$> parseField r 10 numeric) -- digvDeclaration
<*> (if length (recordFields r) > 11
then Just <$> parseField r 11 numeric -- digvAlignment
else pure Nothing)
<*> (if length (recordFields r) > 12
then mdForwardRefOrNull ctx mt <$> parseField r 12 numeric -- digvAnnotations
else pure Nothing)
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoGlobalVariable digv)) pm
28 -> label "METADATA_LOCAL_VAR" $ do
-- this one is a bit funky:
-- https://github.com/llvm-mirror/llvm/blob/release_38/lib/Bitcode/Reader/BitcodeReader.cpp#L2308
assertRecordSizeBetween 8 10
ctx <- getContext
field0 <- parseField r 0 numeric
let isDistinct = testBit (field0 :: Word32) 0
hasAlignment = testBit (field0 :: Word32) 1
hasTag | not hasAlignment && length (recordFields r) > 8 = 1
| otherwise = 0
adj i = i + hasTag
alignInBits <-
if hasAlignment
then do n <- parseField r 8 numeric
when ((n :: Word64) > fromIntegral (maxBound :: Word32))
(fail "Alignment value is too large")
return $ Just (fromIntegral n :: Word32)
else return Nothing
dilv <- DILocalVariable
<$> (mdForwardRefOrNull ("dilvScope":ctx) mt
<$> parseField r (adj 1) numeric) -- dilvScope
<*> (mdStringOrNull ("dilvName" :ctx) pm
<$> parseField r (adj 2) numeric) -- dilvName
<*> (mdForwardRefOrNull ("dilvFile" :ctx) mt
<$> parseField r (adj 3) numeric) -- dilvFile
<*> parseField r (adj 4) numeric -- dilvLine
<*> (mdForwardRefOrNull ("dilvType" :ctx) mt
<$> parseField r (adj 5) numeric) -- dilvType
<*> parseField r (adj 6) numeric -- dilvArg
<*> parseField r (adj 7) numeric -- dilvFlags
<*> pure alignInBits -- dilvAlignment
<*> (if hasAlignment && length (recordFields r) > 9
then mdForwardRefOrNull ctx mt <$> parseField r 9 numeric -- dilvAnnotations
else pure Nothing)
return $! updateMetadataTable
(addDebugInfo isDistinct (DebugInfoLocalVariable dilv)) pm
29 -> label "METADATA_EXPRESSION" $ do
isDistinct <- parseField r 0 nonzero
diExpr <- DebugInfoExpression . DIExpression <$> parseFields r 1 numeric