-
Notifications
You must be signed in to change notification settings - Fork 154
/
Internal.hs
1965 lines (1771 loc) · 67.2 KB
/
Internal.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
{-|
Copyright : (C) 2013-2016, University of Twente,
2017-2019, Myrtle Software Ltd
2017-2022, Google Inc.,
2021-2023, QBayLogic B.V.
License : BSD2 (see the file LICENSE)
Maintainer : QBayLogic B.V. <[email protected]>
-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Unsafe #-}
{-# OPTIONS_GHC -fplugin=GHC.TypeLits.Extra.Solver #-}
{-# OPTIONS_GHC -fplugin=GHC.TypeLits.Normalise #-}
{-# OPTIONS_GHC -fplugin=GHC.TypeLits.KnownNat.Solver #-}
-- See: https://github.com/clash-lang/clash-compiler/commit/721fcfa9198925661cd836668705f817bddaae3c
-- as to why we need this.
{-# OPTIONS_GHC -fno-cpr-anal #-}
{-# OPTIONS_HADDOCK show-extensions not-home #-}
module Clash.Signal.Internal
( -- * Datatypes
Signal(..)
, head#
, tail#
-- * Domains
, Domain
, sameDomain
, KnownDomain(..)
, KnownConfiguration
, knownDomainByName
, ActiveEdge(..)
, SActiveEdge(..)
, InitBehavior(..)
, SInitBehavior(..)
, ResetKind(..)
, SResetKind(..)
, ResetPolarity(..)
, SResetPolarity(..)
, DomainConfiguration(..)
, SDomainConfiguration(..)
-- ** Configuration type families
, DomainPeriod
, DomainActiveEdge
, DomainResetKind
, DomainInitBehavior
, DomainResetPolarity
, DomainConfigurationPeriod
, DomainConfigurationActiveEdge
, DomainConfigurationResetKind
, DomainConfigurationInitBehavior
, DomainConfigurationResetPolarity
-- *** Convenience types
, HasSynchronousReset
, HasAsynchronousReset
, HasDefinedInitialValues
-- ** Default domains
, System
, XilinxSystem
, IntelSystem
, vSystem
, vIntelSystem
, vXilinxSystem
-- ** Domain utilities
, VDomainConfiguration(..)
, vDomain
, createDomain
-- * Clocks
, Clock (..)
, ClockN (..)
, DiffClock (..)
, hzToPeriod
, periodToHz
, ClockAB (..)
, clockTicks
, clockTicksEither
-- ** Enabling
, Enable(..)
, toEnable
, fromEnable
, enableGen
-- * Resets
, Reset(..)
, unsafeToReset
, unsafeFromReset
, unsafeToActiveHigh
, unsafeToActiveLow
, unsafeFromActiveHigh
, unsafeFromActiveLow
, invertReset
-- * Basic circuits
, delay#
, register#
, asyncRegister#
, syncRegister#
, registerPowerup#
, mux
-- * Simulation and testbench functions
, clockGen
, tbClockGen
, Femtoseconds(..) -- experimental, do not expose in public API
, fsToHz -- experimental, do not expose in public API
, hzToFs -- experimental, do not expose in public API
, unFemtoseconds -- experimental, do not expose in public API
, mapFemtoseconds -- experimental, do not expose in public API
, tbDynamicClockGen -- experimental, do not expose in public API
, dynamicClockGen -- experimental, do not expose in public API
, resetGen
, resetGenN
-- * Boolean connectives
, (.&&.), (.||.)
-- * Simulation functions (not synthesizable)
, simulate
-- ** lazy version
, simulate_lazy
-- ** Automaton
, signalAutomaton
-- * List \<-\> Signal conversion (not synthesizable)
, sample
, sampleN
, fromList
-- ** lazy versions
, sample_lazy
, sampleN_lazy
, fromList_lazy
-- * QuickCheck combinators
, testFor
-- * Type classes
-- ** 'Eq'-like
, (.==.), (./=.)
-- ** 'Ord'-like
, (.<.), (.<=.), (.>=.), (.>.)
-- ** 'Functor'
, mapSignal#
-- ** 'Applicative'
, signal#
, appSignal#
-- ** 'Foldable'
, foldr#
-- ** 'Traversable'
, traverse#
-- * EXTREMELY EXPERIMENTAL
, joinSignal#
-- * Deprecated
, unsafeFromHighPolarity
, unsafeFromLowPolarity
, unsafeToHighPolarity
, unsafeToLowPolarity
)
where
import Data.IORef (IORef, atomicModifyIORef, newIORef, readIORef)
import Type.Reflection (Typeable)
import Control.Arrow.Transformer.Automaton
#if !MIN_VERSION_base(4,18,0)
import Control.Applicative (liftA2)
#endif
import Control.Applicative (liftA3)
import Control.DeepSeq (NFData)
import Clash.Annotations.Primitive (hasBlackBox, dontTranslate)
import Data.Binary (Binary)
import Data.Char (isAsciiUpper, isAlphaNum, isAscii)
import Data.Coerce (coerce)
import Data.Data (Data)
import Data.Default.Class (Default (..))
import Data.Hashable (Hashable)
import Data.Int (Int64)
import Data.Maybe (isJust)
import Data.Proxy (Proxy(..))
import Data.Ratio (Ratio)
import Data.Type.Equality ((:~:))
import GHC.Generics (Generic)
import GHC.Stack (HasCallStack, withFrozenCallStack)
import GHC.TypeLits (KnownSymbol, KnownNat, Nat, Symbol, type (<=), sameSymbol)
import Language.Haskell.TH.Syntax -- (Lift (..), Q, Dec)
import Language.Haskell.TH.Compat
import Numeric.Natural (Natural)
import System.IO.Unsafe (unsafeInterleaveIO, unsafePerformIO)
import Test.QuickCheck (Arbitrary (..), CoArbitrary(..), Property,
property)
import Clash.CPP (fStrictMapSignal)
import Clash.NamedTypes
import Clash.Promoted.Nat (SNat (..), snatToNum, snatToNatural)
import Clash.Promoted.Symbol (SSymbol (..), ssymbolToString)
import Clash.XException
(NFDataX(..), errorX, isX, deepseqX, defaultSeqX, seqX)
{- $setup
>>> :set -XDataKinds
>>> :set -XMagicHash
>>> :set -XTypeApplications
>>> import Clash.Prelude (SSymbol(..))
>>> import Clash.Signal.Internal
>>> import Clash.Promoted.Nat
>>> import Clash.Promoted.Nat.Literals
>>> import Clash.XException
>>> import Data.Ratio (Ratio)
>>> import Numeric.Natural (Natural)
>>> type System = "System"
>>> let systemClockGen = clockGen @System
>>> let systemResetGen = resetGen @System
>>> import Clash.Explicit.Signal (register)
>>> let registerS = register
>>> let registerA = register
-}
-- * Signal
-- | Determines clock edge memory elements are sensitive to. Not yet
-- implemented.
data ActiveEdge
-- TODO: Implement in blackboxes:
= Rising
-- ^ Elements are sensitive to the rising edge (low-to-high) of the clock.
| Falling
-- ^ Elements are sensitive to the falling edge (high-to-low) of the clock.
deriving (Show, Read, Eq, Ord, Generic, NFData, Data, Hashable, Binary)
-- | Singleton version of 'ActiveEdge'
data SActiveEdge (edge :: ActiveEdge) where
SRising :: SActiveEdge 'Rising
SFalling :: SActiveEdge 'Falling
instance Show (SActiveEdge edge) where
show SRising = "SRising"
show SFalling = "SFalling"
data ResetKind
= Asynchronous
-- ^ Elements respond /asynchronously/ to changes in their reset input. This
-- means that they do /not/ wait for the next active clock edge, but respond
-- immediately instead. Common on Intel FPGA platforms.
| Synchronous
-- ^ Elements respond /synchronously/ to changes in their reset input. This
-- means that changes in their reset input won't take effect until the next
-- active clock edge. Common on Xilinx FPGA platforms.
deriving (Show, Read, Eq, Ord, Generic, NFData, Data, Hashable, Binary)
-- | Singleton version of 'ResetKind'
data SResetKind (resetKind :: ResetKind) where
SAsynchronous :: SResetKind 'Asynchronous
-- See 'Asynchronous' ^
SSynchronous :: SResetKind 'Synchronous
-- See 'Synchronous' ^
instance Show (SResetKind reset) where
show SAsynchronous = "SAsynchronous"
show SSynchronous = "SSynchronous"
-- | Determines the value for which a reset line is considered "active"
data ResetPolarity
= ActiveHigh
-- ^ Reset is considered active if underlying signal is 'True'.
| ActiveLow
-- ^ Reset is considered active if underlying signal is 'False'.
deriving (Eq, Ord, Show, Read, Generic, NFData, Data, Hashable, Binary)
-- | Singleton version of 'ResetPolarity'
data SResetPolarity (polarity :: ResetPolarity) where
SActiveHigh :: SResetPolarity 'ActiveHigh
-- See: 'ActiveHigh' ^
SActiveLow :: SResetPolarity 'ActiveLow
-- See: 'ActiveLow' ^
instance Show (SResetPolarity polarity) where
show SActiveHigh = "SActiveHigh"
show SActiveLow = "SActiveLow"
data InitBehavior
= Unknown
-- ^ Power up value of memory elements is /unknown/.
| Defined
-- ^ If applicable, power up value of a memory element is defined. Applies to
-- 'Clash.Signal.register's for example, but not to
-- 'Clash.Prelude.BlockRam.blockRam'.
deriving (Show, Read, Eq, Ord, Generic, NFData, Data, Hashable, Binary)
data SInitBehavior (init :: InitBehavior) where
SUnknown :: SInitBehavior 'Unknown
-- See: 'Unknown' ^
SDefined :: SInitBehavior 'Defined
-- See: 'Defined' ^
instance Show (SInitBehavior init) where
show SUnknown = "SUnknown"
show SDefined = "SDefined"
-- | A domain with a name (@Domain@). Configures the behavior of various aspects
-- of a circuits. See the documentation of this record's field types for more
-- information on the options.
--
-- See module documentation of "Clash.Explicit.Signal" for more information on
-- how to create custom synthesis domains.
data DomainConfiguration
= DomainConfiguration
{ _name :: Domain
-- ^ Domain name
, _period :: Nat
-- ^ Period of clock in /ps/
, _activeEdge :: ActiveEdge
-- ^ Active edge of the clock
, _resetKind :: ResetKind
-- ^ Whether resets are synchronous (edge-sensitive) or asynchronous (level-sensitive)
, _initBehavior :: InitBehavior
-- ^ Whether the initial (or "power up") value of memory elements is
-- unknown/undefined, or configurable to a specific value
, _resetPolarity :: ResetPolarity
-- ^ Whether resets are active high or active low
}
deriving (Typeable)
-- | Helper type family for 'DomainPeriod'
type family DomainConfigurationPeriod (config :: DomainConfiguration) :: Nat where
DomainConfigurationPeriod ('DomainConfiguration name period edge reset init polarity) = period
-- | Helper type family for 'DomainActiveEdge'
type family DomainConfigurationActiveEdge (config :: DomainConfiguration) :: ActiveEdge where
DomainConfigurationActiveEdge ('DomainConfiguration name period edge reset init polarity) = edge
-- | Helper type family for 'DomainResetKind'
type family DomainConfigurationResetKind (config :: DomainConfiguration) :: ResetKind where
DomainConfigurationResetKind ('DomainConfiguration name period edge reset init polarity) = reset
-- | Helper type family for 'DomainInitBehavior'
type family DomainConfigurationInitBehavior (config :: DomainConfiguration) :: InitBehavior where
DomainConfigurationInitBehavior ('DomainConfiguration name period edge reset init polarity) = init
-- | Helper type family for 'DomainResetPolarity'
type family DomainConfigurationResetPolarity (config :: DomainConfiguration) :: ResetPolarity where
DomainConfigurationResetPolarity ('DomainConfiguration name period edge reset init polarity) = polarity
-- | Convenience type to help to extract a period from a domain. Example usage:
--
-- @
-- myFunc :: (KnownDomain dom, DomainPeriod dom ~ 6000) => ...
-- @
type DomainPeriod (dom :: Domain) =
DomainConfigurationPeriod (KnownConf dom)
-- | Convenience type to help to extract the active edge from a domain. Example
-- usage:
--
-- @
-- myFunc :: (KnownDomain dom, DomainActiveEdge dom ~ 'Rising) => ...
-- @
type DomainActiveEdge (dom :: Domain) =
DomainConfigurationActiveEdge (KnownConf dom)
-- | Convenience type to help to extract the reset synchronicity from a
-- domain. Example usage:
--
-- @
-- myFunc :: (KnownDomain dom, DomainResetKind dom ~ 'Synchronous) => ...
-- @
type DomainResetKind (dom :: Domain) =
DomainConfigurationResetKind (KnownConf dom)
-- | Convenience type to constrain a domain to have synchronous resets. Example
-- usage:
--
-- @
-- myFunc :: HasSynchronousReset dom => ...
-- @
--
-- Using this type implies 'KnownDomain'.
--
-- [Click here for usage hints]("Clash.Explicit.Signal#g:conveniencetypes")
type HasSynchronousReset (dom :: Domain) =
(KnownDomain dom, DomainResetKind dom ~ 'Synchronous)
-- | Convenience type to constrain a domain to have asynchronous resets. Example
-- usage:
--
-- @
-- myFunc :: HasAsynchronousReset dom => ...
-- @
--
-- Using this type implies 'KnownDomain'.
--
-- [Click here for usage hints]("Clash.Explicit.Signal#g:conveniencetypes")
type HasAsynchronousReset (dom :: Domain) =
(KnownDomain dom, DomainResetKind dom ~ 'Asynchronous)
-- | Convenience type to help to extract the initial value behavior from a
-- domain. Example usage:
--
-- @
-- myFunc :: (KnownDomain dom, DomainInitBehavior dom ~ 'Defined) => ...
-- @
type DomainInitBehavior (dom :: Domain) =
DomainConfigurationInitBehavior (KnownConf dom)
-- | Convenience type to constrain a domain to have initial values. Example
-- usage:
--
-- @
-- myFunc :: HasDefinedInitialValues dom => ...
-- @
--
-- Using this type implies 'KnownDomain'.
--
-- Note that there is no @UnknownInitialValues dom@ as a component that works
-- without initial values will also work if it does have them.
--
-- [Click here for usage hints]("Clash.Explicit.Signal#g:conveniencetypes")
type HasDefinedInitialValues (dom :: Domain) =
(KnownDomain dom, DomainInitBehavior dom ~ 'Defined)
-- | Convenience type to help to extract the reset polarity from a domain.
-- Example usage:
--
-- @
-- myFunc :: (KnownDomain dom, DomainResetPolarity dom ~ 'ActiveHigh) => ...
-- @
type DomainResetPolarity (dom :: Domain) =
DomainConfigurationResetPolarity (KnownConf dom)
-- | Singleton version of 'DomainConfiguration'
data SDomainConfiguration (dom :: Domain) (conf :: DomainConfiguration) where
SDomainConfiguration ::
{ sName :: SSymbol dom
-- ^ Domain name
, sPeriod :: SNat period
-- ^ Period of clock in /ps/
, sActiveEdge :: SActiveEdge edge
-- ^ Active edge of the clock (not yet implemented)
, sResetKind :: SResetKind reset
-- ^ Whether resets are synchronous (edge-sensitive) or asynchronous (level-sensitive)
, sInitBehavior :: SInitBehavior init
-- ^ Whether the initial (or "power up") value of memory elements is
-- unknown/undefined, or configurable to a specific value
, sResetPolarity :: SResetPolarity polarity
-- ^ Whether resets are active high or active low
} -> SDomainConfiguration dom ('DomainConfiguration dom period edge reset init polarity)
deriving instance Show (SDomainConfiguration dom conf)
type KnownConfiguration dom conf = (KnownDomain dom, KnownConf dom ~ conf)
-- | A 'KnownDomain' constraint indicates that a circuit's behavior depends on
-- some properties of a domain. See 'DomainConfiguration' for more information.
class (KnownSymbol dom, KnownNat (DomainPeriod dom)) => KnownDomain (dom :: Domain) where
type KnownConf dom :: DomainConfiguration
-- | Returns 'SDomainConfiguration' corresponding to an instance's 'DomainConfiguration'.
--
-- Example usage:
--
-- >>> knownDomain @System
-- SDomainConfiguration {sName = SSymbol @"System", sPeriod = SNat @10000, sActiveEdge = SRising, sResetKind = SAsynchronous, sInitBehavior = SDefined, sResetPolarity = SActiveHigh}
knownDomain :: SDomainConfiguration dom (KnownConf dom)
-- | Version of 'knownDomain' that takes a 'SSymbol'. For example:
--
-- >>> knownDomainByName (SSymbol @"System")
-- SDomainConfiguration {sName = SSymbol @"System", sPeriod = SNat @10000, sActiveEdge = SRising, sResetKind = SAsynchronous, sInitBehavior = SDefined, sResetPolarity = SActiveHigh}
knownDomainByName
:: forall dom
. KnownDomain dom
=> SSymbol dom
-> SDomainConfiguration dom (KnownConf dom)
knownDomainByName =
const knownDomain
{-# INLINE knownDomainByName #-}
-- | A /clock/ (and /reset/) dom with clocks running at 100 MHz
instance KnownDomain System where
type KnownConf System = 'DomainConfiguration System 10000 'Rising 'Asynchronous 'Defined 'ActiveHigh
knownDomain = SDomainConfiguration SSymbol SNat SRising SAsynchronous SDefined SActiveHigh
-- | System instance with defaults set for Xilinx FPGAs
instance KnownDomain XilinxSystem where
type KnownConf XilinxSystem = 'DomainConfiguration XilinxSystem 10000 'Rising 'Synchronous 'Defined 'ActiveHigh
knownDomain = SDomainConfiguration SSymbol SNat SRising SSynchronous SDefined SActiveHigh
-- | System instance with defaults set for Intel FPGAs
instance KnownDomain IntelSystem where
type KnownConf IntelSystem = 'DomainConfiguration IntelSystem 10000 'Rising 'Asynchronous 'Defined 'ActiveHigh
knownDomain = SDomainConfiguration SSymbol SNat SRising SAsynchronous SDefined SActiveHigh
-- | Convenience value to allow easy "subclassing" of System domain. Should
-- be used in combination with 'createDomain'. For example, if you just want to
-- change the period but leave all other settings intact use:
--
-- > createDomain vSystem{vName="System10", vPeriod=10}
--
vSystem :: VDomainConfiguration
vSystem = vDomain (knownDomain @System)
-- | A clock (and reset) dom with clocks running at 100 MHz. Memory elements
-- respond to the rising edge of the clock, and asynchronously to changes in
-- reset signals. It has defined initial values, and active-high resets.
--
-- See module documentation of "Clash.Explicit.Signal" for more information on
-- how to create custom synthesis domains.
type System = ("System" :: Domain)
-- | Convenience value to allow easy "subclassing" of IntelSystem domain. Should
-- be used in combination with 'createDomain'. For example, if you just want to
-- change the period but leave all other settings intact use:
--
-- > createDomain vIntelSystem{vName="Intel10", vPeriod=10}
--
vIntelSystem :: VDomainConfiguration
vIntelSystem = vDomain (knownDomain @IntelSystem)
-- | A clock (and reset) dom with clocks running at 100 MHz. Memory elements
-- respond to the rising edge of the clock, and asynchronously to changes in
-- reset signals. It has defined initial values, and active-high resets.
--
-- See module documentation of "Clash.Explicit.Signal" for more information on
-- how to create custom synthesis domains.
type IntelSystem = ("IntelSystem" :: Domain)
-- | Convenience value to allow easy "subclassing" of XilinxSystem domain. Should
-- be used in combination with 'createDomain'. For example, if you just want to
-- change the period but leave all other settings intact use:
--
-- > createDomain vXilinxSystem{vName="Xilinx10", vPeriod=10}
--
vXilinxSystem :: VDomainConfiguration
vXilinxSystem = vDomain (knownDomain @XilinxSystem)
-- | A clock (and reset) dom with clocks running at 100 MHz. Memory elements
-- respond to the rising edge of the clock, and synchronously to changes in
-- reset signals. It has defined initial values, and active-high resets.
--
-- See module documentation of "Clash.Explicit.Signal" for more information on
-- how to create custom synthesis domains.
type XilinxSystem = ("XilinxSystem" :: Domain)
-- | Same as SDomainConfiguration but allows for easy updates through record update syntax.
-- Should be used in combination with 'vDomain' and 'createDomain'. Example:
--
-- > createDomain (knownVDomain @System){vName="System10", vPeriod=10}
--
-- This duplicates the settings in the 'System' domain, replaces the name and
-- period, and creates an instance for it. As most users often want to update
-- the system domain, a shortcut is available in the form:
--
-- > createDomain vSystem{vName="System10", vPeriod=10}
--
data VDomainConfiguration
= VDomainConfiguration
{ vName :: String
-- ^ Corresponds to '_name' on 'DomainConfiguration'
, vPeriod :: Natural
-- ^ Corresponds to '_period' on 'DomainConfiguration'
, vActiveEdge :: ActiveEdge
-- ^ Corresponds to '_activeEdge' on 'DomainConfiguration'
, vResetKind :: ResetKind
-- ^ Corresponds to '_resetKind' on 'DomainConfiguration'
, vInitBehavior :: InitBehavior
-- ^ Corresponds to '_initBehavior' on 'DomainConfiguration'
, vResetPolarity :: ResetPolarity
-- ^ Corresponds to '_resetPolarity' on 'DomainConfiguration'
}
deriving (Eq, Generic, NFData, Show, Read, Binary)
-- | Convert 'SDomainConfiguration' to 'VDomainConfiguration'. Should be used in combination with
-- 'createDomain' only.
vDomain :: SDomainConfiguration dom conf -> VDomainConfiguration
vDomain (SDomainConfiguration dom period edge reset init_ polarity) =
VDomainConfiguration
(ssymbolToString dom)
(snatToNatural period)
(case edge of {SRising -> Rising; SFalling -> Falling})
(case reset of {SAsynchronous -> Asynchronous; SSynchronous -> Synchronous})
(case init_ of {SDefined -> Defined; SUnknown -> Unknown})
(case polarity of {SActiveHigh -> ActiveHigh; SActiveLow -> ActiveLow})
-- TODO: Function might reject valid type names. Figure out what's allowed.
isValidDomainName :: String -> Bool
isValidDomainName (x:xs) = isAsciiUpper x && all isAscii xs && all isAlphaNum xs
isValidDomainName _ = False
-- | Convenience method to express new domains in terms of others.
--
-- > createDomain (knownVDomain @System){vName="System10", vPeriod=10}
--
-- This duplicates the settings in the "System" domain, replaces the name and
-- period, and creates an instance for it. As most users often want to update
-- the system domain, a shortcut is available in the form:
--
-- > createDomain vSystem{vName="System10", vPeriod=10}
--
-- The function will create two extra identifiers. The first:
--
-- > type System10 = ..
--
-- You can use that as the dom to Clocks\/Resets\/Enables\/Signals. For example:
-- @Signal System10 Int@. Additionally, it will create a 'VDomainConfiguration' that you can
-- use in later calls to 'createDomain':
--
-- > vSystem10 = knownVDomain @System10
--
-- It will also make @System10@ an instance of 'KnownDomain'.
--
-- If either identifier is already in scope it will not be generated a second time.
-- Note: This can be useful for example when documenting a new domain:
--
-- > -- | Here is some documentation for CustomDomain
-- > type CustomDomain = ("CustomDomain" :: Domain)
-- >
-- > -- | Here is some documentation for vCustomDomain
-- > createDomain vSystem{vName="CustomDomain"}
createDomain :: VDomainConfiguration -> Q [Dec]
createDomain (VDomainConfiguration name period edge reset init_ polarity) =
if isValidDomainName name then do
kdType <- [t| KnownDomain $nameT |]
kcType <- [t| ('DomainConfiguration $nameT $periodT $edgeT $resetKindT $initT $polarityT) |]
sDom <- [| SDomainConfiguration SSymbol SNat $edgeE $resetKindE $initE $polarityE |]
let vNameImpl = AppE (VarE 'vDomain) (AppTypeE (VarE 'knownDomain) (LitT (StrTyLit name)))
kdImpl = FunD 'knownDomain [Clause [] (NormalB sDom) []]
kcImpl = mkTySynInstD ''KnownConf [LitT (StrTyLit name)] kcType
vName' = mkName ('v':name)
tySynExists <- isJust <$> lookupTypeName name
vHelperExists <- isJust <$> lookupValueName ('v':name)
pure $ concat
[
[ -- Type synonym (ex: type System = "System")
TySynD (mkName name) [] (LitT (StrTyLit name) `SigT` ConT ''Domain)
| not tySynExists
]
, concat
[ -- vDomain helper (ex: vSystem = vDomain (knownDomain @System))
[ SigD vName' (ConT ''VDomainConfiguration)
, FunD vName' [Clause [] (NormalB vNameImpl) []]
]
| not vHelperExists
]
, [ -- KnownDomain instance (ex: instance KnownDomain "System" where ...)
InstanceD Nothing [] kdType [kcImpl, kdImpl]
]
]
else
error ("Domain names should be a valid Haskell type name, not: " ++ name)
where
edgeE =
pure $
case edge of
Rising -> ConE 'SRising
Falling -> ConE 'SFalling
resetKindE =
pure $
case reset of
Asynchronous -> ConE 'SAsynchronous
Synchronous -> ConE 'SSynchronous
initE =
pure $
case init_ of
Unknown -> ConE 'SUnknown
Defined -> ConE 'SDefined
polarityE =
pure $
case polarity of
ActiveHigh -> ConE 'SActiveHigh
ActiveLow -> ConE 'SActiveLow
nameT = pure (LitT (StrTyLit name))
periodT = pure (LitT (NumTyLit (toInteger period)))
edgeT =
pure $
case edge of
Rising -> PromotedT 'Rising
Falling -> PromotedT 'Falling
resetKindT =
pure $
case reset of
Asynchronous -> PromotedT 'Asynchronous
Synchronous -> PromotedT 'Synchronous
initT =
pure $
case init_ of
Unknown -> PromotedT 'Unknown
Defined -> PromotedT 'Defined
polarityT =
pure $
case polarity of
ActiveHigh -> PromotedT 'ActiveHigh
ActiveLow -> PromotedT 'ActiveLow
type Domain = Symbol
-- | We either get evidence that this function was instantiated with the same
-- domains, or Nothing.
sameDomain
:: forall (domA :: Domain) (domB :: Domain)
. (KnownDomain domA, KnownDomain domB)
=> Maybe (domA :~: domB)
sameDomain = sameSymbol (Proxy @domA) (Proxy @domB)
infixr 5 :-
{- | Clash has synchronous 'Signal's in the form of:
@
'Signal' (dom :: 'Domain') a
@
Where /a/ is the type of the value of the 'Signal', for example /Int/ or /Bool/,
and /dom/ is the /clock-/ (and /reset-/) domain to which the memory elements
manipulating these 'Signal's belong.
The type-parameter, /dom/, is of the kind 'Domain' - a simple string. That
string refers to a single /synthesis domain/. A synthesis domain describes the
behavior of certain aspects of memory elements in it.
* __NB__: \"Bad things\"™ happen when you actually use a clock period of @0@,
so do __not__ do that!
* __NB__: You should be judicious using a clock with period of @1@ as you can
never create a clock that goes any faster!
* __NB__: For the best compatibility make sure your period is divisible by 2,
because some VHDL simulators don't support fractions of picoseconds.
* __NB__: Whether 'System' has good defaults depends on your target platform.
Check out 'IntelSystem' and 'XilinxSystem' too!
Signals have the <https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role>
>>> :i Signal
type role Signal nominal representational
...
as it is safe to coerce the underlying value of a signal, but not safe to coerce
a signal between different synthesis domains.
See the module documentation of "Clash.Signal" for more information about
domains.
-}
type role Signal nominal representational
data Signal (dom :: Domain) a
-- | The constructor, @(':-')@, is __not__ synthesizable.
= a :- Signal dom a
head# :: Signal dom a -> a
head# (x' :- _ ) = x'
tail# :: Signal dom a -> Signal dom a
tail# (_ :- xs') = xs'
instance Show a => Show (Signal dom a) where
show (x :- xs) = show x ++ " " ++ show xs
instance Lift a => Lift (Signal dom a) where
lift ~(x :- _) = [| signal# x |]
#if MIN_VERSION_template_haskell(2,16,0)
liftTyped = liftTypedFromUntyped
#endif
instance Default a => Default (Signal dom a) where
def = signal# def
instance Functor (Signal dom) where
fmap = mapSignal#
mapSignal# :: forall a b dom. (a -> b) -> Signal dom a -> Signal dom b
mapSignal# f = go
where
-- See -fstrict-mapSignal documentation in clash-prelude.cabal
theSeq = if fStrictMapSignal then seqX else flip const
go ~(xs@(a :- as)) = f a :- (a `theSeq` (xs `seq` go as))
-- See: https://github.com/clash-lang/clash-compiler/pull/2511
{-# CLASH_OPAQUE mapSignal# #-}
{-# ANN mapSignal# hasBlackBox #-}
instance Applicative (Signal dom) where
pure = signal#
(<*>) = appSignal#
signal# :: a -> Signal dom a
signal# a = let s = a :- s in s
-- See: https://github.com/clash-lang/clash-compiler/pull/2511
{-# CLASH_OPAQUE signal# #-}
{-# ANN signal# hasBlackBox #-}
appSignal# :: Signal dom (a -> b) -> Signal dom a -> Signal dom b
appSignal# (f :- fs) xs@(~(a :- as)) = f a :- (xs `seq` appSignal# fs as) -- See [NOTE: Lazy ap]
-- See: https://github.com/clash-lang/clash-compiler/pull/2511
{-# CLASH_OPAQUE appSignal# #-}
{-# ANN appSignal# hasBlackBox #-}
instance NFDataX a => NFDataX (Signal domain a) where
deepErrorX = pure . deepErrorX
ensureSpine s = case isX s of
Left e -> deepErrorX e
Right (a :- s') -> ensureSpine a :- ensureSpine s'
hasUndefined = error "hasUndefined on (Signal domain a): No sensible implementation exists"
rnfX = error "rnfX on (Signal domain a): No sensible implementation exists"
{- NOTE: Lazy ap
Signal's ap, i.e (Applicative.<*>), must be lazy in it's second argument:
> appSignal :: Signal clk (a -> b) -> Signal clk a -> Signal clk b
> appSignal (f :- fs) ~(a :- as) = f a :- appSignal fs as
because some feedback loops, such as the loop described in 'system' in the
example at https://hackage.haskell.org/package/clash-prelude-1.0.0/docs/Clash-Prelude-BlockRam.html,
will lead to "Exception <<loop>>".
However, this "naive" lazy version is _too_ lazy and induces spaceleaks.
The current version:
> appSignal# :: Signal clk (a -> b) -> Signal clk a -> Signal clk b
> appSignal# (f :- fs) xs@(~(a :- as)) = f a :- (xs `seq` appSignal# fs as)
Is lazy enough to handle the earlier mentioned feedback loops, but doesn't leak
(as much) memory like the "naive" lazy version, because the Signal constructor
of the second argument is evaluated as soon as the tail of the result is evaluated.
-}
-- | __WARNING: EXTREMELY EXPERIMENTAL__
--
-- The circuit semantics of this operation are unclear and/or non-existent.
-- There is a good reason there is no 'Monad' instance for 'Signal'.
--
-- Is currently treated as 'id' by the Clash compiler.
joinSignal# :: Signal dom (Signal dom a) -> Signal dom a
joinSignal# ~(xs :- xss) = head# xs :- joinSignal# (mapSignal# tail# xss)
-- See: https://github.com/clash-lang/clash-compiler/pull/2511
{-# CLASH_OPAQUE joinSignal# #-}
{-# ANN joinSignal# hasBlackBox #-}
instance Num a => Num (Signal dom a) where
(+) = liftA2 (+)
(-) = liftA2 (-)
(*) = liftA2 (*)
negate = fmap negate
abs = fmap abs
signum = fmap signum
fromInteger = signal# . fromInteger
-- | __NB__: Not synthesizable
--
-- __NB__: In \"@'foldr' f z s@\":
--
-- * The function @f@ should be /lazy/ in its second argument.
-- * The @z@ element will never be used.
instance Foldable (Signal dom) where
foldr = foldr#
-- | __NB__: Not synthesizable
--
-- __NB__: In \"@'foldr#' f z s@\":
--
-- * The function @f@ should be /lazy/ in its second argument.
-- * The @z@ element will never be used.
foldr# :: (a -> b -> b) -> b -> Signal dom a -> b
foldr# f z (a :- s) = a `f` (foldr# f z s)
-- See: https://github.com/clash-lang/clash-compiler/pull/2511
{-# CLASH_OPAQUE foldr# #-}
{-# ANN foldr# hasBlackBox #-}
instance Traversable (Signal dom) where
traverse = traverse#
traverse# :: Applicative f => (a -> f b) -> Signal dom a -> f (Signal dom b)
traverse# f (a :- s) = (:-) <$> f a <*> traverse# f s
-- See: https://github.com/clash-lang/clash-compiler/pull/2511
{-# CLASH_OPAQUE traverse# #-}
{-# ANN traverse# hasBlackBox #-}
-- * Clocks, resets, and enables
-- | A signal of booleans, indicating whether a component is enabled. No special
-- meaning is implied, it's up to the component itself to decide how to respond
-- to its enable line. It is used throughout Clash as a global enable signal.
data Enable dom = Enable (Signal dom Bool)
-- | Convert 'Enable' construct to its underlying representation: a signal of
-- bools.
fromEnable :: Enable dom -> Signal dom Bool
fromEnable (Enable x) = x
{-# INLINE fromEnable #-}
-- | Convert a signal of bools to an 'Enable' construct
toEnable :: Signal dom Bool -> Enable dom
toEnable = Enable
{-# INLINE toEnable #-}
-- | Enable generator for some domain. Is simply always True.
enableGen :: Enable dom
enableGen = toEnable (pure True)
-- | A clock signal belonging to a domain named /dom/.
data Clock (dom :: Domain) = Clock
{ -- | Domain associated with the clock
clockTag :: SSymbol dom
-- | Periods of the clock. This is an experimental feature used to simulate
-- clock frequency correction mechanisms. Currently, all ways to contruct
-- such a clock are hidden from the public API.
, clockPeriods :: Maybe (Signal dom Femtoseconds)
}
instance Show (Clock dom) where
show (Clock dom Nothing) = "<Clock: " ++ ssymbolToString dom ++ ">"
show (Clock dom _) = "<Dynamic clock: " ++ ssymbolToString dom ++ ">"
-- | The negative or inverted phase of a differential clock signal. HDL
-- generation will treat it the same as 'Clock', except that no @create_clock@
-- command is issued in the SDC file for 'ClockN'. Used in 'DiffClock'.
newtype ClockN (dom :: Domain) = ClockN { clockNTag :: SSymbol dom }
instance Show (ClockN dom) where
show (ClockN dom) = "<ClockN: " ++ ssymbolToString dom ++ ">"
-- | A differential clock signal belonging to a domain named /dom/. The clock
-- input of a design with such an input has two ports which are in antiphase.
-- The first input is the positive phase, the second the negative phase. When
-- using 'Clash.Annotations.TH.makeTopEntity', the names of the inputs will end
-- in @_p@ and @_n@ respectively.
data DiffClock (dom :: Domain) =
DiffClock ("p" ::: Clock dom) ("n" ::: ClockN dom)
instance Show (DiffClock dom) where
show (DiffClock (Clock dom Nothing) _) =
"<DiffClock: " ++ ssymbolToString dom ++ ">"
show (DiffClock (Clock dom _) _) =
"<Dynamic DiffClock: " ++ ssymbolToString dom ++ ">"
-- | Clock generator for simulations. Do __not__ use this clock generator for
-- the /testBench/ function, use 'tbClockGen' instead.
--
-- To be used like:
--
-- @
-- clkSystem = clockGen @System
-- @
--
-- See 'DomainConfiguration' for more information on how to use synthesis domains.
clockGen
:: KnownDomain dom
=> Clock dom
clockGen = tbClockGen (pure True)
-- | Clock generator to be used in the /testBench/ function.
--
-- To be used like:
--
-- @
-- clkSystem en = tbClockGen @System en
-- @
--
-- === __Example__
--
-- @
-- module Example where
--
-- import "Clash.Explicit.Prelude"
-- import "Clash.Explicit.Testbench"
--
-- -- Fast domain: twice as fast as \"Slow\"
-- 'Clash.Explicit.Prelude.createDomain' 'Clash.Explicit.Prelude.vSystem'{vName=\"Fast\", vPeriod=10}
--
-- -- Slow domain: twice as slow as \"Fast\"
-- 'Clash.Explicit.Prelude.createDomain' 'Clash.Explicit.Prelude.vSystem'{vName=\"Slow\", vPeriod=20}
--
-- topEntity
-- :: 'Clock' \"Fast\"
-- -> 'Reset' \"Fast\"
-- -> 'Enable' \"Fast\"
-- -> 'Clock' \"Slow\"