Îõ³h&Ü‚ƒñ      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ € � ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ � Ž � � ‘’“” • – — ˜ ™ š › œ � žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ ÿ € � ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ � Ž � � ‘ ’ !“ !” !• !– !— !˜ !™ !š !› !œ !� !ž !Ÿ !  !¡ !¢ !£ !¤ !¥ !¦ !§ "¨ #© #ª $« $¬ $­ $® $¯ $° $± $² $³ $´ $µ $¶ $· $¸ $¹ $º $» $¼ $½ $¾ $¿ $À $Á $ $à $Ä $Å $Æ $Ç $È $É $Ê $Ë $Ì $Í $Î $Ï $Ð $Ñ $Ò $Ó $Ô $Õ $Ö $× $Ø $Ù $Ú $Û $Ü $Ý $Þ $ß $à $á $â $ã $ä $å $æ $ç $è $é $ê $ë $ì $í $î $ï $ð $ñ $ò $ó $ô $õ $ö $÷ $ø $ù $ú $û $ü $ý $þ $ÿ $€ $� $‚ $ƒ $„ $… $† $‡ $ˆ $‰ $Š $‹ $Œ $� $Ž $� $� $‘ $’ $“ $” $• $– $— $˜ $™ $š $› $œ $� $ž $Ÿ $  $¡ $¢ $£ $¤ $¥ $¦ $§ $¨ $© $ª $« $¬ $­ $® $¯ $° $± $² $³ $´ $µ $¶ $· $¸ $¹ $º $» $¼ $½ $¾ $¿ $À $Á $ $à $Ä $Å $Æ $Ç $È $É $Ê $Ë $Ì $Í $Î $Ï $Ð $Ñ $Ò $Ó $Ô $Õ $Ö $× $Ø $Ù $Ú $Û $Ü $Ý $Þ $ß $à $á $â $ã $ä $å $æ $ç $è $é $ê $ë $ì $í $î $ï $ð $ñ $ò $ó $ô $õ $ö $÷ $ø $ù $ú $û $ü $ý $þ $ÿ $€ $� $‚ $ƒ $„ $… $† $‡ $ˆ $‰ $Š $‹ $Œ $� $Ž $� $� $‘ $’ $“ $” $• $– $— $˜ $™ $š $› $œ $� $ž $Ÿ $  $¡ $¢ $£ $¤ $¥ $¦ $§ $¨ $© $ª $« $¬ $­ $® $¯ $° $± $² $³ $´ $µ $¶ $· $¸ $¹ $º $» $¼ $½ $¾ $¿ $À $Á $ $à $Ä $Å $Æ $Ç $È $É $Ê $Ë $Ì $Í $Î $Ï $Ð $Ñ $Ò $Ó $Ô $Õ $Ö $× $Ø $Ù $Ú $Û $Ü $Ý $Þ $ß $à $á $â $ã $ä $å $æ $ç $è $é $ê $ë $ì $í $î $ï $ð $ñ $ò $ó $ô $õ $ö $÷ $ø $ù $ú $û $ü $ý $þ $ÿ $€ $� $‚ $ƒ $„ $… $† $‡ $ˆ $‰ $Š $‹ $Œ $� $Ž $� $� $‘ $’ $“ $” $• $– $— $˜ $™ $š $› $œ $� $ž $Ÿ $  $¡ $¢ $£ $¤ $¥ $¦ $§ $¨ $© $ª $« $¬ $­ $® $¯ $° $± $² $³ $´ $µ $¶ $· $¸ $¹ $º $» $¼ $½ $¾ $¿ $À $Á $ $à $Ä $Å $Æ $Ç $È $É $Ê $Ë $Ì $Í $Î $Ï $Ð $Ñ $Ò $Ó $Ô $Õ $Ö $× $Ø $Ù $Ú $Û $Ü $Ý $Þ $ß $à $á $â $ã $ä $å $æ $ç $è $é $ê $ë $ì $í $î $ï $ð $ñ $ò $ó $ô $õ $ö $÷ $ø $ù $ú $û $ü $ý $þ $ÿ $€ $� $‚ $ƒ $„ $… $† $‡ $ˆ $‰ $Š $‹ $Œ $� $Ž $� $� $‘ $’ $“ $” $• $– $— $˜ $™ $š $› $œ $� $ž $Ÿ $  $¡ $¢ $£ $¤ $¥ $¦ $§ $¨ $© $ª $« $¬ $­ $® $¯ $° $± $² $³ $´ $µ $¶ $· $¸ $¹ $º $» $¼ $½ $¾ $¿ $À $Á $ $à $Ä $Å $Æ $Ç $È $É $Ê $Ë $Ì $Í $Î $Ï $Ð $Ñ $Ò $Ó $Ô $Õ $Ö $× $Ø $Ù $Ú $Û $Ü $Ý $Þ $ß $à $á $â $ã $ä $å $æ $ç $è $é $ê $ë $ì $í $î $ï $ð $ñ $ò $ó $ô $õ $ö $÷ $ø $ù $ú $û $ü $ý $þ $ÿ $€$�$‚$ƒ$„$…$†$‡$ˆ$‰$Š$‹$Œ$�$Ž$�$�$‘$’$“$”$•$–$—$˜$™$š$›$œ$�$ž$Ÿ$ $¡$¢$£$¤$¥$¦$§$¨$©$ª$«$¬$­$®$¯$°$±$²$³$´$µ$¶$·$¸$¹$º$»$¼$½$¾$¿$À$Á$Â$Ã$Ä$Å$Æ$Ç$È$É$Ê$Ë$Ì$Í$Î$Ï$Ð$Ñ$Ò$Ó$Ô$Õ$Ö$×$Ø$Ù$Ú$Û$Ü$Ý$Þ$ß$à$á$â$ã$ä$å$æ$ç$è$é$ê$ë$ì$í$î$ï$ð$ñ$ò$ó$ô$õ$ö$÷$ø$ù$ú$û$ü$ý$þ$ÿ$€$�$‚$ƒ$„$…$†$‡$ˆ$‰$Š$‹$Œ$�$Ž$�$�$‘$’$“$”$•$–$—$˜$™$š$›$œ$�$ž$Ÿ$ $¡$¢$£$¤$¥$¦$§$¨$©$ª$«$¬$­$®$¯$°$±$²$³$´$µ$¶$·$¸$¹$º$»$¼$½$¾$¿$À$Á$Â$Ã$Ä$Å$Æ$Ç$È$É$Ê$Ë$Ì$Í$Î$Ï$Ð$Ñ$Ò$Ó$Ô$Õ$Ö$×$Ø$Ù$Ú$Û$Ü$Ý$Þ$ß$à$á$â$ã$ä$å$æ$ç$è$é$ê$ë$ì$í$î$ï$ð$ñ$ò$ó$ô$õ$ö$÷$ø$ù$ú$û$ü$ý$þ$ÿ$€$�$‚$ƒ$„$…$†$‡$ˆ$‰$Š$‹$Œ$�$Ž$�$�$‘$’$“$”$•$–$—$˜$™$š$›$œ$�$ž$Ÿ$ $¡$¢$£$¤$¥$¦$§$¨$©$ª$«$¬$­$®$¯$°$±$²$³$´$µ$¶$·$¸$¹$º$»$¼$½$¾$¿$À$Á$Â$Ã$Ä$Å$Æ$Ç$È$É$Ê$Ë$Ì$Í$Î$Ï$Ð$Ñ$Ò$Ó$Ô$Õ$Ö$×$Ø$Ù$Ú$Û$Ü$Ý$Þ$ß$à$á$â$ã$ä$å$æ$ç$è$é$ê$ë$ì$í$î$ï$ð$ñ$ò$ó$ô$õ$ö$÷$ø$ù$ú$û$ü$ý$þ$ÿ$€$�$‚$ƒ$„$…$†$‡$ˆ$‰$Š$‹$Œ$�$Ž$�$�$‘$’$“$”$•$–$—$˜$™$š$›$œ$�$ž$Ÿ$ $¡$¢$£$¤$¥$¦$§$¨$©$ª$«%¬%­&®'¯'°'±'²'³'´'µ'¶'·'¸'¹'º'»'¼'½'¾'¿'À'Á'Â'Ã'Ä'Å'Æ'Ç'È'É'Ê'Ë'Ì'Í'Î'Ï'Ð'Ñ'Ò'Ó'Ô'Õ'Ö'×'Ø'Ù'Ú'Û'Ü'Ý'Þ'ß'à'á'â'ã'ä'å'æ'ç'è'é'ê'ë'ì'í'î'ï(ð(ñ(ò(ó(ô(õ(ö(÷(ø(ù(ú(û(ü(ý)þ)ÿ)€*�*‚*ƒ*„*…*†*‡+ˆ+‰+Š+‹+Œ+�+Ž+�+�+‘+’+“+”+•+–+—+˜,™-š-›-œ-�-ž-Ÿ- -¡-¢-£-¤-¥-¦-§-¨-©-ª-«-¬-­-®-¯-°-±-²-³-´-µ-¶-·-¸-¹-º-»-¼-½-¾-¿-À-Á-Â-Ã-Ä-Å-Æ-Ç-È-É-Ê-Ë-Ì-Í-Î-Ï-Ð-Ñ-Ò-Ó-Ô-Õ-Ö-×-Ø-Ù-Ú-Û-Ü-Ý-Þ-ß-à.á/â/ã/ä/å/æ/ç/è/é/ê/ë/ì/í/î/ï/ð/ñ/ò/ó/ô/õ/ö/÷/ø/ù/ú/û/ü/ý/þ/ÿ/€/�/‚/ƒ/„/…/†/‡/ˆ/‰/Š/‹/Œ/�/Ž/�/�/‘/’/“/”/•/–/—/˜/™/š/›/œ/�/ž/Ÿ/ /¡/¢/£/¤/¥/¦/§/¨/©0ª0«0¬0­0®0¯0°0±0²0³0´0µ0¶0·0¸0¹0º0»0¼0½0¾0¿0À0Á0Â0Ã0Ä0Å0Æ0Ç0È0É0Ê0Ë0Ì0Í0Î0Ï0Ð0Ñ0Ò0Ó0Ô0Õ0Ö0×0Ø0Ù0Ú0Û0Ü0Ý0Þ0ßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ 1¡1¢1£1¤1¥1¦1§1¨1©1ª1«1¬1­1®1¯1°1±1²1³1´1µ1¶2·2¸2¹3º3»3¼3½3¾4¿4À3Á3Â3Ã3Ä3Å3Æ4Ç3È3É3Ê5Ë5Ì5Í5Î5Ï5Ð5Ñ5Ò5Ó5Ô5Õ5Ö5×5Ø5Ù5Ú5Û6Ü6Ý6Þ6ß6à6á6â6ã6ä6å6æ6ç6è6é6ê6ë6ì6í6î6ï6ð6ñ6ò6ó6ô6õ6ö6÷6ø6ù6ú6û6ü6ý6þ6ÿ6€6�6‚6ƒ6„7…7†7‡7ˆ7‰7Š7‹7Œ7�7Ž7�7�7‘7’7“7”7•7–7—7˜7™7š7›7œ7�7ž7Ÿ7 7¡7¢7£7¤7¥7¦7§7¨7©7ª8«8¬8­8®8¯9°9±9²9³9´9µ9¶9·9¸9¹9º9»9¼9½9¾9¿:À:Á4Â:Ã:Ä:Å4Æ4Ç4È4É4Ê:Ë:Ì:Í:Î:Ï:Ð;Ñ;Ò;Ó;Ô;Õ;Ö;×;Ø;Ù;Ú;Û;Ü;Ý;Þ;ß;à;á;â;ã;ä;å;æ;ç;è;éêëìíîïðñòóôõö÷øùúûüý<þ<ÿ<€<�<‚=ƒ=„=…>†>‡>ˆ?‰?Š?‹?Œ@�@Ž@�@�A‘A’A“A”A•B–B—B˜C™CšC›CœC�CžCŸC C¡C¢C£C¤C¥C¦C§C¨C©CªC«C¬D­D®E¯E°E±E²E³E´EµE¶E·E¸E¹FºF»F¼F½F¾F¿FÀFÁFÂFÃFÄFÅFÆFÇFÈFÉFÊFËFÌFÍFÎFÏFÐFÑFÒFÓFÔFÕFÖF×FØFÙFÚFÛFÜFÝFÞFßFàFáFâFãFäFåFæFçGèGéGêGëHìHíHîHïHðHñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢I£I¤J¥J¦J§J¨J©JªK«K¬K­K®K¯L°L±L²L³L´LµL¶L·L¸L¹LºL»L¼L½L¾L¿LÀLÁLÂLÃLÄLÅLÆLÇLÈLÉLÊLËLÌLÍMÎMÏMÐMÑMÒNÓNÔNÕNÖN×OØOÙOÚOÛOÜPÝPÞQßQàQáQâRãRäRåRæRçSèSéSêSëSìSíSîSïSðSñSòSóSôSõSöS÷SøSùSúSûSüSýSþTÿT€U�U‚VƒV„V…V†V‡Vˆ‰Š‹Œ�Ž��‘’“”•–W—W˜W™WšW›WœX�XžXŸX X¡X¢X£X¤X¥X¦X§X¨X©XªX«X¬X­X®X¯X°X±Y²Y³Z´ZµZ¶Z·Z¸Z¹ZºZ»Z¼Z½Z¾Z¿ZÀZÁZÂZÃZÄZÅZÆZÇZÈZÉZÊZËZÌZÍZÎZÏZÐZÑZÒ[Ó[Ô[Õ[Ö[×[Ø\Ù\Ú\Û\Ü\Ý\Þ\ß\à\á\â\ã\ä\å\æ\ç\è\é\ê\ë\ì\í\î\ï\ð]ñ]ò]ó]ô]õ]ö]÷]ø]ù]ú]û]ü]ý]þ]ÿ]€]�]‚]ƒ]„]…]†]‡]ˆ]‰^Š^‹^Œ^�^Ž^�^�^‘^’^“^”^•^–^—^˜^™^š^›^œ^�^ž^Ÿ^ ^¡_¢_£_¤_¥_¦_§_¨_©_ª_«_¬_­_®_¯_°_±_²_³_´_µ_¶_·_¸`¹`º`»`¼`½`¾`¿`À`Á`Â`Ã`Ä`Å`Æ`Ç`È`É`Ê`Ë`Ì`Í`Î`Ï`ÐaÑaÒaÓaÔaÕaÖa×aØaÙaÚaÛaÜaÝaÞaßaàaáaâaãaäbåbæbçbèbéêëìíîcïcðcñcòcócôcõcöc÷cøcùcúcûcücýdþdÿd€d�d‚dƒd„d…d†d‡dˆd‰dŠd‹dŒd�dŽd�d�d‘d’d“d”d•d–d—d˜d™eše›eœe�ežeŸe e¡e¢e£e¤e¥e¦e§e¨e©eªe«e¬b­b®¯°±f²f³f´fµf¶f·f¸f¹fºf»f¼f½f¾f¿fÀfÁfÂfÃfÄfÅfÆfÇfÈfÉfÊfËfÌfÍfÎfÏfÐfÑfÒfÓfÔfÕfÖf×fØfÙfÚfÛfÜfÝfÞfßfàfáfâfãfäfåfæfçfèfégêgëgìgíhîhïiðiõ(C) 2018, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij None&/02356789;<ÇÉÐÑÔÖ×ÙâìMßÜ clash-preludeæAnnotation for constructors. Indicates how to match this constructor based off of the whole datatype.Þ clash-prelude7Annotation for custom bit representations of data typesUsing ANNÞ pragma's you can tell the Clash compiler to use a custom bit-representation for a data type. For example: 'data Color = R | G | B {-# ANN module (Þ $(ä5 [t|Color|]) 2 [ Ü% 'R 0b11 0b00 [] , Ü% 'G 0b11 0b01 [] , Ü* 'B 0b11 0b10 [] ]) #-} This specifies that R should be encoded as 0b00, G as 0b01, and B* as 0b10. The first binary value in every  ConstrReprô in this example is a mask, indicating which bits in the data type are relevant. In this case all of the bits are.Or if we want to annotate  Maybe Color: {-# ANN module ( Þ $(ä= [t|Maybe Color|]) 2 [ Ü, 'Nothing 0b11 0b11 [] , Ü3 'Just 0b00 0b00 [0b11] ] ) #-}  By default,  Maybe ColorÙ is a data type which consumes 3 bits. A single bit to indicate the constructor (either Just or Nothing.), and two bits to encode the first field of JustÁ. Notice that we saved a single bit by exploiting the fact that ColorŸ only uses three values (0, 1, 2), but takes two bits to encode it. We can therefore use the last - unused - value (3), to encode one of the constructors of Maybe0. We indicate which bits encode the underlying Color field of Just by passing [0b11]ú to ConstrRepr. This indicates that the first field is encoded in the first and second bit of the whole datatype (0b11).NB6: BitPack for a custom encoding can be derived using dj.à clash-preludeBitMask used to mask fieldsä clash-preludeLift values inside of ñ! to a Template Haskell expression ÜÝÞßàáâãä ÞßÜÝãâáàäË(C) 2018, Google Inc. 2022, LUMI GUIDE FIETSDETECTIE B.V.BSD2 (see the file LICENSE)-Christiaan Baaij None &/02356789:;<ÇÉÐÑÔÖ×ÙâìSÐï clash-prelude4Convenience type for index built by buildCustomReprsð clash-preludeInternal version of ConstrReprò clash-preludeQualified name of constructoró clash-prelude=Syntactical position in the custom representations definitionô clash-prelude$Mask needed to determine constructorõ clash-preludeValue after applying maskö clash-prelude!Indicates where fields are stored÷ clash-preludeInternal version of DataReprù clash-prelude"Simple representation of data typeú clash-preludeSize of data typeû clash-prelude Constructorsü clash-preludeÅSimple version of template haskell type. Used internally to match on.ý clash-preludeType applicationþ clash-preludeQualified name of typeÿ clash-prelude3Numeral literal (used in BitVector 10, for example)€ clash-prelude,Symbol literal (used in for example (Signal System Int))ƒ clash-prelude>Convert template haskell type to simple representation of type„ clash-prelude-Lookup data type representation based on name… clash-prelude/Lookup constructor representation based on name† clash-prelude"Unchecked version of getConstrRepr‡ clash-preludeNone&/02356789;<ÇÉÐÑÖ×ÙâìXÁ š clash-preludeœResult of various utilty functions. Indicates the origin of a certain bit: either a literal from the constructor (or an undefined bit), or from a literal.› clash-preludeLiteral (high, low, undefind)œ clash-prelude#Bits originate from a field. Field fieldnr from downto.ž clash-preludeHighŸ clash-preludeLow  clash-prelude Undefined¡ clash-preludeÉSame as bitOrigins, but each item in result list represents a single bit.¢ clash-preludeðGiven a type size and one of its constructor this function will yield a specification of which bits the whole type is made up of. I.e., a construction plan on how to make the whole data structure, given its individual constructor fields.£ clash-preludeÚDetermine consecutively set bits in word. Will produce ranges from high to low. Examples:‚bitRanges 0b10 == [(1,1)] bitRanges 0b101 == [(2,2),(0,0)] bitRanges 0b10011001111 == [(10,10),(7,6),(3,0)] š›œ�Ÿž ¡¢£¤ ¢¡£¤š›œ�Ÿž Ê(C) 2017-2019, Myrtle Software 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Safe&/02356789:;<ÇÉÐÑÖ×Ùàâìk_¨ clash-prelude>Warning that will be emitted on instantiating a guarded value.© clash-preludeêMarks value as non-synthesizable. This will trigger a warning if instantiated in a non-testbench context.ª clash-prelude1Always emit warning upon primitive instantiation.« clash-prelude Primitive guard to mark a value as either not translatable or as having a blackbox with an optional extra warning. Helps Clash generate better error messages. For use, see ¶, ·, ¸ and ¹.¬ clash-prelude‚Marks value as not translatable. Clash will error if it finds a blackbox definition for it, or when it is forced to translate it.­ clash-preludeÔMarks a value as having a blackbox. Clash will error if it hasn't found a blackbox.® clash-preludeThe ®ë constructor instructs the clash compiler to look for primitive HDL templates in the indicated directory. °‹ is equivalent but provides the HDL template inline. They are intended for the distribution of new packages with primitive HDL templates. Example of ®¥You have some existing IP written in one of HDLs supported by Clash, and you want to distribute some bindings so that the IP can be easily instantiated from Clash.!You create a package which has a myfancyip.cabal file with the following stanza: >data-files: path/to/MyFancyIP.primitives cpp-options: -DCABAL and a  MyFancyIP.hs5 module with the simulation definition and primitive. êmodule MyFancyIP where import Clash.Prelude myFancyIP :: ... myFancyIP = ... {-# NOINLINE myFancyIP #-} The NOINLINE? pragma is needed so that GHC will never inline the definition..Now you need to add the following imports and ANN pragma: �#ifdef CABAL import Clash.Annotations.Primitive import System.FilePath import qualified Paths_myfancyip import System.IO.Unsafe {-# ANN module (Primitive [VHDL] (unsafePerformIO Paths_myfancyip.getDataDir "path" "to")) #-} #endif Add more files to the  data-files stanza in your .cabal files and more ANNÄ pragma's if you want to add more primitive templates for other HDLs Example of ±ÏThe following example shows off an inline HDL primitive template. It uses the  6https://hackage.haskell.org/package/string-interpolatestring-interpolate& package for nicer multiline strings. Þ{-# LANGUAGE QuasiQuotes #-} module InlinePrimitive where import Clash.Annotations.Primitive import Clash.Prelude import Data.String.Interpolate (__i) {-# ANN example (InlineYamlPrimitive [VHDL] [__i| BlackBox: kind: Declaration name: InlinePrimitive.example template: |- -- begin InlinePrimitive example: ~GENSYM[example][0] : block ~RESULT <= 1 + ~ARG[0]; end block; -- end InlinePrimitive example |]) #-} {-# NOINLINE example #-} example :: Signal System (BitVector 2) -> Signal System (BitVector 2) example = fmap succ ¯ clash-prelude'Description of a primitive for a given ²s in a file at g° clash-prelude'Description of a primitive for a given ²s as an inline JSON R± clash-prelude'Description of a primitive for a given ²s as an inline YAML R² clash-preludeA compilation target HDL.¶ clash-prelude¬Marks value as not translatable. Clash will error if it finds a blackbox definition for it, or when it is forced to translate it. You can annotate a variable or function f like: {-# ANN f dontTranslate #-} · clash-preludeýMarks a value as having a blackbox. Clash will error if it hasn't found a blackbox. You can annotate a variable or function f like: {-# ANN f hasBlackBox #-} ¸ clash-prelude”Marks value as non-synthesizable. This will trigger a warning if instantiated in a non-testbench context. You can annotate a variable or function f like: >{-# ANN f (warnNonSynthesizable "Tread carefully, user!") #-} Implies ·.¹ clash-preludeÛAlways emit warning upon primitive instantiation. You can annotate a variable or function f like: 4{-# ANN f (warnAlways "Tread carefully, user!") #-} Implies ·.º clash-preludeÜExtract primitive definition from a PrimitiveGuard. Will yield Nothing for guards of value ¬.» clash-preludeàExtract primitive warnings from a PrimitiveGuard. Will yield an empty list for guards of value ¬.¨©ª«¬­®¯±°²³´µ¶·¸¹º»¶·¸¹®¯±°²³´µ«¬­¨©ªº»kÐ(C) 2019 , Myrtle Software Ltd, 2023 , QBayLogic B.V.,BSD2 (see the file LICENSE)%QBayLogic B.V.  Safe-Inferred&/02356789;<ÇÉÐÑÖ×Ùâìm%ò clash-prelude6Whether clash-prelude was compiled with -fsuper-strictó clash-prelude:Whether clash-prelude was compiled with -fstrict-mapSignalôõòó Safe-Inferred&/02356789;<ÇÉÐÑÖ×Ùâìmv ßàáâãäåæçèé ßàáâãäåæçèé(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij None&./02356789;<ÇÉÐÑÖ×ÙâìnÐë clash-preludeÂCombine multiple lines with line break. Type-level version of the unlines function but for ErrorMessage. êëìíîëíìêîê4ì4í5 #(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij Safe&/02356789;<ÁÂÇÉÐÑÖ×ÙâìwVï clash-prelude+Ì operators in which overflow and underflow behavior can be specified using õ.ð clash-prelude:Addition with parameterizable over- and underflow behaviorñ clash-prelude=Subtraction with parameterizable over- and underflow behaviorò clash-preludeÀMultiplication with parameterizable over- and underflow behavioró clash-prelude;Get successor of (or in other words, add 1 to) given numberô clash-preludeÄGet predecessor of (or in other words, subtract 1 from) given numberõ clash-preludeÆDetermine how overflow and underflow are handled by the functions in ïö clash-prelude%Wrap around on overflow and underflow÷ clash-preludeBecome T on overflow, and U on underflowø clash-preludeBecome 0 on overflow and underflowù clash-preludeBecome T on overflow, and (U + 1() on underflow for signed numbers, and U for unsigned numbers.ú clash-prelude.Become an XException on overflow and underflowû clash-preludeÉAdding, subtracting, and multiplying values of two different (sub-)types.ü clash-prelude1Type of the result of the addition or subtractioný clash-prelude(Type of the result of the multiplicationþ clash-preludeøAdd values of different (sub-)types, return a value of a (sub-)type that is potentially different from either argument.ÿ clash-preludeýSubtract values of different (sub-)types, return a value of a (sub-)type that is potentially different from either argument.€ clash-preludeýMultiply values of different (sub-)types, return a value of a (sub-)type that is potentially different from either argument.� clash-preludeAddition that clips to T on overflow, and U on underflow‚ clash-preludeSubtraction that clips to T on overflow, and U on underflowƒ clash-preludeMultiplication that clips to T on overflow, and U on underflowïóðñòôõ÷úöøùûüý€þÿ�‚ƒûüý€þÿõ÷úöøùïóðñòô�‚ƒ Ô(C) 2013-2016, University of Twente 2020, Myrtle Software LtdBSD2 (see the file LICENSE)%QBayLogic B.V. Safe&/02356789;<ÇÉÐÑÖ×Ùâì½ ˆ clash-prelude>Coerce a value to be represented by a different number of bits‰ clash-prelude"A sign-preserving resize operation­For signed datatypes: Increasing the size of the number replicates the sign bit to the left. Truncating a number to length L keeps the sign bit and the rightmost L-1 bits.¼For unsigned datatypes: Increasing the size of the number extends with zeros to the left. Truncating a number of length N to a length L just removes the left (most significant) N-L bits.Š clash-prelude Perform a ‹ for unsigned datatypes, and Œ for a signed datatypes‹ clash-prelude'Add extra zero bits in front of the MSBŒ clash-prelude'Add extra sign bits in front of the MSB� clash-preludeRemove bits from the MSBŽ clash-preludeLike , but errors if a is out of bounds for b. Useful when you "know" aÊ can't be out of bounds, but would like to have your assumptions checked.NBÙ: Check only affects simulation. I.e., no checks will be inserted into the generated HDLNB: 5 is not well suited for Clash as it will go through @3 which is arbitrarily bounded in HDL. Instead use lm and the ˆ class.� clash-preludeLike ‰, but errors if f a is out of bounds for f b. Useful when you "know" f aÊ can't be out of bounds, but would like to have your assumptions checked.NBÙ: Check only affects simulation. I.e., no checks will be inserted into the generated HDL� clash-preludeLike �, but errors if  f (a + b) is out of bounds for f a. Useful when you "know"  f (a + b)Ê can't be out of bounds, but would like to have your assumptions checked.NBÙ: Check only affects simulation. I.e., no checks will be inserted into the generated HDL ˆ‰Š‹�ŒŽ�� ˆ‰Š‹�Œ�Ž�Â(C) 2019, QBayLogic B.V. (C) 2021, QBayLogic B.V.BSD2 (see the file LICENSE)$QBayLogic B.V Safe&/02356789;<ÇÉÐÑÖ×Ùâ쀤Ø#UT$³´²± %S&�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��’‘'ª «(¤¥¦§¨©)*Ò+ÇÈÊÉ,רÙÚÛÖ-~./“”•–—˜™š›œ�ž Ÿ0¬­®°¯1ºV»23Ó"! 4sqrut5Z[W\89;IL<=>?@AJKBQOPCDEFMNRXY]^_`abcdefghijklmnopvwxyz{|}€¡¢£µ¶·¸¹¼½¾¿ÀÁÂÃÄÅÆËÌÍÎÏÐÑÔÕ‘’“Ø#UT$³´²± %S&�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��’‘'ª «(¤¥¦§¨©)*Ò+ÇÈÊÉ,רÙÚÛÖ-~./“”•–—˜™š›œ�ž Ÿ0¬­®°¯1ºV»23Ó"! 4sqrut5Z[W\89;IL<=>?@AJKBQOPCDEFMNRXY]^_`abcdefghijklmnopvwxyz{|}€¡¢£µ¶·¸¹¼½¾¿ÀÁÂÃÄÅÆËÌÍÎÏÐÑÔÕ‘’“‘3’2 (C) 2018 , QBayLogic B.V.BSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&-/02356789;<ÁÂÄÇÉÐÑÔÖ×Ùâ쉌” clash-preludeA value reflected to, or hiding at, the  Constraint levele.g. a function: 1f :: Hidden "foo" Int => Bool -> Int f = ... has a normal argument of type Bool, and a hidden argument called "foo" of type Int. In order to apply the Int argument we have to use the • function, so that the hidden+ argument becomes a normal argument again.Original implementation” used to be implemented by: :class Hidden (x :: Symbol) a | x -> a where hidden :: a which is equivalent to IP, except that IPè has magic inference rules bestowed by GHC so that there's never any ambiguity. We need these magic inference rules so we don't end up in type inference absurdity where asking for the type of an type-annotated value results in a no-instance-in-scope error.• clash-prelude Expose a ”2 argument so that it can be applied normally, e.g. Îf :: Hidden "foo" Int => Bool -> Int f = ... g :: Int -> Bool -> Int g = • @"foo" f – clash-preludeUsing -XOverloadedLabels and -XRebindableSyntax , we can turn any value into a hidden argument using the #foo notation, e.g.: ×f :: Int -> Bool -> Int f = ... g :: Hidden "foo" Bool => Int -> Int g i = f i #foo • clash-preludeFunction with a ” argument clash-preludeFunction with the ” argument exposed”•–”•– 5(C) 2017, Myrtle Software Ltd, QBayLogic, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij Safe&./02356789;<ÇÉÐÑÖ×Ùâ슆— clash-preludeAnnotate a type with a name—— Ï(C) 2013-2016, University of Twente 2022 , QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Safe-Inferred&'(/02356789;<ÇÉÐÑÖ×ÙâìŒo˜ clash-prelude(Singleton value for a type-level string sš clash-prelude"Create a singleton symbol literal ˜ s from a proxy for s› clash-preludeReify the type-level ö s to it's term-level R representation.˜™š›˜™š›"(C) 2019-2023, Myrtle Software LtdBSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<ÇÉÐÑÖ×ÙâìŸØ ž clash-prelude�A container for data you only want to have around during simulation and is ignored during synthesis. Useful for carrying around things such as:A map of simulation/vcd traces Co-simulation state or meta-dataetc.  clash-prelude2Prefix instance and register names with the given ö¡ clash-prelude2Suffix instance and register names with the given ö¢ clash-prelude2Suffix instance and register names with the given ÷£ clash-prelude2Suffix instance and register names with the given ö), but add it in front of other suffixes.When you write %suffixName @"A" (suffixName @"B" f)) +you get register and instance names inside f with the suffix: "_B_A";However, if you want them in the other order you can write: &suffixNameP @"A" (suffixName @"B" f)) so that names inside f will have the suffix "_A_B"¤ clash-prelude2Suffix instance and register names with the given ÷), but add it in front of other suffixes.When you write &suffixNameNat @1 (suffixName @"B" f)) +you get register and instance names inside f with the suffix: "_B_1";However, if you want them in the other order you can write: 'suffixNameNatP @1 (suffixName @"B" f)) so that names inside f will have the suffix "_1_B"¥ clash-prelude-Name the instance or register with the given öÍ, instead of using an auto-generated name. Pre- and suffixes annotated with   and ¡; will be added to both instances and registers named with ¥1 and instances and registers that are auto-named.¦ clash-prelude'Name a given term, such as one of type n, using the given ˜Û. Results in a declaration with the name used as the identifier in the generated HDL code.Example usage: &nameHint (SSymbol @"identifier") term NBó: The given name should be considered a hint as it may be expanded, e.g. if it collides with existing identifiers.§ clash-preludeÒForce deduplication, i.e. share a function or operator between multiple branches.By default Clash converts $case x of A -> 3 * y B -> x * x to �let f_arg0 = case x of {A -> 3; _ -> x} f_arg1 = case x of {A -> y; _ -> x} f_out = f_arg0 * f_arg1 in case x of A -> f_out B -> f_out However, it won't do this for: $case x of A -> 3 + y B -> x + x ¾Because according to the internal heuristics the multiplexer introduced for the deduplication are more expensive than the addition. This might not be the case for your particular platform.5In these cases you can force Clash to deduplicate by: case x of A -> § (3 + y) B -> § (x + x) ¨ clash-preludeDo not deduplicate, i.e. keepî, an applied function inside a case-alternative; do not try to share the function between multiple branches.By default Clash converts /case x of A -> f 3 y B -> f x x C -> h x to ¬let f_arg0 = case x of {A -> 3; _ -> x} f_arg1 = case x of {A -> y; _ -> x} f_out = f f_arg0 f_arg1 in case x of A -> f_out B -> f_out C -> h x Æi.e. it deduplicates functions (and operators such as multiplication) between case-alternatives to save on area. This comes at the cost of multiplexing the arguments for the deduplicated function.ÃThere are two reasons you would want to stop Clash from doing this: „The deduplicated function is in the critical path, and the addition of the multiplexers further increased the propagation delay.€Clash's heuristics were off, and the addition of the multiplexers actually made the final circuit larger instead of smaller.9In these cases you want to tell Clash not to deduplicate: case x of A -> ¨ f 3 y B -> f x x C -> h x Where the application of f in the AÅ-alternative is now explicitly not deduplicated, and given that the f< in the B-alternative is the only remaining application of f5 in the case-expression it is also not deduplicated.Note that if the C(-alternative also had an application of f, then the applications of f in the B- and Cæ-alternatives would have been deduplicated; i.e. the final circuit would have had two application of f.© clash-preludeL* in Haskell/Clash simulation. Replaced by I when generating HDL.ª clash-preludeSame as ÕÅ but will make HDL generation fail if included in the final circuit.7This is useful for the error case of static assertions.¡Note that the error message needs to be a literal, and during HDL generation the error message does not include a stack trace, so it had better be descriptive.¦ clash-preludeA hint for a name žŸ ¡¢£¤¥¦§¨©ª  ¡£¢¤¥¦§¨©žŸª(C) 2019, Andrew LelechenkoMIT%QBayLogic B.V. None&/02356789;<ÇÉÐÑÖ×Ùâì¢K¹ clash-preludemodular subtractionº clash-preludemodular addition» clash-preludemodular multiplication¼ clash-preludeÔmodular multiplication for powers of 2, takes a mask instead of a wrap-around point½ clash-preludemodular negations¾ clash-preludeÈGiven a size in bits, return a function that complements the bits in a ø up to that size.¿ clash-prelude&Keep all the bits up to a certain size ¹º»¼½¾¿ÀÁ ¹º»¼½¾¿ÀÁ‰(C) 2016, University of Twente, 2017, QBayLogic, Google Inc. 2017-2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy!&'(/02356789;<>?ÀÁÂÇÉÐÑÖ×Ùâçì§ùÕ clash-preludeÔA class of functors that can be fully evaluated, according to semantics of NFDataX.Ö clash-preludeÖö should reduce its argument to normal form (that is, fully evaluate all sub-components), given an argument to reduce a arguments, and then return ().See Ì for the generic deriving.Þ clash-preludeÔHidden internal type-class. Adds a generic implementation for the "NFData" part of Èè clash-prelude3An exception representing an "uninitialized" value.ê clash-preludeLike ¸$, but values that normally throw an è are converted to  undefined-, instead of error'ing out with an exception.î clash-preludeUse when you want to create a É instance where: There is no 6 instance for your data typeThe 6• derived ShowX method would traverse into the (hidden) implementation details of your data type, and you just want to show the entire value as  undefined.Can be used like: çdata T = ... instance Show T where ... instance ShowX T where showsPrecX = showsPrecXWith showsPrecÑÒÓÔÕÖרÙÛÚÜÝÞßàáâãäåæçèéêëìíîèéêîíåæçÑÒÓÔרÞßÝÜàáâãäÙÛÚÕÖëìo Safe-Inferred&/02356789;<ÇÉÐÑÖ×Ùâì©Dù clash-prelude)Compatibility helper to create TySynInstDú clash-prelude8Compatibility helper to create (total) tuple expressionsùúû(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij  Safe-Inferred&/02356789;<ÇÉÐÑÖ×Ùâìª÷˜ clash-prelude Creates an instance of the form:/instance (ShowX a0, ShowX a1) => ShowX (a0, a1)With n number of variables.™ clash-prelude Trustworthy#&'(/02356789;<>?ÀÁÂÇÉÐÑÖ×ÙâçìÒ¢È clash-prelude)Class that houses functions dealing with  undefined values in Clash. See Î and Ì.É clash-prelude Like the 1* class, but values that normally throw an è are converted to  undefined-, instead of error'ing out with an exception..show (errorX "undefined" :: Integer, 4 :: Int)"(*** Exception: X: undefinedCallStack (from HasCallStack):.../showX (errorX "undefined" :: Integer, 4 :: Int)"(undefined,4)"Can be derived using pq: —{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} import Clash.Prelude import GHC.Generics data T = MkTA Int | MkTB Bool deriving (Show,Generic,ShowX)Ê clash-preludeLike Õ, but throwing an è instead of an üThe É% methods print these error-values as  undefined.; instead of error'ing out with an exception.Ë clash-preludeÉCreate a value where at the very least the spine is defined. For example:/spined = ensureSpine (errorX "?" :: (Int, Int))case spined of (_, _) -> 'a''a'5fmap (const 'b') (ensureSpine undefined :: Vec 3 Int)'b' :> 'b' :> 'b' :> Nil7fmap (const 'c') (ensureSpine undefined :: RTree 2 Int)<<'c','c'>,<'c','c'>>For users familiar with r): this is the generalized version of it.Ì clash-prelude&Evaluate a value to NF. As opposed to ýs þ, it does not bubble up ès.Í clash-prelude¯Determines whether any of parts of a given construct contain undefined parts. Note that a negative answer does not mean its bit representation is fully defined. For example:m = Nothing :: Maybe BoolhasUndefined mFalsepack m0b0.hasUndefined (pack m)TrueÎ clash-prelude.Create a value where all the elements have an Ê, but the spine is defined.Ï clash-preludeLike »$, but values that normally throw an è are converted to  undefined-, instead of error'ing out with an exception.Ð clash-prelude$Evaluate a value to WHNF, returning M msg if is a è. ÀisX 42 = Right 42 isX (XException msg) = Left msg isX (3, XException msg) = Right (3, XException msg) isX (3, _|_) = Right (3, _|_) isX _|_ = _|_› clash-preludeLike V$, but values that normally throw an è are converted to  undefined-, instead of error'ing out with an exception.œ clash-preludeLike º$, but values that normally throw an è are converted to  undefined-, instead of error'ing out with an exception.� clash-preludeEither   or ¨É depending on the value of the cabal flag '-fsuper-strict'. If enabled, � will be ¨ , otherwise  . Flag defaults to false and thus  .ž clash-preludeConvert è to ü+This is useful when tracking the source of è that gets eaten up by st inside of your circuit; since st translates è into undefined bits.1So for example if you have some large function f: !f a b = ... pack a ... pack b ...)Where it is basically an error if either a or b ever throws an è2, and so you want that to be reported the moment a or bÄ is used, instead of it being thrown when evaluating the result of f , then do: Ý{-# LANGUAGE ViewPatterns #-} f (xToErrorCtx "a is X" -> a) (xToErrorCtx "b is X" -> b) = ...ÔWhere we pass an extra string, for context, to know which argument evaluated to an è8. We can also use BangPatterns to report the potential è being thrown by a or b even earlier, i.e. when f is applied: í{-# LANGUAGE ViewPatterns, BangPatterns #-} f (xToErrorCtx "a is X" -> !a) (xToErrorCtx "b is X" -> !b) = ...NBÅ: Fully synthesizable, so doesn't have to be removed before synthesisExample:set -XViewPatterns -XDataKindsimport Clash.Sized.BitVectorimport GHC.Stack:{.let h, h' :: Bit -> BitVector 8 -> BitVector 8Ú h (xToErrorCtx "a is X" -> a) (xToErrorCtx "b is X" -> b) = slice d7 d0 (pack a ++# b)' h' a b = slice d7 d0 (pack a ++# b):}h' (errorX "QQ") 3 0b0000_0011h (errorX "QQ") 3*** Exception: a is XX: QQCallStack (from HasCallStack): errorX, called at ...Ÿ clash-preludeConvert è to ü+This is useful when tracking the source of è that gets eaten up by st inside of your circuit; since st translates è into undefined bits.1So for example if you have some large function f: !f a b = ... pack a ... pack b ...)Where it is basically an error if either a or b ever throws an è2, and so you want that to be reported the moment a or bÄ is used, instead of it being thrown when evaluating the result of f , then do: Å{-# LANGUAGE ViewPatterns #-} f (xToError -> a) (xToError -> b) = ...Unlike žÅ, where we have an extra String argument to distinguish one call to Ÿ to the other, Ÿ will use the puÀ mechanism to aid the user in distinguishing different call to Ÿ8. We can also use BangPatterns to report the potential è being thrown by a or b even earlier, i.e. when f is applied: Õ{-# LANGUAGE ViewPatterns, BangPatterns #-} f (xToError -> !a) (xToError -> !b) = ...NBÅ: Fully synthesizable, so doesn't have to be removed before synthesisExample:set -XViewPatterns -XDataKindsimport Clash.Sized.BitVectorimport GHC.Stack:{Älet f, g, h, h' :: HasCallStack => Bit -> BitVector 8 -> BitVector 8 f = g g = h h (xToError -> a) (xToError -> b) = slice d7 d0 (pack a ++# b)' h' a b = slice d7 d0 (pack a ++# b):}h' (errorX "QQ") 3 0b0000_0011f (errorX "QQ") 3 -*** Exception: CallStack (from HasCallStack): xToError, called at ... h, called at ... g, called at ... f, called at ...X: QQCallStack (from HasCallStack): errorX, called at ...  clash-preludeLike , however, whereas  will always do: seq _|_ b = _|_  will do: 9seqX (XException msg) b = b seqX _|_ b = _|_¡ clash-preludeLike  Ü, but will also catch ErrorCall exceptions which are thrown. This should be used with care. äseqErrorX (ErrorCall msg) b = b seqErrorX (XException msg) b = b seqErrorX _|_ b = _|_¢ clash-preludeLike  ÿ in simulation, but will force its first argument to be rendered in HDL. This is useful for components that need to be rendered in hardware, but otherwise have no meaning in simulation. An example of such a component would be an ILA: a component monitoring an internal signal of a design. The output of such a component (typically a unit) can be passed as the first argument to ¢0 to ensure the ILA ends up in the generated HDL.NB: The result of ¢Œ must (indirectly) be used at the very top of a design. If it's not, Clash will remove it like it does for any other unused circuit parts.NBÉ: Make sure the blackbox for the component with zero-width results uses vw£ clash-prelude"Fully evaluate a value, returning J if it throws è. Note that non-è errors take precedence over è ones. •maybeHasX 42 = Just 42 maybeHasX (XException msg) = Nothing maybeHasX (3, XException msg) = Nothing maybeHasX (XException msg, _|_) = _|_ maybeHasX (_|_, XException msg) = _|_ maybeHasX (3, _|_) = _|_ maybeHasX _|_ = _|_¤ clash-prelude$Evaluate a value to WHNF, returning J if it throws è. ÕmaybeIsX 42 = Just 42 maybeIsX (XException msg) = Nothing maybeIsX (3, XException msg) = Just (3, XException msg) maybeIsX (3, _|_) = Just (3, _|_) maybeIsX _|_ = _|_¥ clash-prelude"Fully evaluate a value, returning M msg if it throws èÆ. If you want to determine if a value contains undefined parts, use Í instead. õhasX 42 = Right 42 hasX (XException msg) = Left msg hasX (3, XException msg) = Left msg hasX (XException msg, _|_) = _|_ hasX (_|_, XException msg) = _|_ hasX (3, _|_) = _|_ hasX _|_ = _|_&If a data structure contains multiple èÅs, the "first" message is picked according to the implementation of Ì.¦ clash-preludeLike $, but values that normally throw an è are converted to  undefined,, instead of error'ing out with an exception§ clash-prelude a variant of ¨& that is useful in some circumstances: forceX x = x `deepseqX` x¨ clash-prelude¨×: fully evaluates the first argument, before returning the second. Does not propagate ès.© clash-preludeReduce to weak head normal formEquivalent to \x ->   x ().Useful for defining xy# for types for which NF=WHNF holds.ú clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples� is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version.… clash-preludeCall to Ê with default string† clash-preludeSame as z{Ñ, but returns a bottom/undefined value that other Clash constructs are aware of.‡ clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples� is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version.ÈÌÎÍËÉÏ›œÊÐèéêî�žŸ ¡¢£¤¥¦§¨©…†èéÊÐ¥¤£†…žŸÉÏ›œê¦î ¡§¨©�¢ÈÌÎÍË�0 0¡0¢0¨0(C) 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Safe-Inferred&/02356789;<ÇÉÐÑÖ×ÙàâèìÛ ’ clash-prelude+Structure helping programmers to deal with èç values. For safety reasons it can't be constructed directly, but should be constructed using either ! or •<. After construction, it can be deconstructed using either ” or “.“ clash-preludeUpon construction, a evaluated to a non-bottom WHNF” clash-preludeUpon construction, a evaluated to è• clash-prelude Construct a ’ value. If a evaluates to è, this function will return ”. Otherwise, it will return “.– clash-prelude Construct a ’ value. If ¥ evaluates to M, this function will return ”. Otherwise, it will return “.— clash-prelude Deconstruct ’ into an a - the opposite of •Ã. Be careful when using this function, because it might return an è if the argument was ”.˜ clash-prelude%Map functions over both constructors.™ clash-prelude Implements ÿ accounting for Xƒ@Xƒ@ƒ@1ƒ@ƒ@0ƒ@ƒ@Xƒ@ƒ@Xƒ@ƒ@Xƒ@ƒ@0ƒ@ƒ@1ƒ@ƒ@Xƒ@ƒ@1ƒ@ƒ@0ƒ@ƒ@0ƒ@ƒ@0ƒ@ƒ@0ƒ@ƒ@0ƒ@š clash-prelude Implements € accounting for Xƒ@Xƒ@ƒ@1ƒ@ƒ@0ƒ@ƒ@Xƒ@ƒ@Xƒ@ƒ@1ƒ@ƒ@Xƒ@ƒ@1ƒ@ƒ@1ƒ@ƒ@1ƒ@ƒ@1ƒ@ƒ@0ƒ@ƒ@Xƒ@ƒ@1ƒ@ƒ@0ƒ@› clash-prelude Note that   and �Ç are X-strict in their arguments. That is, if any of their inputs are ”, their outputs will be too.œ clash-prelude Note that 7 is X-strict in its argument. That is, if its input is ”, its output will be too. ’”“•–—˜™š ’”“”“•–—™š˜™3š2�(C) 2013-2016, University of Twente, 2016 , Myrtle Software Ltd 2022 , QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&'(/02356789;<ÇÉÐÑÔÖ×Ùâìñ„.ž clash-preludeBase-2 encoded natural numberNB-: The LSB is the left/outer-most constructor:NB: Not synthesizableB0 (B1 (B1 BT))b6 ConstructorsStarting/Terminating element: BT :: ž 0 Append a zero (0): B0 :: ž n -> ž (2 |} n) Append a one (1): B1 :: ž n -> ž ((2 |} n) |~ 1) ¢ clash-prelude"Ordering relation between two Nats¥ clash-prelude,Unary representation of a type-level naturalNB: Not synthesizable¨ clash-prelude0Singleton value for a type-level natural number nClash.Promoted.Nat.Literals contains a list of predefined ¨ literalsClash.Promoted.Nat.TH7 has functions to easily create large ranges of new ¨ literalsª clash-prelude Create an ¨ n from a proxy for n« clash-prelude+Supply a function with a singleton natural n according to the context¬ clash-preludeSame as ­ and ‚2, but doesn't take term arguments. Example usage:natToInteger @55­ clash-preludeReify the type-level ÷ n to it's term-level @ representation.® clash-preludeSame as ¯ and |2, but doesn't take term arguments. Example usage:natToNatural @55¯ clash-preludeReify the type-level ÷ n to it's term-level ø.° clash-preludeSame as ±1, but doesn't take term arguments. Example usage:natToNum @5 @Int5± clash-preludeReify the type-level ÷ n to it's term-level +ber.² clash-prelude>Convert a singleton natural number to its unary representationNB: Not synthesizable³ clash-preludeÆConvert a unary-encoded natural number to its singleton representationNB: Not synthesizable´ clash-prelude%Add two unary-encoded natural numbersNB: Not synthesizableµ clash-prelude*Multiply two unary-encoded natural numbersNB: Not synthesizable¶ clash-prelude*Power of two unary-encoded natural numbersNB: Not synthesizable· clash-prelude-Predecessor of a unary-encoded natural numberNB: Not synthesizable¸ clash-prelude*Subtract two unary-encoded natural numbersNB: Not synthesizable¹ clash-prelude)Predecessor of a singleton natural numberº clash-prelude'Successor of a singleton natural number» clash-prelude!Add two singleton natural numbers¼ clash-prelude&Subtract two singleton natural numbers½ clash-prelude&Multiply two singleton natural numbers¾ clash-prelude&Power of two singleton natural numbers¿ clash-prelude)Division of two singleton natural numbersÀ clash-prelude'Modulo of two singleton natural numbersà clash-prelude*Floor of the logarithm of a natural numberÄ clash-prelude,Ceiling of the logarithm of a natural numberÅ clash-prelude+Exact integer logarithm of a natural numberNB5: Only works when the argument is a power of the baseÆ clash-prelude*Power of two of a singleton natural numberÇ clash-prelude*Get an ordering relation between two SNatsÈ clash-prelude1Show a base-2 encoded natural as a binary literalNB(: The LSB is shown as the right-most bitd789d789 toBNat d789b789showBNat (toBNat d789)"0b1100010101"0b1100010101 :: Integer789É clash-prelude?Convert a singleton natural number to its base-2 representationNB: Not synthesizableÊ clash-preludeÇConvert a base-2 encoded natural number to its singleton representationNB: Not synthesizableË clash-prelude&Add two base-2 encoded natural numbersNB: Not synthesizableÌ clash-prelude+Multiply two base-2 encoded natural numbersNB: Not synthesizableÍ clash-prelude+Power of two base-2 encoded natural numbersNB: Not synthesizableÎ clash-prelude,Successor of a base-2 encoded natural numberNB: Not synthesizableÏ clash-prelude.Predecessor of a base-2 encoded natural numberNB: Not synthesizableÐ clash-prelude+Divide a base-2 encoded natural number by 2NB: Not synthesizableÑ clash-prelude:Subtract 1 and divide a base-2 encoded natural number by 2NB: Not synthesizableÒ clash-prelude/Get the log2 of a base-2 encoded natural numberNB: Not synthesizableÓ clash-preludeÂStrip non-contributing zero's from a base-2 encoded natural numberB1 (B0 (B0 (B0 BT)))b1showBNat (B1 (B0 (B0 (B0 BT))))"0b0001",showBNat (stripZeros (B1 (B0 (B0 (B0 BT)))))"0b1"!stripZeros (B1 (B0 (B0 (B0 BT))))b1NB: Not synthesizableÔ clash-prelude/Change a function that has an argument with an  (n ~ (k + m))8 constraint to a function with an argument that has an (k <= n) constraint.Examples Example 1 =f :: Index (n+1) -> Index (n + 1) -> Bool g :: forall n. (1 |€* n) => Index n -> Index n -> Bool g a b = Ô @1 @n (f a b)  Example 2 4head :: Vec (n + 1) a -> a head' :: forall n a. (1 |€ n) => Vec n a -> a head' = Ô 1 n head Õ clash-preludeSame as Ô with added ƒ constraintsà clash-preludeBaseÄ clash-preludeBaseÅ clash-preludeBaseÔ clash-preludeContext with the  (n ~ (k + m)) constraintÕ clash-preludeContext with the  (n ~ (k + m)) constraint8žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕ8¨©ª«­¯±¬®°»½¾Áº¼¿ÀÃÄŹƢ£¤Ç¥¦§²³´µ¶·¸žŸ ¡ÉÊÈÎËÌÍÏÐÑÒÓÔÕ»6¼6½7¾8¿7À7Ö(C) 2013-2016, University of Twente, 2019 , GergÑ Érdi 2016-2019, Myrtle Software Ltd, 2021-2022, QBayLogic B.V. 2023 , Nadia ChambersBSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe#&/02356789:; Maybe Bool decode $(bitPattern "00.._.110") = Just True decode $(bitPattern "10.._0001") = Just False decode $(bitPattern "aa.._b0b1") = Just (aa + bb > 1) decode _ = Nothing · clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer lm and the ˆ class.º clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer lm and the ˆ class.¼ clash-preludeThe functions:  ,  ,  , and  , are not synthesizable.ª clash-preludeunpack functionÓ´Þßàµáãâ¶äåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­Ó´Þßàäåæçèéêëìíîïðñòóµáãâ•–ôõö«›’“”—œ�šž˜™÷ø¬ùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž�Ÿ ¡¢£¤¥¦§�‘¨©¶ª­Ì(C) 2013-2016, University of Twente 2022 , Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<ÇÉÐÑÖ×Ùâì ºÖ clash-prelude&Shift in a bit from the MSB side of a µ. Equal to right shifting the µ< by one and replacing the MSB with the bit to be shifted in.!1 +>>. 0b1111_0000 :: BitVector 8 0b1111_1000!0 +>>. 0b1111_0000 :: BitVector 8 0b0111_1000× clash-prelude&Shift in a bit from the LSB side of a µ. Equal to left shifting the µ< by one and replacing the LSB with the bit to be shifted in.!0b1111_0000 .<<+ 0 :: BitVector 8 0b1110_0000!0b1111_0000 .<<+ 1 :: BitVector 8 0b1110_0001 ´µäåôõö•–›­Ö× ´ä嵕–ôõö›Ö×­Ö4×4«(C) 2013-2016, University of Twente, 2017-2019, Myrtle Software Ltd 2017-2022, Google Inc., 2021-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe'%&'(-/02356789:;<>?ÀÇÉÊÐÑÖ×Ùàâè쇦�Ù clash-preludeClock edge A producedÚ clash-preludeClock edge B producedÛ clash-preludeClock edges coincidedÜ clash-prelude,A reset signal belonging to a domain called dom.+The underlying representation of resets is ;.Þ clash-preludeFemtoseconds expressed as an †Ñ. Is a newtype to prevent accidental mixups with picoseconds - the unit used in ’.à clash-prelude8A 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 c�', the names of the inputs will end in _p and _n respectively.=To create a differential clock in a test bench, you can use ‚.â clash-preludeéThe negative or inverted phase of a differential clock signal. HDL generation will treat it the same as å, except that no  create_clock( command is issued in the SDC file for â . Used in à.å clash-prelude+A clock signal belonging to a domain named dom.ç clash-prelude Domain associated with the clockè clash-prelude¼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.é clash-preludeå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.ë clash-preludeClash has synchronous ës in the form of: ë (dom :: í) a Where a! is the type of the value of the ë, for example Int or Bool, and dom is the clock- (and reset-9) domain to which the memory elements manipulating these ë s belong.The type-parameter, dom, is of the kind í3 - 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"¢B happen when you actually use a clock period of 0, so do not do that!NB7: You should be judicious using a clock with period of 16 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 ø> has good defaults depends on your target platform. Check out ÷ and ö 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.ì clash-preludeThe constructor, (ì), is not synthesizable.î clash-preludeûSame as SDomainConfiguration but allows for easy updates through record update syntax. Should be used in combination with ¶ and · . Example: ÁcreateDomain (knownVDomain @System){vName="System10", vPeriod=10}$This duplicates the settings in the ø£ 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: 2createDomain vSystem{vName="System10", vPeriod=10}ð clash-preludeCorresponds to ” on ’ñ clash-preludeCorresponds to • on ’ò clash-preludeCorresponds to – on ’ó clash-preludeCorresponds to — on ’ô clash-preludeCorresponds to ˜ on ’õ clash-preludeCorresponds to ™ on ’ö clash-preludeØ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.÷ clash-preludeÙ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.ø clash-preludeÙ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.ù clash-preludeA ùÝ constraint indicates that a circuit's behavior depends on some properties of a domain. See ’ for more information.û clash-preludeReturns ý corresponding to an instance's ’.Example usage:knownDomain @System²SDomainConfiguration {sName = SSymbol @"System", sPeriod = SNat @10000, sActiveEdge = SRising, sResetKind = SAsynchronous, sInitBehavior = SDefined, sResetPolarity = SActiveHigh}ý clash-preludeSingleton version of ’ÿ clash-prelude Domain name€ clash-preludePeriod of clock in ps� clash-prelude.Active edge of the clock (not yet implemented)‚ clash-preludeÑWhether resets are synchronous (edge-sensitive) or asynchronous (level-sensitive)ƒ clash-prelude÷Whether the initial (or "power up") value of memory elements is unknown/undefined, or configurable to a specific value„ clash-prelude,Whether resets are active high or active low… clash-preludeÕConvenience type to help to extract the reset polarity from a domain. Example usage: ÊmyFunc :: (KnownDomain dom, DomainResetPolarity dom ~ 'ActiveHigh) => ... † clash-preludeÎConvenience type to constrain a domain to have initial values. Example usage: -myFunc :: HasDefinedInitialValues dom => ... Using this type implies ù.Note that there is no UnknownInitialValues dom× as a component that works without initial values will also work if it does have them.(Clash.Explicit.Signal#g:conveniencetypesClick here for usage hints‡ clash-preludeÝConvenience type to help to extract the initial value behavior from a domain. Example usage: ÆmyFunc :: (KnownDomain dom, DomainInitBehavior dom ~ 'Defined) => ... ˆ clash-preludeÓConvenience type to constrain a domain to have asynchronous resets. Example usage: *myFunc :: HasAsynchronousReset dom => ... Using this type implies ù.(Clash.Explicit.Signal#g:conveniencetypesClick here for usage hints‰ clash-preludeÒConvenience type to constrain a domain to have synchronous resets. Example usage: )myFunc :: HasSynchronousReset dom => ... Using this type implies ù.(Clash.Explicit.Signal#g:conveniencetypesClick here for usage hintsŠ clash-preludeÚConvenience type to help to extract the reset synchronicity from a domain. Example usage: ÇmyFunc :: (KnownDomain dom, DomainResetKind dom ~ 'Synchronous) => ... ‹ clash-preludeÒConvenience type to help to extract the active edge from a domain. Example usage: ÃmyFunc :: (KnownDomain dom, DomainActiveEdge dom ~ 'Rising) => ... Œ clash-preludeÊConvenience type to help to extract a period from a domain. Example usage:  ... � clash-preludeHelper type family for …Ž clash-preludeHelper type family for ‡� clash-preludeHelper type family for Š� clash-preludeHelper type family for ‹‘ clash-preludeHelper type family for Œ’ clash-preludeA 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.” clash-prelude Domain name• clash-preludePeriod of clock in ps– clash-preludeActive edge of the clock— clash-preludeÑWhether resets are synchronous (edge-sensitive) or asynchronous (level-sensitive)˜ clash-prelude÷Whether the initial (or "power up") value of memory elements is unknown/undefined, or configurable to a specific value™ clash-prelude,Whether resets are active high or active lowž clash-prelude%Power up value of memory elements is unknown.Ÿ clash-preludeÊIf applicable, power up value of a memory element is defined. Applies to ƒs for example, but not to V„.  clash-preludeSingleton version of ££ clash-preludeÂDetermines the value for which a reset line is considered "active"¤ clash-prelude3Reset is considered active if underlying signal is L.¥ clash-prelude3Reset is considered active if underlying signal is I.¦ clash-preludeSingleton version of ©ª clash-preludeElements 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.« clash-preludeElements 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.¬ clash-preludeSingleton version of ¯¯ clash-preludeÍDetermines clock edge memory elements are sensitive to. Not yet implemented.° clash-preludeÅElements are sensitive to the rising edge (low-to-high) of the clock.± clash-preludeÆElements are sensitive to the falling edge (high-to-low) of the clock.² clash-prelude Version of û that takes a ˜. For example:%knownDomainByName (SSymbol @"System")²SDomainConfiguration {sName = SSymbol @"System", sPeriod = SNat @10000, sActiveEdge = SRising, sResetKind = SAsynchronous, sInitBehavior = SDefined, sResetPolarity = SActiveHigh}³ clash-preludeäConvenience value to allow easy "subclassing" of System domain. Should be used in combination with ·Þ. For example, if you just want to change the period but leave all other settings intact use: 2createDomain vSystem{vName="System10", vPeriod=10}´ clash-preludeéConvenience value to allow easy "subclassing" of IntelSystem domain. Should be used in combination with ·Þ. For example, if you just want to change the period but leave all other settings intact use: 6createDomain vIntelSystem{vName="Intel10", vPeriod=10}µ clash-preludeêConvenience value to allow easy "subclassing" of XilinxSystem domain. Should be used in combination with ·Þ. For example, if you just want to change the period but leave all other settings intact use: 8createDomain vXilinxSystem{vName="Xilinx10", vPeriod=10}¶ clash-preludeConvert ý to î&. Should be used in combination with · only.· clash-prelude=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: 2createDomain 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 î% that you can use in later calls to ·: "vSystem10 = knownVDomain @System10It will also make System10 an instance of ù.•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"}¸ clash-preludeÞWe either get evidence that this function was instantiated with the same domains, or Nothing.¾ clash-preludeWARNING: EXTREMELY EXPERIMENTALíThe circuit semantics of this operation are unclear and/or non-existent. There is a good reason there is no ) instance for ë.Is currently treated as X by the Clash compiler.¿ clash-preludeNB: Not synthesizableNB: In "¿ f z s": The function f should be lazy in its second argument.The z element will never be used.Á clash-preludeConvert éÀ construct to its underlying representation: a signal of bools. clash-prelude Convert a signal of bools to an é constructà clash-prelude8Enable generator for some domain. Is simply always True.Ä clash-prelude$Clock generator for simulations. Do not# use this clock generator for the  testBench function, use Å instead.To be used like: clkSystem = clockGen @System See ’6 for more information on how to use synthesis domains.Å clash-prelude"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" b… b†Ä{vName="Fast", vPeriod=10} -- Slow domain: twice as slow as "Fast" b… b†+{vName="Slow", vPeriod=20} topEntity :: å "Fast" -> Ü "Fast" -> é "Fast" -> å "Slow" -> ë "Fast" (Unsigned 8) -> ëê "Slow" (Unsigned 8, Unsigned 8) topEntity clk1 rst1 en1 clk2 i = let h = register clk1 rst1 en1 0 (register clk1 rst1 en1 0 i) l = register clk1 rst1 en1 0 i in unsafeSynchronizer clk1 clk2 (bundle (h, l)) testBench :: ë; "Slow" Bool testBench = done where testInput = ‡ clkA1 rstA1 $(ˆ5 [1::Unsigned 8,2,3,4,5,6,7,8]) expectedOutput = ‰ clkB2 rstB2 $(ˆË [(0,0) :: (Unsigned 8, Unsigned 8),(1,2),(3,4),(5,6),(7,8)]) done = expectedOutput (topEntity clkA1 rstA1 enableGen clkB2 testInput) notDone = not <$> done clkA1 = ÅÇ @"Fast" (unsafeSynchronizer clkB2 clkA1 notDone) clkB2 = Å& @"Slow" notDone rstA1 = Š @"Fast" rstB2 = Š @"Slow" Æ clash-preludeStrip newtype wrapper ÞÇ clash-preludeMap † fields in ÞÈ clash-prelude‚Clock generator with dynamic clock periods for simulations. This is an experimental feature and hence not part of the public API.To be used like: $clkSystem = dynamicClockGen @System See ’6 for more information on how to use synthesis domains.É clash-preludeˆClock generator with dynamic clock periods for simulations. This is an experimental feature and hence not part of the public API. Like ÅTo be used like: $clkSystem = dynamicClockGen @System See ’6 for more information on how to use synthesis domains.Ê clash-preludeÏReset generator for simulation purposes. Asserts the reset for a single cycle.To be used like: rstSystem = resetGen @System See ‹ for example usage.NB : While this can be used in the  testBench1 function, it cannot be synthesized to hardware.Ë clash-preludeÉReset generator for simulation purposes. Asserts the reset for the first n cycles.To be used like: !rstSystem5 = resetGen @System d5 Example usage:5sampleN 7 (unsafeToActiveHigh (resetGenN @System d3))([True,True,True,False,False,False,False]NB : While this can be used in the  testBench1 function, it cannot be synthesized to hardware.Ì clash-prelude…Convert a reset to an active high reset. Has no effect if reset is already an active high reset. Is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityþFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.Í clash-prelude…Convert a reset to an active high reset. Has no effect if reset is already an active high reset. Is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityþFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.Î clash-prelude†Convert a reset to an active low reset. Has no effect if reset is already an active low reset. It is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityþFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.Ï clash-prelude†Convert a reset to an active low reset. Has no effect if reset is already an active low reset. It is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityþFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.Ð clash-preludeÐ$ is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityþFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.NB: You probably want to use Î or Ì.Ñ clash-preludeÑŽ is unsafe. For asynchronous resets it is unsafe because it can introduce combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability0 issues in the presence of asynchronous resets.NB: You probably want to use Õ or Ó.Ò clash-preludeüInterpret a signal of bools as an active high reset and convert it to a reset signal corresponding to the domain's setting.þFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.Ó clash-preludeüInterpret a signal of bools as an active high reset and convert it to a reset signal corresponding to the domain's setting.þFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.Ô clash-preludeûInterpret a signal of bools as an active low reset and convert it to a reset signal corresponding to the domain's setting.þFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.Õ clash-preludeûInterpret a signal of bools as an active low reset and convert it to a reset signal corresponding to the domain's setting.þFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.Ö clash-preludeInvert reset signal× clash-prelude'The above type is a generalization for: (.||.) :: n ; -> n ; -> n ; It is a version of (€) that returns a n of ;Ø clash-prelude'The above type is a generalization for: (.&&.) :: n ; -> n ; -> n ; It is a version of (ÿ) that returns a n of ;Ú clash-prelude®A register with a power up and reset value. Power up values are not supported on all platforms, please consult the manual of your target platform and check the notes below.àXilinx: power up values and reset values MUST be the same. If they are not, the Xilinx tooling will ignore the reset value1 and use the power up value instead. Source: MIAÞIntel: power up values and reset values MUST be the same. If they are not, the Intel tooling will ignore the power up value+ and use the reset value instead. Source: úhttps://www.intel.com/content/www/us/en/programmable/support/support-resources/knowledge-base/solutions/rd01072011_91.htmlÛ clash-prelude Acts like XÎ if given domain allows powerup values, but returns a value constructed with Î otherwise.Ü clash-prelude Version of ÚÈ that simulates a register on an asynchronous domain. Is synthesizable.Ý clash-prelude Version of ÚÇ that simulates a register on a synchronous domain. Not synthesizable.Þ clash-prelude'The above type is a generalization for: mux :: n ; -> n a -> n a -> n a A multiplexer. Given "Þ b t f ", output t when b is L, and f when b is I.ß clash-prelude'The above type is a generalization for: (.==.) :: % a => n a -> n a -> n ; It is a version of () that returns a n of ;à clash-prelude'The above type is a generalization for: (./=.) :: % a => n a -> n a -> n ; It is a version of (S) that returns a n of ;á clash-prelude'The above type is a generalization for: (.<.) :: , a => n a -> n a -> n ; It is a version of (×) that returns a n of ;â clash-prelude'The above type is a generalization for: (.<=.) :: , a => n a -> n a -> n ; It is a version of (|€) that returns a n of ;ã clash-prelude'The above type is a generalization for: (.>.) :: , a => n a -> n a -> n ; It is a version of (Ù) that returns a n of ;ä clash-prelude'The above type is a generalization for: (.>=.) :: , a => n a -> n a -> n ; It is a version of () that returns a n of ;å clash-prelude'The above type is a generalization for: testFor :: ? -> n Bool -> ‡  testFor n s tests the signal s for n cycles.NB$: This function is not synthesizableæ clash-prelude'The above type is a generalization for: sample :: n a -> [a] 'Get an infinite list of samples from a n9The elements in the list correspond to the values of the n at consecutive clock cycles  sample s == [s0, s1, s2, s3, ...NB$: This function is not synthesizableç clash-prelude'The above type is a generalization for: sampleN :: Int -> n a -> [a] Get a list of n samples from a n9The elements in the list correspond to the values of the n at consecutive clock cycles sampleN 3 s == [s0, s1, s2]NB$: This function is not synthesizableè clash-prelude Create a n from a listØEvery element in the list will correspond to a value of the signal for one clock cycle. sampleN 2 (fromList [1,2,3,4,5])[1,2]NB$: This function is not synthesizableé clash-prelude Simulate a (n a -> n b,) function given a list of samples of type aÄsimulate (register systemClockGen resetGen enableGen 8) [1, 1, 2, 3] [8,8,1,2,3......NB$: This function is not synthesizableê clash-prelude'The above type is a generalization for: sample :: n a -> [a] 'Get an infinite list of samples from a n9The elements in the list correspond to the values of the n at consecutive clock cycles  sample s == [s0, s1, s2, s3, ...NB$: This function is not synthesizableë clash-prelude'The above type is a generalization for: sampleN :: Int -> n a -> [a] Get a list of n samples from a n9The elements in the list correspond to the values of the n at consecutive clock cycles sampleN 3 s == [s0, s1, s2]NB$: This function is not synthesizableì clash-prelude Create a n from a listØEvery element in the list will correspond to a value of the signal for one clock cycle.5sampleN 2 (fromList [1,2,3,4,5] :: Signal System Int)[1,2]NB$: This function is not synthesizableí clash-prelude Simulate a (n a -> n b,) function given a list of samples of type aÄsimulate (register systemClockGen resetGen enableGen 8) [1, 1, 2, 3] [8,8,1,2,3......NB$: This function is not synthesizableî clash-preludeCalculate the period in ps, given a frequency in HzÊI.e., to calculate the clock period for a circuit to run at 240 MHz we gethzToPeriod 240e64166 If the value  hzToPeriod" is applied to is not of the type ˆ ø, you can use  hzToPeriod ( f). Note that if f is negative,  realToFrac will give an Œ� :: ŒŽ4 without a call stack, making debugging cumbersome.2Before Clash 1.8, this function always returned a øÄ. To get the old behavior of this function, use a type application:hzToPeriod @Natural 240e64166NB$: This function is not synthesizableNB : This function is lossy. I.e., periodToHz . hzToPeriod /= id.ï clash-preludeCalculate the period in fs, given a frequency in HzÊI.e., to calculate the clock period for a circuit to run at 240 MHz we get hzToFs 240e6Femtoseconds 4166666 If the value hzToFs" is applied to is not of the type ˆ ø, you can use hzToFs ( f). Note that if f is negative,  realToFrac will give an Œ� :: ŒŽ4 without a call stack, making debugging cumbersome.NB$: This function is not synthesizableNB!: This function is lossy. I.e., fsToHz . hzToFs /= id.ð clash-preludeCalculate the frequency in Hz, given the period in psËI.e., to calculate the clock frequency of a clock with a period of 5000 ps:periodToHz 50002.0e8 Note that if p in  periodToHz ( p) is negative,  fromIntegral will give an Œ� :: ŒŽ4 without a call stack, making debugging cumbersome.2Before Clash 1.8, this function always returned a ˆ øÃ. To get the old behavior of this function, use a type application: periodToHz @(Ratio Natural) 5000 200000000 % 1NB$: This function is not synthesizableñ clash-preludeCalculate the frequency in Hz, given the period in fsËI.e., to calculate the clock frequency of a clock with a period of 5000 fs:fsToHz (Femtoseconds 5000)2.0e11NB$: This function is not synthesizableò clash-prelude Build an ‰ from a function over ës.NB%: Consumption of continuation of the ‰ò must be affine; that is, you can only apply the continuation associated with a particular element at most once.ó clash-prelude—Given two clocks, produce a list of clock ticks indicating which clock (or both) ticked. Can be used in components handling multiple clocks, such as unsafeSynchronizer or dual clock FIFOs.èIf your primitive does not care about coincided clock edges, it should - by convention - replace it by ClockB:ClockA:.ô clash-preludežGiven two clock periods, produce a list of clock ticks indicating which clock (or both) ticked. Can be used in components handling multiple clocks, such as unsafeSynchronizer or dual clock FIFOs.èIf your primitive does not care about coincided clock edges, it should - by convention - replace it by ClockB:ClockA:.ù clash-prelude1System instance with defaults set for Intel FPGAsú clash-prelude2System instance with defaults set for Xilinx FPGAsû clash-preludeA clock (and reset$) dom with clocks running at 100 MHz€ clash-preludeNB: Not synthesizableNB: In "Š f z s": The function f should be lazy in its second argument.The z element will never be used. È clash-preludeClock period in femtoseconds.NBŸ: Beware that the periods are given in femtoseconds; this differs from the usual unit Clash uses to represent period length, picoseconds.NB„: Beware that not all simulators support femtoseconds. For example, Vivado's XSIM will round down to nearest picoseconds.NB-: Beware that, by default, Clash will define `timescale 100fs/100fsŸ in its generated Verilog. The latter will make simulators round time to 100fs. If you rely on more precision you should pass -fclash-timescale-precision 1fs to Clash.É clash-preludeClock period in femtoseconds.NBŸ: Beware that the periods are given in femtoseconds; this differs from the usual unit Clash uses to represent period length, picoseconds.NB„: Beware that not all simulators support femtoseconds. For example, Vivado's XSIM will round down to nearest picoseconds.NB-: Beware that, by default, Clash will define `timescale 100fs/100fsŸ in its generated Verilog. The latter will make simulators round time to 100fs. If you rely on more precision you should pass -fclash-timescale-precision 1fs to Clash.Ë clash-prelude+Number of initial cycles to hold reset highÒ clash-preludeReset signal that's L when active, and I when inactive.Ó clash-preludeReset signal that's L when active, and I when inactive.Ô clash-preludeReset signal that's I when active, and L when inactive.Õ clash-preludeReset signal that's I when active, and L when inactive.Ú clash-preludePower up value clash-prelude Reset valueÜ clash-prelude Clock signal clash-prelude Reset signal clash-prelude Enable signal clash-preludePower up value clash-prelude Reset valueÝ clash-prelude Clock signal clash-prelude Reset signal clash-prelude Enable signal clash-preludePower up value clash-prelude Reset value�ØÛÙÚÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóô�ë칺í¸ùúûü²¯°±¬­®�žŸš›œ©ª«¦§¨£¤¥ ¡¢’“”•–—˜™ýþÿ€�‚ƒ„Œ‹Š‡…‘��Ž�‰ˆ†øö÷³´µîïðñòóôõ¶·åæçèâãäàáîðØÛÙÚóôéêÂÁÃÜÝÑÐÌÎÓÕÖÙÚÜÝÛÞÄÅÞßñïÆÇÉÈÊËØ×éíòæçèêëìåßàáâä㻼½¿À¾ÒÔÍÏ ì5×2Ø3ß4à4á4â4ã4ä4(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)%QBayLogic B.V. None &/02356789;<>ÀÁÂÄÇÉÐÑÖ×Ùâ씘 clash-prelude×An AssertionValue is a bool-like value or stream that can be used in property specifications. Clash implements two: a stream of booleans (Signal dom Bool), and the result of a property expression (Assertion dom).à clash-prelude$Convert given type into a Assertion.Ä clash-preludeøA result of some property. Besides carrying the actual boolean result, it carries some properties used to make reports.Æ clash-prelude)Name of property belonging to this resultÇ clash-prelude3False whenever property is violated, True otherwiseÈ clash-prelude÷A property is a temporal or basic assertion that's specified to either used as an _assert_ or _cover_ statement. See  � and  �.Ì clash-preludeInternal version of È#. All user facing will instantiate a with (Maybe Text, Signal dom Bool)'. Blackboxes will instantiate it with (Maybe Text, Term) instead.Ð clash-preludeInternal version of Ê.Ñ clash-prelude"(Bootstrapping) signal of booleansÒ clash-prelude7Tag to force a non-temporal assertion to a temporal oneÓ clash-preludeBoolean literalÔ clash-prelude Logical notÕ clash-prelude Logical andÖ clash-prelude Logical or× clash-preludeLogical impliesØ clash-preludeMoves start point of assertion n cycles forwardÙ clash-preludeBefore  CvBefore a b is the same as CvAnd a (CvNext 1 b)Ú clash-preludeTemporal implies CvTemporalImplies n a b:n | n == 0 -> same as  CvImplies a b | otherwise -> same as CvImplies a (CvNextN n b)Û clash-preludeAssertion should _always_ holdÜ clash-prelude4Assertion should _never_ hold (not supported by SVA)Ý clash-prelude"Assertion should _eventually_ holdá clash-preludeRender target for HDLâ clash-preludeProperty Specification Languageã clash-preludeSystemVerilog Assertionsä clash-prelude)Use SVA for SystemVerilog, PSL for otherså clash-prelude=Yosys Formal Extensions for Verilog and SystemVerilog. See:  8https://symbiyosys.readthedocs.io/en/latest/verilog.html and 8https://symbiyosys.readthedocs.io/en/latest/verific.htmläFalls back to PSL for VHDL, however currently Clash's PSL syntax isn't suported by GHDL+SymbiYosys;é clash-prelude"Result of a property specificationê clash-prelude.Stream of booleans, originating from a circuit'ÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞàßáâãäåæçè'ÄÅÆÇÈÉÊËáâãäåÞàßÂÃÐÑÒÓÔÕÖרÙÚÛÜÝÌÍÎÏæçèNone%&/02356789;<ÇÉÐÑÔÖ×Ùâì™Yø clash-prelude/Get the clock period from a KnownDomain contextù clash-preludeGet ¯+ from a KnownDomain context. Example usage: õf :: forall dom . KnownDomain dom => .... f a b c = case activeEdge @dom of SRising -> foo SFalling -> bar ú clash-preludeGet ©+ from a KnownDomain context. Example usage: þf :: forall dom . KnownDomain dom => .... f a b c = case resetKind @dom of SAsynchronous -> foo SSynchronous -> bar û clash-preludeGet �+ from a KnownDomain context. Example usage: øf :: forall dom . KnownDomain dom => .... f a b c = case initBehavior @dom of SDefined -> foo SUnknown -> bar ü clash-preludeGet £+ from a KnownDomain context. Example usage: þf :: forall dom . KnownDomain dom => .... f a b c = case resetPolarity @dom of SActiveHigh -> foo SActiveLow -> bar ý clash-preludeLike 'knownDomain but yields a î+. Should only be used in combination with ·.øùúûüýýøùúûü‘None&/02356789;<ÇÉÐÑÖ×Ùâìšd‹ clash-prelude,Contruct all the tuple instances for Bundle.‹ clash-preludeBundle clash-prelude Unbundled clash-preludebundle clash-preludeunbundleŒ‹ Ä(C) 2019, Myrtle Software Ltd 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<ÇÉÐÑÖ×Ùâì¨þ clash-prelude®Convert a signal to a cv expression with a name hint. Clash will try its best to use this name in the rendered assertion, but might run into collisions. You can skip using þÏ altogether. Clash will then try its best to get a readable name from context.ÿ clash-prelude8For using a literal (either True or False) in assertions€  clash-preludeTruth table for € : 6a | not a ------------ True | False False | True �  clash-preludeTruth table for � : a | b | a � ô b --------------|---------- False | False | False False | True | False True | False | False True | True | True ‚  clash-preludeTruth table for ‚ : a | b | a ‚ ñ b --------------|--------- False | False | False False | True | True True | False | True True | True | True ƒ  clash-preludeTruth table for ƒ : a | b | a ƒ ö b --------------|-------------- False | False | True False | True | True True | False | False True | True | True „  clash-preludeTruth table for „ : a[n] | a[n+1] | a ƒ … next a ---------------|------------------- False | False | True False | True | True True | False | False True | True | True #where a[n] represents the value of a at cycle n and a[n+1] represents the value of a at cycle n+1 . Cycle n is an arbitrary cycle.…  clash-preludeTruth table for … : a[n] | a[n+m] | a ƒ ‰ next m a ---------------|--------------------- False | False | True False | True | True True | False | False True | True | True #where a[n] represents the value of a at cycle n% and a[n+m] represents the value of a at cycle n+m . Cycle n is an arbitrary cycle.†  clash-preludeSame as  a && next b but with a nice syntax. E.g.,  a && next b could be written as a †  b2. Might be read as "a happens one cycle before b".‡  clash-preludeSame as a ƒ  next b but with a nice syntax. E.g., a ƒ  next b could be written as a ‡  b:. Might be read as "a at cycle n implies b at cycle n+1".ˆ  clash-preludeSame as ƒ  but strictly temporal.‰  clash-prelude&Specify assertion should _always_ holdŠ  clash-prelude Trustworthy &'(/02356789;<ÁÂÇÉÊÎÐÑÖ×Ùâì·¯ ’  clash-prelude+A synchronized signal with samples of type a, synchronized to clock clk, that has accumulated delay( amount of samples delay along its path.DSignal has the Îhttps://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i DSignal2type role DSignal nominal nominal representational...öas it is safe to coerce the values in the signal, but not safe to coerce the synthesis domain or delay in the signal.”  clash-preludeStrip a ’  of its delay information.•  clash-prelude Create a ’  from a listØEvery element in the list will correspond to a value of the signal for one clock cycle.,sampleN 2 (toSignal (dfromList [1,2,3,4,5]))[1,2]NB$: This function is not synthesizable–  clash-prelude Create a ’  from a listØEvery element in the list will correspond to a value of the signal for one clock cycle.,sampleN 2 (toSignal (dfromList [1,2,3,4,5]))[1,2]NB$: This function is not synthesizable—  clash-prelude8Feed the delayed result of a function back to its input: Ümac :: forall dom . KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> ’  dom 0 Int -> ’  dom 0 Int -> ’  dom 0 Int mac clk rst en x y = — & (mac' x y) where mac' :: ’  dom 0 Int -> ’  dom 0 Int -> ’  dom 0 Int -> (’  dom 0 Int, ’ Ó dom 1 Int) mac' a b acc = let acc' = a * b + acc in (acc, <’ clk rst en 0 acc') æsampleN 7 (toSignal (mac systemClockGen systemResetGen enableGen (dfromList [0..]) (dfromList [0..])))[0,0,1,5,14,30,55]˜  clash-preludeës are not delayed™  clash-prelude EXPERIMENTALUnsafely convert a ë to a ’  with an arbitrary delay.NBÉ: Should only be used to interface with functions specified in terms of ë.š  clash-prelude EXPERIMENTAL Access a delayedò signal from the future in the present. Often required When writing a circuit that requires feedback from itself. Ìmac :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> ’  dom 0 Int -> ’  dom 0 Int -> ’  dom 0 Int mac clk rst en x y = acc' where acc' = (x * y) + š  d1 acc acc = <’ clk rst en 0 acc' ›  clash-prelude EXPERIMENTAL Access a delayed8 signal from the past in the present. In contrast with <“ñ and friends forward does not insert any logic. This means using this function violates the delay invariant of ’ Ö. This is sometimes useful when combining unrelated delayed signals where inserting logic is not wanted or when abstracting over internal delayed signals where the internal delay information should not be leaked.«For example, the circuit below returns a sequence of numbers as a pair but the internal delay information between the elements of the pair should not leak into the type. ànumbers :: forall dom . KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> ’ × dom 5 (Int, Int) numbers clk rst en = DB.bundle (forward d1 s1, s2) where s1 :: ’  dom 4 Int s1 = <“> clk rst en (100 :> 10 :> 5 :> 1 :> Nil) (pure 200) s2 :: ’  dom 5 Int s2 = fmap (2*) $ <” d1 0 en clk s1 ÆsampleN 8 (toSignal (numbers systemClockGen systemResetGen enableGen))Â[(1,0),(1,2),(5,2),(10,10),(100,20),(200,200),(200,400),(200,400)] ’ “ ” • – — ˜ ™ š › ’ “ ” — ˜ • – ™ š › "Ï(C) 2015-2016, University of Twente 2022 , QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe&/02356789;<ÇÉÐÑÖ×Ùâì¸á§  clash-prelude!I hope you know what you're doing§ § ##(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<ÇÉÐÑÖ×Ùâ캮¨  clash-prelude Create an ¨ literal $(decLiteralD 1111):t d1111d1111 :: SNat 1111©  clash-preludeCreate a range of ¨ literals $(decLiteralsD 1200 1202):t d1200d1200 :: SNat 1200:t d1201d1201 :: SNat 1201:t d1202d1202 :: SNat 1202¨ © ¨ © $#(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<ÇÉÐÑÖ×Ùâì»l�ª « ¬ ­ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ € � ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ � Ž � � ‘ ’ “ ” • – — ˜ ™ š › œ � ž Ÿ   ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ € � ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ � Ž � � ‘ ’ “ ” • – — ˜ ™ š › œ � ž Ÿ   ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ € � ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ � Ž � � ‘ ’ “ ” • – — ˜ ™ š › œ � ž Ÿ   ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ € � ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ � Ž � � ‘ ’ “ ” • – — ˜ ™ š › œ � ž Ÿ   ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ €�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª�ª©¨§¦¥¤£¢¡ Ÿž�œ›š™˜—–•”“’‘��Ž�Œ‹Š‰ˆ‡†…„ƒ‚�€ÿþýüûúùø÷öõôóòñðïîíìëêéèçæåäãâáàßÞÝÜÛÚÙØ×ÖÕÔÓÒÑÐÏÎÍÌËÊÉÈÇÆÅÄÃÂÁÀ¿¾½¼»º¹¸·¶µ´³²±°¯®­¬«ª©¨§¦¥¤£¢¡ Ÿž�œ›š™˜—–•”“’‘��Ž�Œ‹Š‰ˆ‡†…„ƒ‚�€ÿþýüûúùø÷öõôóòñðïîíìëêéèçæåäãâáàßÞÝÜÛÚÙØ×ÖÕÔÓÒÑÐÏÎÍÌËÊÉÈÇÆÅÄÃÂÁÀ¿¾½¼»º¹¸·¶µ´³²±°¯®­¬«ª©¨§¦¥¤£¢¡ Ÿž�œ›š™˜—–•”“’‘��Ž�Œ‹Š‰ˆ‡†…„ƒ‚�€ÿþýüûúùø÷öõôóòñðïîíìëêéèçæåäãâáàßÞÝÜÛÚÙØ×ÖÕÔÓÒÑÐÏÎÍÌËÊÉÈÇÆÅÄÃÂÁÀ¿¾½¼»º¹¸·¶µ´³²±°¯®­¬«ª©¨§¦¥¤£¢¡ Ÿž�œ›š™˜—–•”“’‘��Ž�Œ‹Š‰ˆ‡†…„ƒ‚�€ÿ þ ý ü û ú ù ø ÷ ö õ ô ó ò ñ ð ï î í ì ë ê é è ç æ å ä ã â á à ß Þ Ý Ü Û Ú Ù Ø × Ö Õ Ô Ó Ò Ñ Ð Ï Î Í Ì Ë Ê É È Ç Æ Å Ä Ã Â Á À ¿ ¾ ½ ¼ » º ¹ ¸ · ¶ µ ´ ³ ² ± ° ¯ ® ­ ¬ « ª © ¨ § ¦ ¥ ¤ £ ¢ ¡   Ÿ ž � œ › š ™ ˜ — – • ” “ ’ ‘ � � Ž � Œ ‹ Š ‰ ˆ ‡ † … „ ƒ ‚ � € ÿ þ ý ü û ú ù ø ÷ ö õ ô ó ò ñ ð ï î í ì ë ê é è ç æ å ä ã â á à ß Þ Ý Ü Û Ú Ù Ø × Ö Õ Ô Ó Ò Ñ Ð Ï Î Í Ì Ë Ê É È Ç Æ Å Ä Ã Â Á À ¿ ¾ ½ ¼ » º ¹ ¸ · ¶ µ ´ ³ ² ± ° ¯ ® ­ ¬ « ª © ¨ § ¦ ¥ ¤ £ ¢ ¡   Ÿ ž � œ › š ™ ˜ — – • ” “ ’ ‘ � � Ž � Œ ‹ Š ‰ ˆ ‡ † … „ ƒ ‚ � € ÿ þ ý ü û ú ù ø ÷ ö õ ô ó ò ñ ð ï î í ì ë ê é è ç æ å ä ã â á à ß Þ Ý Ü Û Ú Ù Ø × Ö Õ Ô Ó Ò Ñ Ð Ï Î Í Ì Ë Ê É È Ç Æ Å Ä Ã Â Á À ¿ ¾ ½ ¼ » º ¹ ¸ · ¶ µ ´ ³ ² ± ° ¯ ® ­ ¬ « ª © ¨ § ¦ ¥ ¤ £ ¢ ¡   Ÿ ž � œ › š ™ ˜ — – • ” “ ’ ‘ � � Ž � Œ ‹ Š ‰ ˆ ‡ † … „ ƒ ‚ � € ÿ þ ý ü û ú ù ø ÷ ö õ ô ó ò ñ ð ï î í ì ë ê é è ç æ å ä ã â á à ß Þ Ý Ü Û Ú Ù Ø × Ö Õ Ô Ó Ò Ñ Ð Ï Î Í Ì Ë Ê É È Ç Æ Å Ä Ã Â Á À ¿ ¾ ½ ¼ » º ¹ ¸ · ¶ µ ´ ³ ² ± ° ¯ ® ­ ¬ « ª © ¨ § ¦ ¥ ¤ £ ¢ ¡   Ÿ ž � œ › š ™ ˜ — – • ” “ ’ ‘ � � Ž � Œ ‹ Š ‰ ˆ ‡ † … „ ƒ ‚ � € ÿ þ ý ü û ú ù ø ÷ ö õ ô ó ò ñ ð ï î í ì ë ê é è ç æ å ä ã â á à ß Þ Ý Ü Û Ú Ù Ø × Ö Õ Ô Ó Ò Ñ Ð Ï Î Í Ì Ë Ê É È Ç Æ Å Ä Ã Â Á À ¿ ¾ ½ ¼ » º ¹ ¸ · ¶ µ ´ ³ ² ± ° ¯ ® ­ ¬ « ª %(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij  Safe-Inferred&/02356789;<ÇÉÐÑÖ×ÙâìÌ"«¬«¬&(C) 2019, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<ÇÉÐÑÖ×Ùâì͈­ clash-preludeÂContruct all the tuple (starting at size 3) instances for BitPack.­ clash-preludeBitPack clash-preludeBitSize clash-preludepack clash-preludeunpack­­'¬(C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2021-2023 QBayLogic B.V., 2022, Google Inc.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789; a -> b f = unpack . go . pack where go :: BitVector (BitSize a) -> BitVector (BitSize b) go = _ -- A function on the underlying bit vector ÆA type should only implement this class if it has a statically known size, as otherwise it is not possible to determine how many bits are needed to represent values. This means that types such as [a] cannot have BitPack instances, as even if aÑ has a statically known size, the length of the list cannot be known in advance.ÌIt is not possible to give data a custom bit representation by providing a BitPack instance. A BitPackƒ instance allows no creativity and should always accurately reflect the bit representation of the data in HDL. You should always derive (6 , BitPack)Í unless you use a custom data representation, in which case you should use dj(. Custom encodings can be created with #Clash.Annotations.BitRepresentation and ,Clash.Annotations.BitRepresentation.Deriving.If the BitPack‘ instance does not accurately match the bit representation of the data in HDL, Clash designs will exhibit incorrect behavior in various places.÷Clash provides some generic functions on packable types in the prelude, such as indexing into packable stuctures (see Clash.Class.BitPack.BitIndex/) and bitwise reduction of packable data (see  Clash.Class.BitPack.BitReduction).´ clash-prelude Number of •)s needed to represents elements of type aCan be derived using pq: ‚import Clash.Prelude import GHC.Generics data MyProductType = MyProductType { a :: Int, b :: Bool } deriving (Generic, BitPack)µ clash-preludeConvert element of type a to a µpack (-5 :: Signed 6) 0b11_1011¶ clash-prelude Convert a µ to an element of type apack (-5 :: Signed 6) 0b11_1011let x = pack (-5 :: Signed 6)unpack x :: Unsigned 659pack (59 :: Unsigned 6) 0b11_1011¹ clash-preludePack both arguments to a µ and use ¬; to compare them. This is a more lentiant comparison than À, behaving more like (but not necessarily exactly the same as)  std_match in VHDL or casez in Verilog.Unlike þ, isLike is not symmetric. The reason for this is that a defined bit is said to be like an undefined bit, but not vice-versa:!isLike (12 :: Signed 8) undefinedTrue!isLike undefined (12 :: Signed 8)False8However, it is still trivially reflexive and transitive::set -XTemplateHaskelllet x1 = $(bLit "0010")let x2 = $(bLit "0.10")let x3 = $(bLit "0.1.") isLike x1 x1True isLike x1 x2True isLike x2 x3True isLike x1 x3TrueNB: Not synthesizableº clash-preludeÇCoerce a value from one type to another through its bit representation.pack (-5 :: Signed 6) 0b11_1011(bitCoerce (-5 :: Signed 6) :: Unsigned 659pack (59 :: Unsigned 6) 0b11_1011» clash-preludeÍMap a value by first coercing to another type through its bit representation.pack (-5 :: Signed 32))0b1111_1111_1111_1111_1111_1111_1111_1011ÃbitCoerceMap @(Vec 4 (BitVector 8)) (replace 1 0) (-5 :: Signed 32) -16711685pack (-16711685 :: Signed 32))0b1111_1111_0000_0000_1111_1111_1111_1011À clash-preludeZero-extend a ;ean value to a µ of the appropriate size.boolToBV True :: BitVector 6 0b00_0001boolToBV False :: BitVector 6 0b00_0000Á clash-preludeConvert a Bool to a Bit clash-preludeConvert a Bit to a BoolÒ clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples� is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version.± clash-preludeCurrent constructor clash-prelude Data to pack clash-prelude#(Constructor number, Packed fields)² clash-preludeConstruct with constructor n clash-preludeCurrent constructor clash-preludeBitVector containing fields clash-preludeUnpacked result®²±°¯³¶µ´·¸¹º»¼½¾¿ÀÁ³¶µ´·¸¹º»¼½¾¿®²±°¯ÀÁÂ((C) 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy#$&'(/02356789;<ÇÉÐÑÖ×Ùâìãqï clash-prelude#Efficient storage of memory content It holds n words of µ m.õ clash-prelude Convert a ï back to a listNB: Not synthesizable ïðôóòñõö÷øùúû ïðôóòñõö÷øùúû)Ð(C) 2013-2016, University of Twente, 2021, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789; Trustworthy&/02356789;>> slice d6 d4 (7 :: Unsigned 6)  BLANKLINE  interactiveù:... ¢@ Couldn't match type ˜@7 + i0™@ with ˜@6™@ arising from a use of ˜@slice™@ The type variable ˜@i0™@ is ambiguous ¢@ In the expression: slice d6 d4 (7 :: Unsigned 6) In an equation for ˜@it™@: it = slice d6 d4 (7 :: Unsigned 6)‚ clash-preludeSplit a value of a bit size m + n" into a tuple of values with size m and size n.pack (7 :: Unsigned 6) 0b00_01115split (7 :: Unsigned 6) :: (BitVector 2, BitVector 4) (0b00,0b0111)ƒ clash-prelude"Set the bit at the specified indexNB: Bit indices are  DESCENDING.pack (-5 :: Signed 6) 0b11_1011replaceBit 4 0 (-5 :: Signed 6)-21pack (-21 :: Signed 6) 0b10_1011replaceBit 5 0 (-5 :: Signed 6)27pack (27 :: Signed 6) 0b01_1011replaceBit 6 0 (-5 :: Signed 6)3*** Exception: replaceBit: 6 is out of range [5..0]...„ clash-preludeSet the bits between bit index m and bit index n.NB: Bit indices are  DESCENDING.pack (-5 :: Signed 6) 0b11_1011!setSlice d4 d3 0 (-5 :: Signed 6)-29pack (-29 :: Signed 6) 0b10_0011 # 145 "srcClashClassBitPack3BitIndex.hs" >>> setSlice d6 d5 0 (-5 :: Signed 6)  BLANKLINE  interactive†:... ¢@ Couldn't match type ˜@7 + i0™@ with ˜@6™@ arising from a use of ˜@setSlice™@ The type variable ˜@i0™@ is ambiguous ¢@ In the expression: setSlice d6 d5 0 (- 5 :: Signed 6) In an equation for ˜@it™@: it = setSlice d6 d5 0 (- 5 :: Signed 6)… clash-preludeGet the most significant bit.pack (-4 :: Signed 6) 0b11_1100msb (-4 :: Signed 6)1pack (4 :: Signed 6) 0b00_0100msb (4 :: Signed 6)0† clash-preludeGet the least significant bit.pack (-9 :: Signed 6) 0b11_0111lsb (-9 :: Signed 6)1pack (-8 :: Signed 6) 0b11_1000lsb (-8 :: Signed 6)0€�‚ƒ„…†€�‚ƒ„…†l€(C) 2013-2016, University of Twente 2016-2017, Myrtle Software Ltd 2021, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Safe&/02356789;<ÇÉÐÑÖ×ÙâìóF³´µ¶·¹º»ÀÁÂýþÿ€�‚ƒ„…†³´µ¶¹º»ÀÁ·€�‚ƒ„…†ýþÿ+(C) 2019, QBayLogicBSD2 (see the file LICENSE)-Christiaan Baaij None&/02356789;Unsafe"&/02356789:;<ÁÂÇÉÊÐÑÖ×Ùáâìý�˜ clash-prelude0Arbitrary-width unsigned integer represented by n bitsGiven n bits, an ˜ n number has a range of: [0 .. 2^n-1]NBÏ: The usual Haskell method of converting an integral numeric type to another, 6, is not well suited for Clash as it will go through @3 which is arbitrarily bounded in HDL. Instead use º and the ˆ class.NB: The + operators perform  wrap-aroundÁ on overflow. If you want saturation on overflow, check out the ï class. maxBound :: Unsigned 37minBound :: Unsigned 302read (show (maxBound :: Unsigned 3)) :: Unsigned 371 + 2 :: Unsigned 332 + 6 :: Unsigned 301 - 3 :: Unsigned 362 * 3 :: Unsigned 362 * 4 :: Unsigned 307(2 :: Unsigned 3) `mul` (4 :: Unsigned 3) :: Unsigned 687(2 :: Unsigned 3) `add` (6 :: Unsigned 3) :: Unsigned 48%satAdd SatSymmetric 2 6 :: Unsigned 37%satSub SatSymmetric 2 3 :: Unsigned 30Unsigned has the Îhttps://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i Unsignedtype role Unsigned nominal...ías it is not safe to coerce between different width Unsigned. To change the width, use the functions in the ˆ class.™ clash-preludeThe constructor, ™, and the field, š, are not synthesizable.Ð clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer º and the ˆ class.Ó clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer º and the ˆ class.Õ clash-preludeThe functions:  ,  ,  , and  , are not synthesizable.Ù clash-prelude None of the -" class' methods are synthesizable.,˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃ,˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃ,#(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<ÇÉÐÑÖ×Ùâìþ嘘/‚(C) 2013-2016, University of Twente, 2016 , Myrtle Software Ltd, 2021-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe"&/02356789:;<ÁÂÇÉÊÐÑÖ×ÙáâìUà clash-prelude.Arbitrary-width signed integer represented by n bits, including the sign bitÀUses standard 2-complements representation. Meaning that, given n bits, a à n number has a range of: [-(2^(n -1)) .. 2^(n -1)-1] for n > 0. When n = 0#, both the min and max bound are 0.NBÏ: The usual Haskell method of converting an integral numeric type to another, 6, is not well suited for Clash as it will go through @3 which is arbitrarily bounded in HDL. Instead use lm and the ˆ class.NB: The + operators perform  wrap-aroundÁ on overflow. If you want saturation on overflow, check out the ï class. maxBound :: Signed 33minBound :: Signed 3-4.read (show (minBound :: Signed 3)) :: Signed 3-41 + 2 :: Signed 332 + 3 :: Signed 3-3(-2) + (-3) :: Signed 332 * 3 :: Signed 462 * 4 :: Signed 4-81(2 :: Signed 3) `mul` (4 :: Signed 4) :: Signed 781(2 :: Signed 3) `add` (3 :: Signed 3) :: Signed 453(-2 :: Signed 3) `add` (-3 :: Signed 3) :: Signed 4-5#satAdd SatSymmetric 2 3 :: Signed 33)satAdd SatSymmetric (-2) (-3) :: Signed 3-3Signed has the Îhttps://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i Signedtype role Signed nominal...ëas it is not safe to coerce between different width Signed. To change the width, use the functions in the ˆ class.á clash-preludeThe constructor, á, and the field, â, are not synthesizable.™ clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer lm and the ˆ class.œ clash-prelude Operators do  wrap-around on overflowNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer lm and the ˆ class.ž clash-preludeThe functions:  ,  ,  , and  , are not synthesizable.¢ clash-prelude None of the -" class' methods are synthesizable.-àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ-àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ.#(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<ÇÉÐÑÖ×Ùâì ½àà0Ñ(C) 2013-2016, University of Twente, 2021, QBayLogic B.V.,BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy#&-/02356789; º rep int2 frac2° int1 frac1 int2 frac2 for: ¹ int1 frac1 -> ¹ int2 frac2¯ rep int1 frac1 int2 frac2 for: ¸ int1 frac1 -> ¸ int2 frac2Å clash-preludeConvert, at compile-time, a = constant to a º-point literalÕ. The conversion saturates on overflow, and uses truncation as its rounding method.So when you type: n = $$(Å pi) :: ¹ 4 4 The compiler sees: n = º (fromInteger 50) :: ¹ 4 4 ïUpon evaluation you see that the value is rounded / truncated in accordance to the fixed point representation:n3.125Further examples:sin 0.5 :: Double0.479425538604203 $$(fLit (sin 0.5)) :: SFixed 1 8 0.4765625atan 0.2 :: Double0.19739555984988078!$$(fLit (atan 0.2)) :: SFixed 1 8 0.1953125"$$(fLit (atan 0.2)) :: SFixed 1 200.19739532470703125Æ clash-preludeConvert, at run-time, a = to a º-point.NB: This function is not synthesizableCreating data-files creatingdatafilesÈAn example usage of this function is to convert a data file containing =às to a data file with ASCII-encoded binary numbers to be used by a synthesizable function like M– . For example, consider a file Data.txt containing: $1.2 2.0 3.0 4.0 -1.0 -2.0 -3.5 -4.0 4which we want to put in a ROM, interpreting them as 8.8Ø signed fixed point numbers. What we do is that we first create a conversion utility,  createRomFile , which uses Æ:createRomFile.hs: �module Main where import Clash.Prelude import Clash.Prelude.ROM.File import System.Environment import qualified Data.List as L createRomFile :: BitPack a => (Double -> a) -> FilePath -> FilePath -> IO () createRomFile convert fileR fileW = do f <- readFile fileR let ds :: [Double] ds = L.concat . (L.map . L.map) read . L.map words $ lines f fes = L.map convert ds writeFile fileW (M—Á Nothing fes) toSFixed8_8 :: Double -> SFixed 8 8 toSFixed8_8 = ÆÝ main :: IO () main = do [fileR,fileW] <- getArgs createRomFile toSFixed8_8 fileR fileW &We then compile this to an executable:  $ clash --make createRomFile.hs ,We can then use this utility to convert our Data.txt file which contains =s to a Data.binà file which will containing the desired ASCII-encoded binary data: ($ ./createRomFile "Data.txt" "Data.bin" Which results in a Data.bin file containing: ˆ0000000100110011 0000001000000000 0000001100000000 0000010000000000 1111111100000000 1111111000000000 1111110010000000 1111110000000000 We can then use this Data.bin file in for our ROM: ÆromF :: Unsigned 3 -> Unsigned 3 -> SFixed 8 8 romF rowAddr colAddr = ¶ $ M–) d8 "Data.bin" ((rowAddr * 4) + colAddr) "And see that it works as expected:  >>> romF 1 2 -3.5  >>> romF 0 0 1.19921875 Using Template HaskellÐFor those of us who like to live on the edge, another option is to convert our Data.txt at compile-time using  Ùhttps://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/template_haskell.htmlTemplate Haskell%. For this we first create a module CreateRomFileTH.hs: €module CreateRomFileTH (romDataFromFile) where import Clash.Prelude import Clash.Prelude.ROM.File import qualified Data.List as L import Language.Haskell.TH (ExpQ, litE, stringL) import Language.Haskell.TH.Syntax (qRunIO) createRomFile :: BitPack a => (Double -> a) -> FilePath -> FilePath -> IO () createRomFile convert fileR fileW = do f <- readFile fileR let ds :: [Double] ds = L.concat . (L.map . L.map) read . L.map words $ lines f fes = L.map convert ds writeFile fileW (M—Ö Nothing fes) romDataFromFile :: BitPack a => (Double -> a) -> String -> ExpQ romDataFromFile convert fileR = do let fileW = fileR L.++ ".bin" qRunIO (createRomFile convert fileR fileW) litE (stringL fileW) Instead of first converting Data.txt to Data.bin, we will now use the romDataFromFile function to convert Data.txtÀ to a new file in the proper format at compile-time of our new romF' function: ¡import Clash.Prelude import CreateRomFileTH romF' :: Unsigned 3 -> Unsigned 3 -> SFixed 8 8 romF' rowAddr colAddr = unpack $ asyncRomFile d8 $(romDataFromFile (fLitR :: Double -> SFixed 8 8) "Data.txt") -- Template Haskell splice ((rowAddr * 4) + colAddr) $And see that it works just like the romF function from earlier:  >>> romF' 1 2 -3.5  >>> romF' 0 0 1.19921875 Ç clash-preludeFixed point division7When used in a polymorphic setting, use the following  #constraintsynonymsConstraint synonyms" for less verbose type signatures:® rep int1 frac1 int2 frac2 for: º rep int1 frac1 -> º rep int2 frac2 -> º& rep (int1 + frac2 + 1) (int2 + frac1)­ rep int1 frac1 int2 frac2 for: ¹ int1 frac1 -> ¹ int2 frac2 -> ¹" (int1 + frac2 + 1) (int2 + frac1)¬ rep int1 frac1 int2 frac2 for: ¸ int1 frac1 -> ¸ int2 frac2 -> ¸" (int1 + frac2 + 1) (int2 + frac1)Ê clash-prelude None of the -" class' methods are synthesizable.Î clash-prelude7When used in a polymorphic setting, use the following  )Clash-Sized-Fixed.html#constraintsynonymsConstraint synonyms# for less verbose type signatures:· rep frac1 frac2 size1 size2 for: º¶ int1 frac1 int2 frac2 for: ¹µ int1 frac1 int2 frac2 for: ¸Ñ clash-preludeThese behave similar to >, = and C. ´/³ add/subtract 1. See the  Ìhttps://www.haskell.org/onlinereport/haskell2010/haskellch6.html#dx13-131001Haskell Report for full details..The rules set out there for instances of both $ and ## are also observed. In particular, ´ and ³Å result in a runtime error if the result cannot be represented. See ó and ô for other options.Ò clash-preludeàThe operators of this instance saturate on overflow, and use truncation as the rounding method.7When used in a polymorphic setting, use the following  )Clash-Sized-Fixed.html#constraintsynonymsConstraint synonyms# for less verbose type signatures:´ frac rep size for: º frac rep size³ int frac for: ¹ int frac² int frac for: ¸ int fracÔ clash-preludeàThe operators of this instance saturate on overflow, and use truncation as the rounding method.7When used in a polymorphic setting, use the following  )Clash-Sized-Fixed.html#constraintsynonymsConstraint synonyms# for less verbose type signatures:« frac rep size for: º frac rep sizeª int frac for: ¹ int frac© int frac for: ¸ int fracÕ clash-prelude3Instance functions do not saturate. Meaning that "`shiftL` 1 == ò ö 2'"½ clash-preludePosition of the virtual point clash-preludeThe à integer¿ clash-preludePosition of the virtual point clash-preludeThe ˜ integer©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇ¹½¾¸¿ÀÇÅÆº»¼Ä󶪰­²µ©¯¬´·«±®Á‚(C) 2013-2016, University of Twente, 2016-2019, Myrtle Software Ltd, 2021-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe"&/02356789:; Trustworthy&/02356789;<ÇÉÐÑÖ×ÙâìF�˜ clash-prelude!An alternative implementation of l˜ for the ·. data type; for when you know the size of the µ( and want to determine the size of the ·.That is, the type of l˜ is: unpack :: µ (Ž 2 n) -> · n ,And is useful when you know the size of the ·", and want to get a value from a µ that is large enough (CLog 2 n) enough to hold an · . Note that l˜ can fail at run-time when the value inside the µ is higher than 'n-1'.˜ on the other hand will never fail at run-time, because the µ argument determines the size.·â˜·˜â�(C) 2013-2016, University of Twente, 2017 , Myrtle Software Ltd 2022-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy%&'(/02356789;<>ÀÇÉÐÑÔÖ×ÙàâèìŠðà clash-preludeFixed size vectors.-Lists with their length encoded in their typeÃtor elements have an  ASCENDING, subscript starting from 0 and ending at Ù - 1.Ä clash-preludeı, applied to a binary operator, a starting value (typically the left-identity of the operator), and a vector, reduces the vector using the binary operator, from left to right: €foldl f z (x1 :> x2 :> ... :> xn :> Nil) == (...((z `f` x1) `f` x2) `f`...) `f` xn foldl f z Nil == z%foldl (/) 1 (5 :> 4 :> 3 :> 2 :> Nil)8.333333333333333e-3"Ä f z xs." corresponds to the following circuit layout: doc/foldl.svgNB: "Ä f z xs"Á produces a linear structure, which has a depth, or delay, of O(Ù xs). Use à if your binary operator f is associative, as "à f xs"/ produces a structure with a depth of O(log_2(Ù xs)).Å clash-preludeŲ, applied to a binary operator, a starting value (typically the right-identity of the operator), and a vector, reduces the vector using the binary operator, from right to left: €foldr f z (x1 :> ... :> xn1 :> xn :> Nil) == x1 `f` (... (xn1 `f` (xn `f` z))...) foldr r z Nil == z%foldr (/) 1 (5 :> 4 :> 3 :> 2 :> Nil)1.875"Å f z xs." corresponds to the following circuit layout: doc/foldr.svgNB: "Å f z xs"Á produces a linear structure, which has a depth, or delay, of O(Ù xs). Use à if your binary operator f is associative, as "à f xs"/ produces a structure with a depth of O(log_2(Ù xs)).Æ clash-prelude"Æ f xs%" is the vector obtained by applying f to each element of xs, i.e., Ímap f (x1 :> x2 :> ... :> xn :> Nil) == (f x1 :> f x2 :> ... :> f xn :> Nil)0and corresponds to the following circuit layout: doc/map.svgÇ clash-prelude Convert a µ to a à of ´s.let x = 6 :: BitVector 8x 0b0000_0110bv2v x+0 :> 0 :> 0 :> 0 :> 0 :> 1 :> 1 :> 0 :> Nil™ clash-preludeTo be used as the motive p for ÿ , when the f in "ÿ p f" is a variation on (�), e.g.: Ímap' :: forall n a b . KnownNat n => (a -> b) -> Vec n a -> Vec n b map' f = ÿ (Proxy @(™ b)) (_ x xs -> f x :> xs) œ clash-prelude'Add an element to the tail of a vector.(3:>4:>5:>Nil) :< 13 :> 4 :> 5 :> 1 :> Nillet x = (3:>4:>5:>Nil) :< 1:t xx :: Num a => Vec 4 aCan be used as a pattern:let f (_ :< y :< x) = y + x:t f&f :: Num a => Vec ((n + 1) + 1) a -> af (3:>4:>5:>6:>7:>Nil)13Also in conjunctions with (�):0let g (a :> b :> (_ :< y :< x)) = a + b + x + y:t g2g :: Num a => Vec ((((n + 1) + 1) + 1) + 1) a -> ag (1:>2:>3:>4:>5:>Nil)12� clash-prelude'Add an element to the head of a vector. 3:>4:>5:>Nil3 :> 4 :> 5 :> Nillet x = 3:>4:>5:>Nil:t xx :: Num a => Vec 3 aCan be used as a pattern:let f (x :> y :> _) = x + y:t f&f :: Num a => Vec ((n + 1) + 1) a -> af (3:>4:>5:>6:>7:>Nil)7Also in conjunctions with (œ):0let g (a :> b :> (_ :< y :< x)) = a + b + x + y:t g2g :: Num a => Vec ((((n + 1) + 1) + 1) + 1) a -> ag (1:>2:>3:>4:>5:>Nil)12Ÿ clash-preludeCreate a vector of one element singleton 55 :> Nil  clash-prelude%Extract the first element of a vectorhead (1:>2:>3:>Nil)1 # 423 "srcClashSized/Vector.hs" >>> head Nil  BLANKLINE  interactiveî:... ¢@ Couldn't match type ˜@1™@ with ˜@0™@ Expected type: Vec (0 + 1) a Actual type: Vec 0 a ¢@ In the first argument of ˜@head™@, namely ˜@Nil™@ In the expression: head Nil In an equation for ˜@it™@: it = head Nil¡ clash-prelude/Extract the elements after the head of a vectortail (1:>2:>3:>Nil) 2 :> 3 :> Nil # 458 "srcClashSized/Vector.hs" >>> tail Nil  BLANKLINE  interactiveî:... ¢@ Couldn't match type ˜@1™@ with ˜@0™@ Expected type: Vec (0 + 1) a Actual type: Vec 0 a ¢@ In the first argument of ˜@tail™@, namely ˜@Nil™@ In the expression: tail Nil In an equation for ˜@it™@: it = tail Nil¢ clash-prelude$Extract the last element of a vectorlast (1:>2:>3:>Nil)3 # 493 "srcClashSized/Vector.hs" >>> last Nil  BLANKLINE  interactiveî:... ¢@ Couldn't match type ˜@1™@ with ˜@0™@ Expected type: Vec (0 + 1) a Actual type: Vec 0 a ¢@ In the first argument of ˜@last™@, namely ˜@Nil™@ In the expression: last Nil In an equation for ˜@it™@: it = last Nil£ clash-prelude2:>3:>Nil) 1 :> 2 :> Nil # 529 "srcClashSized/Vector.hs" >>> init Nil  BLANKLINE  interactiveî:... ¢@ Couldn't match type ˜@1™@ with ˜@0™@ Expected type: Vec (0 + 1) a Actual type: Vec 0 a ¢@ In the first argument of ˜@init™@, namely ˜@Nil™@ In the expression: init Nil In an equation for ˜@it™@: it = init Nil¤ clash-preludeïShift in elements to the head of a vector, bumping out elements at the tail. The result is a tuple containing:The new vectorThe shifted out elements7shiftInAt0 (1 :> 2 :> 3 :> 4 :> Nil) ((-1) :> 0 :> Nil)((-1 :> 0 :> 1 :> 2 :> Nil,3 :> 4 :> Nil)(shiftInAt0 (1 :> Nil) ((-1) :> 0 :> Nil)(-1 :> Nil,0 :> 1 :> Nil)¥ clash-preludeîShift in element to the tail of a vector, bumping out elements at the head. The result is a tuple containing:The new vectorThe shifted out elements4shiftInAtN (1 :> 2 :> 3 :> 4 :> Nil) (5 :> 6 :> Nil)'(3 :> 4 :> 5 :> 6 :> Nil,1 :> 2 :> Nil)%shiftInAtN (1 :> Nil) (2 :> 3 :> Nil)(3 :> Nil,1 :> 2 :> Nil)¦ clash-preludeÎAdd an element to the head of a vector, and extract all but the last element.1 +>> (3:>4:>5:>Nil)1 :> 3 :> 4 :> Nil 1 +>> NilNil§ clash-preludeÏAdd an element to the tail of a vector, and extract all but the first element.(3:>4:>5:>Nil) <<+ 14 :> 5 :> 1 :> Nil Nil <<+ 1Nil¨ clash-preludeShift mà elements out from the head of a vector, filling up the tail with �* values. The result is a tuple containing:The new vectorThe shifted out valuesÂshiftOutFrom0 d2 ((1 :> 2 :> 3 :> 4 :> 5 :> Nil) :: Vec 5 Integer),(3 :> 4 :> 5 :> 0 :> 0 :> Nil,1 :> 2 :> Nil)© clash-preludeShift mà elements out from the tail of a vector, filling up the head with �* values. The result is a tuple containing:The new vectorThe shifted out valuesÂshiftOutFromN d2 ((1 :> 2 :> 3 :> 4 :> 5 :> Nil) :: Vec 5 Integer),(0 :> 0 :> 1 :> 2 :> 3 :> Nil,4 :> 5 :> Nil)ª clash-preludeAppend two vectors.(1:>2:>3:>Nil) ++ (7:>8:>Nil)1 :> 2 :> 3 :> 7 :> 8 :> Nil« clash-prelude3Split a vector into two vectors at the given point.-splitAt (SNat :: SNat 3) (1:>2:>3:>7:>8:>Nil)"(1 :> 2 :> 3 :> Nil,7 :> 8 :> Nil)splitAt d3 (1:>2:>3:>7:>8:>Nil)"(1 :> 2 :> 3 :> Nil,7 :> 8 :> Nil)¬ clash-preludeÚSplit a vector into two vectors where the length of the two is determined by the context.7splitAtI (1:>2:>3:>7:>8:>Nil) :: (Vec 2 Int, Vec 3 Int)"(1 :> 2 :> Nil,3 :> 7 :> 8 :> Nil)­ clash-prelude Concatenate a vector of vectors.×concat ((1:>2:>3:>Nil) :> (4:>5:>6:>Nil) :> (7:>8:>9:>Nil) :> (10:>11:>12:>Nil) :> Nil)Â1 :> 2 :> 3 :> 4 :> 5 :> 6 :> 7 :> 8 :> 9 :> 10 :> 11 :> 12 :> Nil® clash-preludeØMap a function over all the elements of a vector and concatentate the resulting vectors.'concatMap (replicate d3) (1:>2:>3:>Nil)01 :> 1 :> 1 :> 2 :> 2 :> 2 :> 3 :> 3 :> 3 :> Nil¯ clash-preludeÈSplit a vector of (n * m) elements into a vector of "vectors of length m", where the length m is given.8unconcat d4 (1:>2:>3:>4:>5:>6:>7:>8:>9:>10:>11:>12:>Nil)Ý(1 :> 2 :> 3 :> 4 :> Nil) :> (5 :> 6 :> 7 :> 8 :> Nil) :> (9 :> 10 :> 11 :> 12 :> Nil) :> Nil° clash-preludeSplit a vector of (n * m)/ elements into a vector of "vectors of length m", where the length m is determined by the context.ËunconcatI (1:>2:>3:>4:>5:>6:>7:>8:>9:>10:>11:>12:>Nil) :: Vec 2 (Vec 6 Int)Ô(1 :> 2 :> 3 :> 4 :> 5 :> 6 :> Nil) :> (7 :> 8 :> 9 :> 10 :> 11 :> 12 :> Nil) :> Nil± clash-prelude4Merge two vectors, alternating their elements, i.e.,9merge (1 :> 2 :> 3 :> 4 :> Nil) (5 :> 6 :> 7 :> 8 :> Nil)+1 :> 5 :> 2 :> 6 :> 3 :> 7 :> 4 :> 8 :> Nil² clash-prelude*The elements in a vector in reverse order.reverse (1:>2:>3:>4:>Nil)4 :> 3 :> 2 :> 1 :> Nil³ clash-prelude 2 :> 2 :> 2 :> Nil)5imap (+) (2 :> 2 :> 2 :> 2 :> Nil) :: Vec 4 (Index 4)"imap (+) (2 :> 2 :> 2 :> 2 :> Nil)Ð2 :> 3 :> *** Exception: X: Clash.Sized.Index: result 4 is out of bounds: [0..3]...×imap (\i a -> extend (bitCoerce i) + a) (2 :> 2 :> 2 :> 2 :> Nil) :: Vec 4 (Unsigned 8)2 :> 3 :> 4 :> 5 :> Nil"³ f xs." corresponds to the following circuit layout: doc/imap.svg´ clash-preludeÇZip two vectors with a functions that also takes the elements' indices.>izipWith (\i a b -> i + a + b) (2 :> 2 :> Nil) (3 :> 3:> Nil)Æ*** Exception: X: Clash.Sized.Index: result 3 is out of bounds: [0..1]...çizipWith (\i a b -> extend (bitCoerce i) + a + b) (2 :> 2 :> Nil) (3 :> 3 :> Nil) :: Vec 2 (Unsigned 8) 5 :> 6 :> Nil"³ f xs." corresponds to the following circuit layout: doc/izipWith.svgNB: ´ is strict in its second argument, and lazy! in its third. This matters when ´% is used in a recursive setting. See þ for more information.µ clash-prelude;Right fold (function applied to each element and its index)Òlet findLeftmost x xs = ifoldr (\i a b -> if a == x then Just i else b) Nothing xs)findLeftmost 3 (1:>3:>2:>4:>3:>5:>6:>Nil)Just 1)findLeftmost 8 (1:>3:>2:>4:>3:>5:>6:>Nil)Nothing"µ f z xs." corresponds to the following circuit layout: doc/ifoldr.svg¶ clash-prelude:Left fold (function applied to each element and its index)Ólet findRightmost x xs = ifoldl (\a i b -> if b == x then Just i else a) Nothing xs*findRightmost 3 (1:>3:>2:>4:>3:>5:>6:>Nil)Just 4*findRightmost 8 (1:>3:>2:>4:>3:>5:>6:>Nil)Nothing"¶ f z xs." corresponds to the following circuit layout: doc/ifoldl.svg· clash-preludeGenerate a vector of indices. indices d40 :> 1 :> 2 :> 3 :> Nil¸ clash-preludeÛGenerate a vector of indices, where the length of the vector is determined by the context.indicesI :: Vec 4 (Index 4)0 :> 1 :> 2 :> 3 :> Nil¹ clash-prelude"¹ p xs" returns the index of the first element of xs satisfying the predicate p, or J if there is no such element.*findIndex (> 3) (1:>3:>2:>4:>3:>5:>6:>Nil)Just 3*findIndex (> 8) (1:>3:>2:>4:>3:>5:>6:>Nil)Nothingº clash-prelude"º a xs" returns the index of the first element which is equal (by ) to the query element a, or J if there is no such element.&elemIndex 3 (1:>3:>2:>4:>3:>5:>6:>Nil)Just 1&elemIndex 8 (1:>3:>2:>4:>3:>5:>6:>Nil)Nothing» clash-prelude» generalizes Ìê by zipping with the function given as the first argument, instead of a tupling function. For example, "» (+)Ä" applied to two vectors produces the vector of corresponding sums. õzipWith f (x1 :> x2 :> ... xn :> Nil) (y1 :> y2 :> ... :> yn :> Nil) == (f x1 y1 :> f x2 y2 :> ... :> f xn yn :> Nil)"» f xs ys." corresponds to the following circuit layout: doc/zipWith.svgNB: » is strict in its second argument, and lazy" in its third. This matters when »& is used in a recursive setting. See þ for more information.¼ clash-prelude¼ generalizes ÍÚ by zipping with the function given as the first argument, instead of a tupling function. žzipWith3 f (x1 :> x2 :> ... xn :> Nil) (y1 :> y2 :> ... :> yn :> Nil) (z1 :> z2 :> ... :> zn :> Nil) == (f x1 y1 z1 :> f x2 y2 z2 :> ... :> f xn yn zn :> Nil)"¼  f xs ys zs." corresponds to the following circuit layout: doc/zipWith3.svgNB: ¼ is strict in its second argument, and lazy- in its third and fourth. This matters when ¼& is used in a recursive setting. See þ for more information.Á clash-preludeÁ is a variant of ÅÕ that has no starting value argument, and thus must be applied to non-empty vectors. Ífoldr1 f (x1 :> ... :> xn2 :> xn1 :> xn :> Nil) == x1 `f` (... (xn2 `f` (xn1 `f` xn))...) foldr1 f (x1 :> Nil) == x1 foldr1 f Nil == TYPE ERROR)foldr1 (/) (5 :> 4 :> 3 :> 2 :> 1 :> Nil)1.875"Á f xs." corresponds to the following circuit layout: doc/foldr1.svgNB: "Á f z xs"Á produces a linear structure, which has a depth, or delay, of O(Ù xs). Use à if your binary operator f is associative, as "à f xs"/ produces a structure with a depth of O(log_2(Ù xs)). clash-prelude is a variant of ÄÕ that has no starting value argument, and thus must be applied to non-empty vectors. Èfoldl1 f (x1 :> x2 :> x3 :> ... :> xn :> Nil) == (...((x1 `f` x2) `f` x3) `f`...) `f` xn foldl1 f (x1 :> Nil) == x1 foldl1 f Nil == TYPE ERROR)foldl1 (/) (1 :> 5 :> 4 :> 3 :> 2 :> Nil)8.333333333333333e-3" f xs." corresponds to the following circuit layout: doc/foldl1.svgNB: " f z xs"Á produces a linear structure, which has a depth, or delay, of O(Ù xs). Use à if your binary operator f is associative, as "à f xs"/ produces a structure with a depth of O(log_2(Ù xs)).à clash-preludeà is a variant of Á and §, but instead of reducing from right to left, or left to right, it reduces a vector using a tree-like structure. The depth, or delay, of the structure produced by "à f xs ", is hence O(log_2(Ù xs)) , and not O(Ù xs).NB: The binary operator "f" in "à f xs" must be associative. Îfold f (x1 :> x2 :> ... :> xn1 :> xn :> Nil) == ((x1 `f` x2) `f` ...) `f` (... `f` (xn1 `f` xn)) fold f (x1 :> Nil) == x1 fold f Nil == TYPE ERROR'fold (+) (5 :> 4 :> 3 :> 2 :> 1 :> Nil)15"à f xs." corresponds to the following circuit layout: doc/fold.svgÄ clash-preludeÄ is similar to ÄÃ, but returns a vector of successive reduced values from the left: Úscanl f z (x1 :> x2 :> ... :> Nil) == z :> (z `f` x1) :> ((z `f` x1) `f` x2) :> ... :> Nil%scanl (+) 0 (5 :> 4 :> 3 :> 2 :> Nil)0 :> 5 :> 9 :> 12 :> 14 :> Nil"Ä f z xs." corresponds to the following circuit layout: doc/scanl.svgNB: #last (scanl f z xs) == foldl f z xsßFor a different trade-off between circuit size and logic depth for associative operators, see Clash.Sized.RTree#scansÅ clash-preludeÄ with no seed value$scanl1 (-) (1 :> 2 :> 3 :> 4 :> Nil)1 :> -1 :> -4 :> -8 :> NilÆ clash-preludeÈ with no seed value$scanr1 (-) (1 :> 2 :> 3 :> 4 :> Nil)-2 :> 3 :> -1 :> 4 :> NilÇ clash-preludeÇ is a variant of Ä# where the first result is dropped: Ùpostscanl f z (x1 :> x2 :> ... :> Nil) == (z `f` x1) :> ((z `f` x1) `f` x2) :> ... :> Nil)postscanl (+) 0 (5 :> 4 :> 3 :> 2 :> Nil)5 :> 9 :> 12 :> 14 :> Nil"Ç f z xs." corresponds to the following circuit layout: doc/sscanl.svgÈ clash-preludeÈ is similar to ÅÄ, but returns a vector of successive reduced values from the right: Üscanr f z (... :> xn1 :> xn :> Nil) == ... :> (xn1 `f` (xn `f` z)) :> (xn `f` z) :> z :> Nil%scanr (+) 0 (5 :> 4 :> 3 :> 2 :> Nil)14 :> 9 :> 5 :> 2 :> 0 :> Nil"È f z xs." corresponds to the following circuit layout: doc/scanr.svgNB: #head (scanr f z xs) == foldr f z xsßFor a different trade-off between circuit size and logic depth for associative operators, see Clash.Sized.RTree#scansÉ clash-preludeÉ is a variant of È' that where the last result is dropped: Ûpostscanr f z (... :> xn1 :> xn :> Nil) == ... :> (xn1 `f` (xn `f` z)) :> (xn `f` z) :> Nil)postscanr (+) 0 (5 :> 4 :> 3 :> 2 :> Nil)14 :> 9 :> 5 :> 2 :> Nil"É f z xs." corresponds to the following circuit layout: doc/sscanr.svgÊ clash-preludeThe Ê( function behaves like a combination of Æ and Ä»; it applies a function to each element of a vector, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new vector.ÃmapAccumL (\acc x -> (acc + x,acc + 1)) 0 (1 :> 2 :> 3 :> 4 :> Nil)(10,1 :> 2 :> 4 :> 7 :> Nil)"Ê f acc xs." corresponds to the following circuit layout: doc/mapAccumL.svgË clash-preludeThe Ë( function behaves like a combination of Æ and Å»; it applies a function to each element of a vector, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new vector.ÃmapAccumR (\acc x -> (acc + x,acc + 1)) 0 (1 :> 2 :> 3 :> 4 :> Nil)(10,10 :> 8 :> 5 :> 1 :> Nil)"Ë f acc xs." corresponds to the following circuit layout: doc/mapAccumR.svgÌ clash-preludeÌ? takes two vectors and returns a vector of corresponding pairs.'zip (1:>2:>3:>4:>Nil) (4:>3:>2:>1:>Nil)'(1,4) :> (2,3) :> (3,2) :> (4,1) :> NilÍ clash-preludeÍÄ takes three vectors and returns a vector of corresponding triplets.:zip3 (1:>2:>3:>4:>Nil) (4:>3:>2:>1:>Nil) (5:>6:>7:>8:>Nil)/(1,4,5) :> (2,3,6) :> (3,2,7) :> (4,1,8) :> NilÎ clash-preludeÎÄ takes four vectors and returns a list of quadruples, analogous to Ì.Ï clash-preludeÏÅ takes five vectors and returns a list of five-tuples, analogous to Ì.Ð clash-preludeÐà takes six vectors and returns a list of six-tuples, analogous to Ì.Ñ clash-preludeÑÇ takes seven vectors and returns a list of seven-tuples, analogous to Ì.Ò clash-preludeÒã transforms a vector of pairs into a vector of first components and a vector of second components.'unzip ((1,4):>(2,3):>(3,2):>(4,1):>Nil)1(1 :> 2 :> 3 :> 4 :> Nil,4 :> 3 :> 2 :> 1 :> Nil)Ó clash-preludeÓ… transforms a vector of triplets into a vector of first components, a vector of second components, and a vector of third components.0unzip3 ((1,4,5):>(2,3,6):>(3,2,7):>(4,1,8):>Nil)É(1 :> 2 :> 3 :> 4 :> Nil,4 :> 3 :> 2 :> 1 :> Nil,5 :> 6 :> 7 :> 8 :> Nil)Ô clash-preludeÔÆ takes a vector of quadruples and returns four vectors, analogous to Ò.Õ clash-preludeÕÇ takes a vector of five-tuples and returns five vectors, analogous to Ò.Ö clash-preludeÖÅ takes a vector of six-tuples and returns six vectors, analogous to Ò.× clash-prelude×É takes a vector of seven-tuples and returns seven vectors, analogous to Ò.Ø clash-prelude"xs Ø n" returns the n'th element of xs.NB: Vector elements have an  ASCENDING* subscript starting from 0 and ending at Ù - 1.(1:>2:>3:>4:>5:>Nil) !! 459(1:>2:>3:>4:>5:>Nil) !! (length (1:>2:>3:>4:>5:>Nil) - 1)5(1:>2:>3:>4:>5:>Nil) !! 12(1:>2:>3:>4:>5:>Nil) !! 14Ï*** Exception: Clash.Sized.Vector.(!!): index 14 is larger than maximum index 4...Ù clash-preludeThe length of a à tor as an ? value.length (6 :> 7 :> 8 :> Nil)3Ú clash-prelude"Ú n a xs" returns the vector xs where the n'th element is replaced by a.NB: Vector elements have an  ASCENDING* subscript starting from 0 and ending at Ù - 1. replace 3 7 (1:>2:>3:>4:>5:>Nil)1 :> 2 :> 3 :> 7 :> 5 :> Nil replace 0 7 (1:>2:>3:>4:>5:>Nil)7 :> 2 :> 3 :> 4 :> 5 :> Nil replace 9 7 (1:>2:>3:>4:>5:>Nil)ê1 :> 2 :> 3 :> 4 :> 5 :> *** Exception: Clash.Sized.Vector.replace: index 9 is larger than maximum index 4...Û clash-prelude"Û n xs" returns the n-length prefix of xs.*take (SNat :: SNat 3) (1:>2:>3:>4:>5:>Nil)1 :> 2 :> 3 :> Nil*take d3 (1:>2:>3:>4:>5:>Nil)1 :> 2 :> 3 :> Nil!take d0 (1:>2:>Nil)Nil # 1518 "srcClash7Sized/Vector.hs" >>> take d4 (1:>2:>Nil)  BLANKLINE  interactiveÏ:... ¢@ Couldn't match type ˜@4 + n0™@ with ˜@2™@ Expected type: Vec (4 + n0) a Actual type: Vec (1 + 1) a The type variable ˜@n0™@ is ambiguous ¢@ In the second argument of ˜@take™@, namely ˜@(1 :> 2 :> Nil)™@ In the expression: take d4 (1 :> 2 :> Nil) In an equation for ˜@it™@: it = take d4 (1 :> 2 :> Nil)Ü clash-prelude"Ü xs" returns the prefix of xs as demanded by the context.'takeI (1:>2:>3:>4:>5:>Nil) :: Vec 2 Int 1 :> 2 :> NilÝ clash-prelude"Ý n xs" returns the suffix of xs after the first n elements.*drop (SNat :: SNat 3) (1:>2:>3:>4:>5:>Nil) 4 :> 5 :> Nil*drop d3 (1:>2:>3:>4:>5:>Nil) 4 :> 5 :> Nil!drop d0 (1:>2:>Nil) 1 :> 2 :> Nil # 1562 "srcClash7Sized/Vector.hs" >>> drop d4 (1:>2:>Nil)  BLANKLINE  interactiveÍ:...: error:... ¢@ Couldn't match...type ˜@4 + n0... The type variable ˜@n0™@ is ambiguous ¢@ In the first argument of ˜@print™@, namely ˜@it™@ In a stmt of an interactive GHCi command: print itÞ clash-prelude"Þ xs" returns the suffix of xs as demanded by the context.'dropI (1:>2:>3:>4:>5:>Nil) :: Vec 2 Int 4 :> 5 :> Nilß clash-prelude"ß n xs " returns n'th element of xsNB: Vector elements have an  ASCENDING* subscript starting from 0 and ending at Ù - 1.(at (SNat :: SNat 1) (1:>2:>3:>4:>5:>Nil)2(at d1 (1:>2:>3:>4:>5:>Nil)2à clash-prelude"à f s n xs " selects n elements with step-size s and offset f from xs.×select (SNat :: SNat 1) (SNat :: SNat 2) (SNat :: SNat 3) (1:>2:>3:>4:>5:>6:>7:>8:>Nil)2 :> 4 :> 6 :> Nil-select d1 d2 d3 (1:>2:>3:>4:>5:>6:>7:>8:>Nil)2 :> 4 :> 6 :> Nilá clash-prelude"á f s xsÆ" selects as many elements as demanded by the context with step-size s and offset f from xs.8selectI d1 d2 (1:>2:>3:>4:>5:>6:>7:>8:>Nil) :: Vec 2 Int 2 :> 4 :> Nilâ clash-prelude"â n a" returns a vector that has n copies of a.replicate (SNat :: SNat 3) 66 :> 6 :> 6 :> Nilreplicate d3 66 :> 6 :> 6 :> Nilã clash-prelude"ã a*" creates a vector with as many copies of a as demanded by the context.repeat 6 :: Vec 5 Int6 :> 6 :> 6 :> 6 :> 6 :> Nilä clash-prelude"ä n f x!" returns a vector starting with x followed by n repeated applications of f to x. —iterate (SNat :: SNat 4) f x == (x :> f x :> f (f x) :> f (f (f x)) :> Nil) iterate d4 f x == (x :> f x :> f (f x) :> f (f (f x)) :> Nil)iterate d4 (+1) 11 :> 2 :> 3 :> 4 :> Nil"ä n f z." corresponds to the following circuit layout: doc/iterate.svgå clash-prelude"å f x!" returns a vector starting with x followed by n repeated applications of f to x, where n is determined by the context. 7iterateI f x :: Vec 3 a == (x :> f x :> f (f x) :> Nil)iterateI (+1) 1 :: Vec 3 Int1 :> 2 :> 3 :> Nil"å f z." corresponds to the following circuit layout: doc/iterate.svgæ clash-prelude"æ n f s" builds a vector of length n from a seed value s, where every element a# is created by successive calls of f on s . Unlike ™š from  Data.List the generating function fÑ cannot dictate the length of the resulting vector, it must be statically known.a simple use of æ:unfoldr d10 (\s -> (s,s-1)) 10610 :> 9 :> 8 :> 7 :> 6 :> 5 :> 4 :> 3 :> 2 :> 1 :> Nilç clash-prelude"ç f s$" builds a vector from a seed value s, where every element a# is created by successive calls of f on sÁ; the length of the vector is inferred from the context. Unlike ™š from  Data.List the generating function fÒ cannot dictate the length of the resulting vector, it must be statically known.a simple use of ç:)unfoldrI (\s -> (s,s-1)) 10 :: Vec 10 Int610 :> 9 :> 8 :> 7 :> 6 :> 5 :> 4 :> 3 :> 2 :> 1 :> Nilè clash-prelude"è n f x" returns a vector with n repeated applications of f to x. µgenerate (SNat :: SNat 4) f x == (f x :> f (f x) :> f (f (f x)) :> f (f (f (f x))) :> Nil) generate d4 f x == (f x :> f (f x) :> f (f (f x)) :> f (f (f (f x))) :> Nil)generate d4 (+1) 12 :> 3 :> 4 :> 5 :> Nil"è n f z." corresponds to the following circuit layout: doc/generate.svgé clash-prelude"é f x" returns a vector with n repeated applications of f to x, where n is determined by the context. ÂgenerateI f x :: Vec 3 a == (f x :> f (f x) :> f (f (f x)) :> Nil)generateI (+1) 1 :: Vec 3 Int2 :> 3 :> 4 :> Nil"é f z." corresponds to the following circuit layout: doc/generate.svgê clash-prelude5Transpose a matrix: go from row-major to column-major4let xss = (1:>2:>Nil):>(3:>4:>Nil):>(5:>6:>Nil):>Nilxss<(1 :> 2 :> Nil) :> (3 :> 4 :> Nil) :> (5 :> 6 :> Nil) :> Nil transpose xss3(1 :> 3 :> 5 :> Nil) :> (2 :> 4 :> 6 :> Nil) :> Nilë clash-prelude"1-dimensional stencil computations"ë stX f xs ", where xs has stX + n, elements, applies the stencil computation f on: n + 1$ overlapping (1D) windows of length stX, drawn from xs. The resulting vector has n + 1 elements. let xs = (1:>2:>3:>4:>5:>6:>Nil):t xsxs :: Num a => Vec 6 a:t stencil1d d2 sum xs'stencil1d d2 sum xs :: Num b => Vec 5 bstencil1d d2 sum xs3 :> 5 :> 7 :> 9 :> 11 :> Nilì clash-prelude"2-dimensional stencil computations"ì  stY stX f xss ", where xss is a matrix of stY + m rows of stX + n+ elements, applies the stencil computation f on: (m + 1) * (n + 1) overlapping (2D) windows of stY rows of stX elements, drawn from xss. The result matrix has m + 1 rows of n + 1 elements.âlet xss = ((1:>2:>3:>4:>Nil):>(5:>6:>7:>8:>Nil):>(9:>10:>11:>12:>Nil):>(13:>14:>15:>16:>Nil):>Nil):t xssxss :: Num a => Vec 4 (Vec 4 a)&:t stencil2d d2 d2 (sum . map sum) xss?stencil2d d2 d2 (sum . map sum) xss :: Num b => Vec 3 (Vec 3 b)#stencil2d d2 d2 (sum . map sum) xssÔ(14 :> 18 :> 22 :> Nil) :> (30 :> 34 :> 38 :> Nil) :> (46 :> 50 :> 54 :> Nil) :> Nilí clash-prelude"í stX xs", where the vector xs has stX + n elements, returns a vector of n + 1 overlapping (1D) windows of xs of length stX. let xs = (1:>2:>3:>4:>5:>6:>Nil):t xsxs :: Num a => Vec 6 a:t windows1d d2 xs+windows1d d2 xs :: Num a => Vec 5 (Vec 2 a)windows1d d2 xsâ(1 :> 2 :> Nil) :> (2 :> 3 :> Nil) :> (3 :> 4 :> Nil) :> (4 :> 5 :> Nil) :> (5 :> 6 :> Nil) :> Nilî clash-prelude"î  stY stX xss", where matrix xss has stY + m rows of stX + n, returns a matrix of m+1 rows of n+1Ð elements. The elements of this new matrix are the overlapping (2D) windows of xss, where every window has stY rows of stX elements.âlet xss = ((1:>2:>3:>4:>Nil):>(5:>6:>7:>8:>Nil):>(9:>10:>11:>12:>Nil):>(13:>14:>15:>16:>Nil):>Nil):t xssxss :: Num a => Vec 4 (Vec 4 a):t windows2d d2 d2 xss?windows2d d2 d2 xss :: Num a => Vec 3 (Vec 3 (Vec 2 (Vec 2 a)))windows2d d2 d2 xssÕ(((1 :> 2 :> Nil) :> (5 :> 6 :> Nil) :> Nil) :> ((2 :> 3 :> Nil) :> (6 :> 7 :> Nil) :> Nil) :> ((3 :> 4 :> Nil) :> (7 :> 8 :> Nil) :> Nil) :> Nil) :> (((5 :> 6 :> Nil) :> (9 :> 10 :> Nil) :> Nil) :> ((6 :> 7 :> Nil) :> (10 :> 11 :> Nil) :> Nil) :> ((7 :> 8 :> Nil) :> (11 :> 12 :> Nil) :> Nil) :> Nil) :> (((9 :> 10 :> Nil) :> (13 :> 14 :> Nil) :> Nil) :> ((10 :> 11 :> Nil) :> (14 :> 15 :> Nil) :> Nil) :> ((11 :> 12 :> Nil) :> (15 :> 16 :> Nil) :> Nil) :> Nil) :> Nilï clash-prelude3Forward permutation specified by an index mapping, ix;. The result vector is initialized by the given defaults, def�, and an further values that are permuted into the result are added to the current value using the given combination function, f.!The combination function must be  associative and  commutative.ð clash-prelude5Backwards permutation specified by an index mapping, isÍ, from the destination vector specifying which element of the source vector xs to read."ð xs is" is equivalent to "Æ (xs Ø) is". For example:*let input = 1:>9:>6:>4:>4:>2:>0:>1:>2:>Nil!let from = 1:>3:>7:>2:>5:>3:>Nilbackpermute input from!9 :> 4 :> 1 :> 6 :> 2 :> 4 :> Nilñ clash-prelude&Copy elements from the source vector, xs;, to the destination vector according to an index mapping is/. This is a forward permute operation where a toŠ vector encodes an input to output index mapping. Output elements for indices that are not mapped assume the value in the default vector def. For example:+let defVec = 0:>0:>0:>0:>0:>0:>0:>0:>0:>Nillet to = 1:>3:>7:>2:>5:>8:>Nil$let input = 1:>9:>6:>4:>4:>2:>5:>Nilscatter defVec to input00 :> 1 :> 4 :> 9 :> 0 :> 4 :> 0 :> 6 :> 2 :> NilNBß: If the same index appears in the index mapping more than once, the latest mapping is chosen.ò clash-prelude5Backwards permutation specified by an index mapping, isÍ, from the destination vector specifying which element of the source vector xs to read."ò xs is" is equivalent to "Æ (xs Ø) is". For example:*let input = 1:>9:>6:>4:>4:>2:>0:>1:>2:>Nil!let from = 1:>3:>7:>2:>5:>3:>Nilgather input from!9 :> 4 :> 1 :> 6 :> 2 :> 4 :> Niló clash-prelude"ó d xs" creates a vector: È 9let xs = 1 :> 2 :> 3 :> 4 :> 5 :> 6 :> 7 :> 8 :> 9 :> Nilinterleave d3 xs01 :> 4 :> 7 :> 2 :> 5 :> 8 :> 3 :> 6 :> 9 :> Nilô clash-prelude Dynamically rotate a Ãtor to the left: let xs = 1 :> 2 :> 3 :> 4 :> NilrotateLeft xs 12 :> 3 :> 4 :> 1 :> NilrotateLeft xs 23 :> 4 :> 1 :> 2 :> NilrotateLeft xs (-1)4 :> 1 :> 2 :> 3 :> NilNB: Use ö! if you want to rotate left by a static amount.õ clash-prelude Dynamically rotate a Ãtor to the right: let xs = 1 :> 2 :> 3 :> 4 :> NilrotateRight xs 14 :> 1 :> 2 :> 3 :> NilrotateRight xs 23 :> 4 :> 1 :> 2 :> NilrotateRight xs (-1)2 :> 3 :> 4 :> 1 :> NilNB: Use ÷" if you want to rotate right by a static amount.ö clash-prelude Statically rotate a Ãtor to the left: let xs = 1 :> 2 :> 3 :> 4 :> NilrotateLeftS xs d12 :> 3 :> 4 :> 1 :> NilNB: Use ô! if you want to rotate left by a dynamic amount.÷ clash-prelude Statically rotate a Ãtor to the right: let xs = 1 :> 2 :> 3 :> 4 :> NilrotateRightS xs d14 :> 1 :> 2 :> 3 :> NilNB: Use õ" if you want to rotate right by a dynamic amount.ø clash-preludeConvert a vector to a list.toList (1:>2:>3:>Nil)[1,2,3]NB$: This function is not synthesizableù clash-prelude„Convert a list to a vector. This function returns Nothing if the size of the list is not equal to the size of the resulting vector.-Vec.fromList [1,2,3,4,5] :: Maybe (Vec 5 Int)#Just (1 :> 2 :> 3 :> 4 :> 5 :> Nil)-Vec.fromList [1,2,3,4,5] :: Maybe (Vec 3 Int)Nothing.Vec.fromList [1,2,3,4,5] :: Maybe (Vec 10 Int)NothingNB: Use û if you want to make a statically known vectorNB$: This function is not synthesizableú clash-prelude§Convert a list to a vector. This function always returns a vector of the desired length, by either truncating the list or padding the vector with undefined elements.+Vec.unsafeFromList [1,2,3,4,5] :: Vec 5 Int1 :> 2 :> 3 :> 4 :> 5 :> Nil+Vec.unsafeFromList [1,2,3,4,5] :: Vec 3 Int1 :> 2 :> 3 :> Nil,Vec.unsafeFromList [1,2,3,4,5] :: Vec 10 Intâ1 :> 2 :> 3 :> 4 :> 5 :> *** Exception: Clash.Sized.Vector.unsafeFromList: vector larger than list...NB: Use û if you want to make a statically known vectorNB$: This function is not synthesizableû clash-prelude,Create a vector literal from a list literal. Ð$(listToVecTH [1::Signed 8,2,3,4,5]) == (8:>2:>3:>4:>5:>Nil) :: Vec 5 (Signed 8)[1 :: Signed 8,2,3,4,5] [1,2,3,4,5]$$(listToVecTH [1::Signed 8,2,3,4,5])1 :> 2 :> 3 :> 4 :> 5 :> Nilü clash-preludeà tor as a � for ÷ý clash-prelude Length of a à tor as an ¨ valueþ clash-preludeÒWhat you should use when your vector functions are too strict in their arguments.doctests setup5let compareSwapL a b = if a < b then (a,b) else (b,a):{Õlet sortVL :: (Ord a, KnownNat (n + 1)) => Vec ((n + 1) + 1) a -> Vec ((n + 1) + 1) a5 sortVL xs = map fst sorted :< (snd (last sorted)) where1 lefts = head xs :> map snd (init sorted) rights = tail xs: sorted = zipWith compareSwapL (lazyV lefts) rights:}:{9let sortV_flip xs = map fst sorted :< (snd (last sorted)) where1 lefts = head xs :> map snd (init sorted) rights = tail xs9 sorted = zipWith (flip compareSwapL) rights lefts:} Example usage For example: *-- Bubble sort for 1 iteration sortV xs = Æ fst sorted œ (snd (¢ sorted)) where lefts =   xs :> Æ snd (£ sorted) rights = ¡ xs sorted = »þ compareSwapL lefts rights -- Compare and swap compareSwapL a b = if a < b then (a,b) else (b,a) Will not terminate because »& is too strict in its second argument.In this case, adding þ on »s second argument:  sortVL xs = Æ fst sorted œ (snd (¢ sorted)) where lefts =   xs :> map snd (£ sorted) rights = ¡ xs sorted = » compareSwapL (þ lefts) rights $Results in a successful computation: sortVL (4 :> 1 :> 2 :> 3 :> Nil)1 :> 2 :> 3 :> 4 :> NilNB!: There is also a solution using Î6, but it slightly obfuscates the meaning of the code: sortV_flip xs = Æ fst sorted œ (snd (¢ sorted)) where lefts =   xs :> Æ snd (£ sorted) rights = ¡ xs sorted = » (Î compareSwapL) rights lefts $sortV_flip (4 :> 1 :> 2 :> 3 :> Nil)1 :> 2 :> 3 :> 4 :> Nilÿ clash-preludeA  dependently typed fold.doctests setup%:seti -fplugin GHC.TypeLits.Normalise1import Data.Singletons (Apply, Proxy (..), TyFun)Àdata Append (m :: Nat) (a :: Type) (f :: TyFun Nat Type) :: Type2type instance Apply (Append m a) l = Vec (l + m) aÊlet append' xs ys = dfold (Proxy :: Proxy (Append m a)) (const (:>)) ys xs Example usageUsing lists, we can define append (a.k.a.  Data.List.™›) in terms of  Data.List.™œ:import qualified Data.List,let append xs ys = Data.List.foldr (:) ys xsappend [1,2] [3,4] [1,2,3,4](However, when we try to do the same for Ã, by defining append' in terms of Clash.Sized.Vector.Å: append' xs ys = Å (:>) ys xs we get a type error: (>>> let append' xs ys = foldr (:>) ys xsü :... ¢@ Occurs check: cannot construct the infinite type: ... ~ ... + 1 Expected type: a -> Vec ... a -> Vec ... a Actual type: a -> Vec ... a -> Vec (... + 1) a ¢@ In the first argument of ˜@foldr™@, namely ˜@(:>)™@ In the expression: foldr (:>) ys xs In an equation for ˜@append'™@: append' xs ys = foldr (:>) ys xs ¢@ Relevant bindings include ys :: Vec ... a (bound at ...) append' :: Vec n a -> Vec ... a -> Vec ... a (bound at ...) The reason is that the type of Å is::t foldr+foldr :: (a -> b -> b) -> b -> Vec n a -> bWhile the type of (�) is::t (:>)%(:>) :: a -> Vec n a -> Vec (n + 1) aWe thus need a fold4 function that can handle the growing vector type: ÿ. Compared to Å, ÿ' takes an extra parameter, called the motiveÌ, that allows the folded function to have an argument and result type that depends, on the current length of the vector. Using ÿ, we can now correctly define append': Óimport Data.Singletons import Data.Proxy data Append (m :: Nat) (a :: Type) (f :: �! Nat Type) :: Type type instance ‘ (Append m a) l = à (l + m) a append' xs ys = ÿ' (Proxy :: Proxy (Append m a)) (const (� )) ys xs We now see that append' has the appropriate type: :t append' Vec k a -> Vec m a -> Vec (k + m) aAnd that it works:'append' (1 :> 2 :> Nil) (3 :> 4 :> Nil)1 :> 2 :> 3 :> 4 :> NilNB: "ÿ m f z xsÁ" creates a linear structure, which has a depth, or delay, of O(Ù xs ). Look at € for a  dependently? typed fold that produces a structure with a depth of O(log_2(Ù xs)).€ clash-preludeA combination of ÿ and Ã: a  dependently; typed fold that reduces a vector in a tree-like structure.doctests setup:seti -XUndecidableInstances1import Data.Singletons (Apply, Proxy (..), TyFun))data IIndex (f :: TyFun Nat Type) :: Type.type instance Apply IIndex l = Index ((2^l)+1):{Úlet populationCount' :: (KnownNat k, KnownNat (2^k)) => BitVector (2^k) -> Index ((2^k)+1)0 populationCount' bv = dtfold (Proxy @IIndex)- fromIntegral4 (\_ x y -> add x y)* (bv2v bv):} Example usage,As an example of when you might want to use €Þ we will build a population counter: a circuit that counts the number of bits set to '1' in a µ. Given a vector of nÆ bits, we only need we need a data type that can represent the number n: · (n+1). · k has a range of  [0 .. k-1] (using  ceil(log2(k)) bits), hence we need · n+1$. As an initial attempt we will use r, because it gives a nice (log2(n)) tree-structure of adders: ÇpopulationCount :: (KnownNat (n+1), KnownNat (n+2)) => µ (n+1) -> ·2 (n+2) populationCount = sum . map fromIntegral . Ç ðThe "problem" with this description is that all adders have the same bit-width, i.e. all adders are of the type: (+) :: · (n+2) -> · (n+2) -> · (n+2). èThis is a "problem" because we could have a more efficient structure: one where each layer of adders is  preciselyË wide enough to count the number of bits at that layer. That is, at height d! we want the adder to be of type: · ((2^d)+1) -> · ((2^d)+1) -> · ((2^(d+1))+1) )We have such an adder in the form of the  �& function, as defined in the instance  ž instance of · . However, we cannot simply use à to create a tree-structure of  �es: # 2390 "srcClashÅSized/Vector.hs" >>> :{ let populationCount' :: (KnownNat (n+1), KnownNat (n+2)) => BitVector (n+1) -> Index (n+2) populationCount' = fold add . map fromIntegral . bv2v :}  BLANKLINE  interactivež:... ¢@ Couldn't match type ˜@((n + 2) + (n + 2)) - 1™@ with ˜@n + 2™@ Expected type: Index (n + 2) -> Index (n + 2) -> Index (n + 2) Actual type: Index (n + 2) -> Index (n + 2) -> AResult (Index (n + 2)) (Index (n + 2)) ¢@ In the first argument of ˜@fold™@, namely ˜@add™@ In the first argument of ˜@(.)™@, namely ˜@fold add™@ In the expression: fold add . map fromIntegral . bv2v ¢@ Relevant bindings include populationCount' :: BitVector (n + 1) -> Index (n + 2) (bound at ...)because à expects a function of type " a -> a -> aÑ", i.e. a function where the arguments and result all have exactly the same type.(In order to accommodate the type of our  �å, where the result is larger than the arguments, we must use a dependently typed fold in the form of €: â{-# LANGUAGE UndecidableInstances #-} import Data.Singletons import Data.Proxy data IIndex (f :: �! Nat Type) :: Type type instance ‘ IIndex l = ·Š ((2^l)+1) populationCount' :: (KnownNat k, KnownNat (2^k)) => BitVector (2^k) -> Index ((2^k)+1) populationCount' bv = €ã (Proxy @IIndex) fromIntegral (\_ x y ->  �$ x y) (Ç bv) And we can test that it works:':t populationCount' (7 :: BitVector 16)0populationCount' (7 :: BitVector 16) :: Index 17$populationCount' (7 :: BitVector 16)3Some final remarks: By using € instead of Ã, we had to restrict our µ5 argument to have bit-width that is a power of 2.Even though our original populationCountª function specified a structure where all adders had the same width. Most VHDL/(System)Verilog synthesis tools will create a more efficient circuit, i.e. one where the adders have an increasing bit-width for every layer, from the VHDL/(System)Verilog produced by the Clash compiler.NB5: The depth, or delay, of the structure produced by "€ m f g xs " is O(log_2(Ù xs)).� clash-preludeSpecialised version of ÿ3 that builds a triangular computational structure.doctests setup4let compareSwap a b = if a > b then (a,b) else (b,a)Èlet insert y xs = let (y',xs') = mapAccumL compareSwap y xs in xs' :< y'(let insertionSort = vfold (const insert) Example usage ÒcompareSwap a b = if a > b then (a,b) else (b,a) insert y xs = let (y',xs') = Ê compareSwap y xs in xs' œ y' insertionSort = � (const insert) ÁBuilds a triangular structure of compare and swaps to sort a row.'insertionSort (7 :> 3 :> 9 :> 1 :> Nil)1 :> 3 :> 7 :> 9 :> NilThe circuit layout of  insertionSort, build using �, is: doc/csSort.svg‚ clash-prelude)The largest element of a non-empty vectorƒ clash-prelude'The least element of a non-empty vector„ clash-preludeÑApply a function to every element of a vector and the element's position (as an ¨ value) in the vector.+let rotateMatrix = smap (flip rotateRightS)=let xss = (1:>2:>3:>Nil):>(1:>2:>3:>Nil):>(1:>2:>3:>Nil):>NilxssË(1 :> 2 :> 3 :> Nil) :> (1 :> 2 :> 3 :> Nil) :> (1 :> 2 :> 3 :> Nil) :> NilrotateMatrix xssË(1 :> 2 :> 3 :> Nil) :> (3 :> 1 :> 2 :> Nil) :> (2 :> 3 :> 1 :> Nil) :> Nil‡ clash-prelude Convert a à of ´s to a µ.2let x = (0:>0:>0:>1:>0:>0:>1:>0:>Nil) :: Vec 8 Bitx+0 :> 0 :> 0 :> 1 :> 0 :> 0 :> 1 :> 0 :> Nilv2bv x 0b0001_0010ˆ clash-preludeÈEvaluate all elements of a vector to WHNF, returning the second argument‰ clash-prelude)Evaluate all elements of a vector to WHNFŠ clash-preludeÞEvaluate all elements of a vector to WHNF, returning the second argument. Does not propagate Ÿs.‹ clash-prelude?Evaluate all elements of a vector to WHNF. Does not propagate Ÿs.Ÿ clash-preludeûIn many cases, this Generic instance only allows generic functions/instances over vectors of at least size 1, due to the n-1 in the  Rep (Vec n a) definition.$We'll have to wait for things like  Îhttps://ryanglscott.github.io/2018/02/11/how-to-derive-generic-for-some-gadts/+ before we can work around this limitation¤ clash-preludeThe old vector clash-prelude$The elements to shift in at the head clash-prelude&(The new vector, shifted out elements)¥ clash-preludeThe old vector clash-prelude$The elements to shift in at the tail clash-prelude&(The new vector, shifted out elements)¨ clash-preludem%, the number of elements to shift out clash-preludeThe old vector clash-prelude&(The new vector, shifted out elements)© clash-preludem%, the number of elements to shift out clash-preludeThe old vector clash-prelude&(The new vector, shifted out elements)ë clash-preludeWindows length stX, at least size 1 clash-preludeThe stencil (function)ì clash-prelude Window hight stY, at least size 1 clash-prelude Window width stX, at least size 1 clash-preludeThe stencil (function)í clash-prelude%Length of the window, at least size 1î clash-prelude Window hight stY, at least size 1 clash-prelude Window width stX, at least size 1ï clash-preludeCombination function, f clash-preludeDefault values, def clash-preludeIndex mapping, is clash-preludeVector to be permuted, xsð clash-preludeSource vector, xs clash-preludeIndex mapping, isñ clash-preludeDefault values, def clash-preludeIndex mapping, is clash-preludeVector to be scattered, xsò clash-preludeSource vector, xs clash-preludeIndex mapping, isó clash-preludeInterleave step, dÿ clash-preludeThe motive clash-preludeFunction to fold.NB: The SNat l is not the index (see (Ø)) to the element a. SNat l7 is the number of elements that occur to the right of a. clash-preludeInitial element clash-preludeVector to fold over€ clash-preludeThe motive clash-prelude"Function to apply to every element clash-preludeFunction to combine results.NB: The SNat l‰ indicates the depth/height of the node in the tree that is created by applying this function. The leafs of the tree have depth/height 0&, and the root of the tree has height k. clash-preludeVector to fold over.NB*: Must have a length that is a power of 2.øÃš�œ›ÄÅÆÇ™žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹úÚ�œ›�œÙýØ ¢ß·¸¹º¡£ÛÜÝÞà᫬¯°Ÿâãäåèéæçûª¦§­®¤¥¨©±Úïðñò²êóôõö÷Ƴ„»¼½¾¿ÀÌÍÎÏÐÑ´ÒÓÔÕÖ×ÅÄÁÂõ¶ÿ€�‚ƒÄÅÈÆÇÉÊËëìíîøùúLJþ™üˆ‰Š‹ž…†›5œ5�5¦4§4ª5ˆ0Š01À(C) 2019, Google Inc., 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&'(/02356789; Int -> SimIO Int tbMachine (fileIn,fileOut) regOut = do eofFileOut <- ­ fileOut eofFileIn <- ­2 fileIn when (eofFileIn || eofFileOut) $ do £ "success" ¤ 0 goldenIn <- ª fileIn goldenOut <- ªü fileOut res <- if regOut == fromEnum goldenOut then do return (fromEnum goldenIn) else do £1 "Output doesn't match golden output" ¤ë 1 display ("Output matches golden output") return res tbInit :: (File,File) tbInit = do fileIn <- ¨( "./goldenInput00.txt" "r" fileOut <- ¨ö "./goldenOutput00.txt" "r" return (fileIn,fileOut) topEntity :: Signal System Int topEntity = regOut where clk = systemClockGen rst = resetGen ena = enableGen regOut = register clk rst ena (fromEnum 'a') regIn regIn = ² clk tbMachine tbInit regOut £ clash-preludeString you want to display¤ clash-prelude=The exit code you want to return at the end of the simulation¥ clash-preludeThe starting value§ clash-preludeThe mutable reference clash-prelude The new value¨ clash-prelude File to open clash-prelude File mode:"r": Open for reading"w": Create for writing "a": Append+"r+": Open for update (reading and writing)"w+": Create for update6"a+": Append, open or create for update at end-of-fileª clash-preludeFile to read from« clash-preludeCharacter to insert clash-preludeBuffer to insert to¬ clash-preludeFile to read from clash-preludeVector to store the content­ clash-preludeFile we want to inspect® clash-preludeFile to set the position for clash-preludePosition clash-preludeMode:!0: From the beginning of the file1: From the current position2: From the end of the file° clash-preludeFile we want to inspect² clash-prelude2Clock at which rate the I/O environment progresses clash-prelude-Transition function inside an I/O environment clash-prelude&I/O action to create the initial state ¡¢£¤¥¦§¨©ª«¬­®¯°±²²¢£¤¡¥¦§ ¨©ª«¬­±®¯°2«(C) 2015-2016, University of Twente, 2017 , Google Inc. 2019 , Myrtle Software Ltd, 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&'(/02356789;<ÇÉÐÑÔÖ×Ùâì™¶ clash-prelude5A ROM with a synchronous read port, with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an Ÿ See also:See #Clash.Sized.Fixed#creatingdatafiles and !Clash.Explicit.BlockRam#usingrams( for ideas on how to use ROMs and RAMs.A large ÃÒ for the content may be too inefficient, depending on how it is constructed. See =  and B¡+ for different approaches that scale well.· clash-prelude3A ROM with a synchronous read port, with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an Ÿ See also:See #Clash.Sized.Fixed#creatingdatafiles and !Clash.Explicit.BlockRam#usingrams( for ideas on how to use ROMs and RAMs.A large ÃÒ for the content may be too inefficient, depending on how it is constructed. See =¢ and B£* for different approaches that scale well.¸ clash-prelude ROM primitive¶ clash-preludeå to synchronize to clash-preludeé line clash-prelude ROM contentNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle· clash-preludeå to synchronize to clash-preludeé line clash-prelude'ROM content, also determines the size, n , of the ROMNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle¸ clash-preludeå to synchronize to clash-preludeé line clash-prelude'ROM content, also determines the size, n , of the ROMNB: MUST be a constant clash-prelude Read address rd clash-prelude The value of the ROM at address rd from the previous clock cycle¶·¸·¶¸3(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij None#&-./02356789;<>ÀÁÂÇÉÐÑÖ×Ùâì"¨ ¹ clash-prelude1Type class that specifies that a certain domain, dom+, needs to be present in some other type, ró. This is used to disambiguate what hidden clock, reset, and enable lines should be exposed in functions such as ¤.+Functions in need of this class should use ÆÑ though, to force Clash to display an error instead of letting it silently pass.» clash-prelude²Helper function for HasSpecificDomain class (I don't really understand why this one is necessary. HasDomainWrapper _should_ check for stuckness and does so according to tests..¼ clash-prelude.Wrapper that checks for stuckness and returns  'NotFound if so¾ clash-preludeÍType family that searches a type and checks whether a specific domain is present. Will result in either "domain not found, and no others either", "domain not found, but found another", or "found domain".¿ clash-prelude"Check domain for equality. Return 'Found if so, return  'NotFound¬ if not. The reason d'etre for this type family is that _open_ type families don't allow overlapping types. We therefore defer equality checking to a closed type family. clash-prelude Merge two Ã+s according to the semantics of 'HasDomain.Ä clash-preludeNo domain foundÅ clash-prelude0Found the specific domain caller was looking forÆ clash-preludeType that forces dom to be present in rÚ at least once. Will resolve to a type error if it doesn't. It will always fail if given dom1 is completely polymorphic and can't be tied to r in any way.¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÈÇÆÃÄÅÂÁÀ¿¾½¼»¹º5Ê(C) 2018, Google Inc., 2021-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&./02356789:;<ÇÉÐÑÖ×Ùâì1ŸÊ clash-preludeùSynthesis attributes are directives passed to synthesis tools, such as Quartus. An example of such an attribute in VHDL: ˆ attribute chip_pin : string; attribute chip_pin of sel : signal is "C4"; attribute chip_pin of data : signal is "D1, D2, D3, D4"; 7This would instruct the synthesis tool to map the wire sel to pin C4 , and wire data to pins D1, D2, D3, and D4. To achieve this in Clash, Attr/s are used. An example of the same annotation: —import Clash.Annotations.SynthesisAttributes (Attr (..), Annotate ) myFunc :: (Signal System Bool `Annotate` 'StringAttr "chip_pin" "C4") -> (Signal System Int4 `Annotate` 'StringAttr "chip_pin" "D1, D2, D3, D4") -> ... myFunc sel data = ... {-# NOINLINE myFunc #-} ÝTo ensure this function will be rendered as its own module, do not forget a NOINLINE pragma.Multiple attributes for the same9 argument can be specified by using a list. For example: ˜Signal System Bool `Annotate` [ 'StringAttr "chip_pin" "C4" , 'BoolAttr "direct_enable" 'True , 'IntegerAttr "max_depth" 512 , 'Attr "keep" ] For Verilog see: íhttps://www.intel.com/content/www/us/en/programmable/quartushelp/current/index.htm#hdl/vlog/vlog_file_dir.htmFor VHDL, see: íhttps://www.intel.com/content/www/us/en/programmable/quartushelp/current/index.htm#hdl/vhdl/vhdl_file_dir.htmWarningsŸWhen using annotations, it is important that annotated arguments are not eta-reduced, as this may result in the annotation being stripped by GHC. For example “f :: Signal System Bool `Annotate` 'StringAttr "chip_pin" "C4" -> Signal System Bool f x = id x -- Using a lambda, i.e. f = x -> id x also works ;will reliably show the annotation in the generated HDL, but Þg :: Signal System Bool `Annotate` 'StringAttr "chip_pin" "C4" -> Signal System Bool g = id will not work.êThis is an experimental feature, please report any unexpected or broken behavior to Clash's GitHub page ( 3https://github.com/clash-lang/clash-compiler/issues).Use Ðã if you wish to annotate an intermediate signal. Its use is preferred over type level annotations.Ë clash-prelude:Attribute which argument is rendered as a bool. Example: ûhttps://www.intel.com/content/www/us/en/programmable/quartushelp/current/index.htm#hdl/vlog/vlog_file_dir_direct_enable.htmÌ clash-prelude=Attribute which argument is rendered as a integer. Example: ÷https://www.intel.com/content/www/us/en/programmable/quartushelp/current/index.htm#hdl/vlog/vlog_file_dir_max_depth.htmÍ clash-prelude Trustworthy!&'(/02356789;<ÇÉÐÑÔÖ×ÙâèìT­Û clash-preludePerfect depth binary tree.)Only has elements at the leaf of the treeA tree of depth d has 2^d elements.Þ clash-preludeRBranch of a perfect depth treeBR (LR 1) (LR 2)<1,2>let x = BR (LR 1) (LR 2):t xx :: Num a => RTree 1 aCase be used a pattern:%let f (BR (LR a) (LR b)) = LR (a + b):t f$f :: Num a => RTree 1 a -> RTree 0 af (BR (LR 1) (LR 2))3ß clash-preludeRLeaf of a perfect depth treeLR 11 let x = LR 1:t xx :: Num a => RTree 0 aCan be used as a pattern:let f (LR a) (LR b) = a + b:t f)f :: Num a => RTree 0 a -> RTree 0 a -> af (LR 1) (LR 2)3à clash-preludeA  dependently typed fold over trees.,As an example of when you might want to use €Þ we will build a population counter: a circuit that counts the number of bits set to '1' in a ¥. Given a vector of nÆ bits, we only need we need a data type that can represent the number n: · (n+1). · k has a range of  [0 .. k-1] (using  ceil(log2(k)) bits), hence we need · n+1$. As an initial attempt we will use á, because it gives a nice (log2(n)) tree-structure of adders: ¶populationCount :: (KnownNat (2^d), KnownNat d, KnownNat (2^d+1)) => BitVector (2^d) -> Index (2^d+1) populationCount = tfold (resize . bv2i . pack) (+) . v2t . bv2v ðThe "problem" with this description is that all adders have the same bit-width, i.e. all adders are of the type: (+) :: · (2^d+1) -> · (2^d+1) -> · (2^d+1). èThis is a "problem" because we could have a more efficient structure: one where each layer of adders is  preciselyË wide enough to count the number of bits at that layer. That is, at height d! we want the adder to be of type: · ((2^d)+1) -> · ((2^d)+1) -> · ((2^(d+1))+1) )We have such an adder in the form of the  �& function, as defined in the instance  ž instance of · . However, we cannot simply use ¦ to create a tree-structure of  � s: # 325 "srcClashßSized/RTree.hs" >>> :{ let populationCount' :: (KnownNat (2^d), KnownNat d, KnownNat (2^d+1)) => BitVector (2^d) -> Index (2^d+1) populationCount' = tfold (resize . bv2i . pack) add . v2t . bv2v :}  BLANKLINE  interactiveÌ:... ¢@ Couldn't match type ˜@(((2 ^ d) + 1) + ((2 ^ d) + 1)) - 1™@ with ˜@(2 ^ d) + 1™@ Expected type: Index ((2 ^ d) + 1) -> Index ((2 ^ d) + 1) -> Index ((2 ^ d) + 1) Actual type: Index ((2 ^ d) + 1) -> Index ((2 ^ d) + 1) -> AResult (Index ((2 ^ d) + 1)) (Index ((2 ^ d) + 1)) ¢@ In the second argument of ˜@tfold™@, namely ˜@add™@ In the first argument of ˜@(.)™@, namely ˜@tfold (resize . bv2i . pack) add™@ In the expression: tfold (resize . bv2i . pack) add . v2t . bv2v ¢@ Relevant bindings include populationCount' :: BitVector (2 ^ d) -> Index ((2 ^ d) + 1) (bound at ...)because á expects a function of type " b -> b -> bÑ", i.e. a function where the arguments and result all have exactly the same type.(In order to accommodate the type of our  �å, where the result is larger than the arguments, we must use a dependently typed fold in the form of €: Ð{-# LANGUAGE UndecidableInstances #-} import Data.Singletons data IIndex (f :: �! Nat Type) :: Type type instance ‘ IIndex l = ·Š ((2^l)+1) populationCount' :: (KnownNat k, KnownNat (2^k)) => BitVector (2^k) -> Index ((2^k)+1) populationCount' bv = àí (Proxy @IIndex) (resize . bv2i . pack) (\_ x y ->  �$ x y) (æ (§ bv)) And we can test that it works:':t populationCount' (7 :: BitVector 16)0populationCount' (7 :: BitVector 16) :: Index 17$populationCount' (7 :: BitVector 16)3á clash-prelude!Reduce a tree to a single elementâ clash-prelude"â d a" returns a tree of depth d , and has 2^d copies of a.treplicate (SNat :: SNat 3) 6<<<6,6>,<6,6>>,<<6,6>,<6,6>>>treplicate d3 6<<<6,6>,<6,6>>,<<6,6>,<6,6>>>ã clash-prelude"ã a(" creates a tree with as many copies of a as demanded by the context.trepeat 6 :: RTree 2 Int <<6,6>,<6,6>>ä clash-prelude"ä f t " is the tree obtained by apply f to each element of t, i.e., 5tmap f (BR (LR a) (LR b)) == BR (LR (f a)) (LR (f b))å clash-preludeÖGenerate a tree of indices, where the depth of the tree is determined by the context.tindices :: RTree 3 (Index 8)<<<0,1>,<2,3>>,<<4,5>,<6,7>>>æ clash-preludeConvert a vector with 2^d elements to a tree of depth d.v2t (1 :> 2 :> 3 :> 4:> Nil) <<1,2>,<3,4>>ç clash-preludeConvert a tree of depth d to a vector of 2^d elements*(BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) <<1,2>,<3,4>>.t2v (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4)))1 :> 2 :> 3 :> 4 :> Nilè clash-prelude"è t n" returns the n'th element of t.The bottom-left leaf had index 0', and the bottom-right leaf has index 2^d-1, where d is the depth of the tree6indexTree (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) 016indexTree (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) 237indexTree (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) 14Ï*** Exception: Clash.Sized.Vector.(!!): index 14 is larger than maximum index 3...é clash-prelude"é n a t" returns the tree t where the n'th element is replaced by a.The bottom-left leaf had index 0', and the bottom-right leaf has index 2^d-1, where d is the depth of the tree:replaceTree 0 5 (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) <<5,2>,<3,4>>:replaceTree 2 7 (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) <<1,2>,<7,4>>:replaceTree 9 6 (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4)))Û<<1,2>,<3,*** Exception: Clash.Sized.Vector.replace: index 9 is larger than maximum index 3...ê clash-preludeê generalizes ëµ by zipping with the function given as the first argument, instead of a tupling function. For example, "tzipWith (+)" applied to two trees produces the tree of corresponding sums. ØtzipWith f (BR (LR a1) (LR b1)) (BR (LR a2) (LR b2)) == BR (LR (f a1 a2)) (LR (f b1 b2))ë clash-preludeë; takes two trees and returns a tree of corresponding pairs.ì clash-preludeìÝ transforms a tree of pairs into a tree of first components and a tree of second components.í clash-preludeGiven a function f that is strict in its nth Û% argument, make it lazy by applying í to this argument: "f x0 x1 .. (lazyT xn) .. xn_plus_kî clash-prelude#Extract the first element of a tree8The first element is defined to be the bottom-left leaf.0thead $ BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))1ï clash-prelude"Extract the last element of a tree8The last element is defined to be the bottom-right leaf.0tlast $ BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))4ð clash-preludeò applied to Ã&scanlPar (+) (1 :> 2 :> 3 :> 4 :> Nil)1 :> 3 :> 6 :> 10 :> Nilñ clash-preludeó applied to Ã&scanrPar (+) (1 :> 2 :> 3 :> 4 :> Nil)10 :> 9 :> 7 :> 4 :> Nilò clash-preludeLow-depth left scanò is similar to ¨Á, but returns a tree of successive reduced values from the left: Ätscanl f [x1, x2, x3, ...] == [x1, x1 `f` x2, x1 `f` x2 `f` x3, ...]*tscanl (+) (v2t (1 :> 2 :> 3 :> 4 :> Nil))<<1,3>,<6,10>> doc/scanlPar.svgó clash-preludeLow-depth right scanó is similar to œÁ, but returns a tree of successive reduced values from the left: Étscanr f [..., xn2, xn1, xn] == [..., xn2 `f` xn1 `f` xn, xn1 `f` xn, xn]*tscanr (+) (v2t (1 :> 2 :> 3 :> 4 :> Nil))<<10,9>,<7,4>>à clash-preludeThe motive clash-prelude.Function to apply to the elements on the leafs clash-prelude#Function to fold the branches with.NB: SNat l& is the depth of the two sub-branches. clash-preludeTree to fold over.á clash-preludeFunction to apply to the leaves clash-preludeÁFunction to combine the results of the reduction of two branches clash-preludeTree to fold reduceð clash-preludeMust be associativeñ clash-preludeMust be associativeò clash-preludeMust be associativeÛßÞÜÝàáâãäåæçèéêëìíîïðñòóÛßÞÜÝßÞâãîïèåéäêëìáàðòñóæçí7Ž(C) 2013-2016, University of Twente, 2017-2019, Myrtle Software Ltd, Google Inc. 2019,2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789;<ÇÉÐÑÖ×Ùâìa�„ clash-preludeIsomorphism between a n9 of a product type (e.g. a tuple) and a product type of ns. Instances of „! must satisfy the following laws: † . ‡ = X ‡ . † = X  By default, † and ‡1, are defined as the identity, that is, writing: "data D = A | B instance Bundle D is the same as: /data D = A | B instance Bundle D where type … clk D = ë clk D † s = s ‡ s = s ÄFor custom product types you'll have to write the instance manually: †data Pair a b = MkPair { getA :: a, getB :: b } instance Bundle (Pair a b) where type Unbundled dom (Pair a b) = Pair (Signal dom a) (Signal dom b) -- bundle :: Pair (Signal dom a) (Signal dom b) -> Signal dom (Pair a b) bundle (MkPair as bs) = MkPair  $ as  *ò bs -- unbundle :: Signal dom (Pair a b) -> Pair (Signal dom a) (Signal dom b) unbundle pairs = MkPair (getA  $ pairs) (getB  $ pairs) † clash-preludeExample: bundle :: (ë dom a, ë dom b) -> ë dom (a,b) However: bundle :: ë dom ´ -> ë dom ´ ‡ clash-preludeExample: unbundle :: ë dom (a,b) -> (ë dom a, ë dom b) However: unbundle :: ë dom ´ -> ë dom ´ – clash-preludeÝHelper type to emulate the "old" behavior of Bundle's unit instance. I.e., the instance for  Bundle () used to be defined as: Úclass Bundle () where bundle :: () -> Signal dom () unbundle :: Signal dom () -> () .In order to have sensible type inference, the „, class specifies that the argument type of †? should uniquely identify the result type, and vice versa for ‡=. The type signatures in the snippet above don't though, as ()= doesn't uniquely map to a specific domain. In other words, domainÀ should occur in both the argument and result of both functions.–7 tackles this by carrying the domain in its type. The † and ‡ instance now looks like: –class Bundle EmptyTuple where bundle :: TaggedEmptyTuple dom -> Signal dom EmptyTuple unbundle :: Signal dom EmptyTuple -> TaggedEmptyTuple dom dom8 is now mentioned both the argument and result for both † and ‡.˜ clash-preludeSee –ž clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples� is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version.© clash-preludeSee  æhttps://github.com/clash-lang/clash-compiler/pull/539/commits/94b0bff5770aa4961e04ddce2515130df3fc7863commit 94b0bff5 and documentation for –. „…‡†–—˜™š „…‡†˜™–—š8¬(C) 2015-2016, University of Twente, 2017 , Google Inc., 2019 , Myrtle Software Ltd, 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe&'(/02356789;<ÇÉÐÑÖ×Ùâìt­ª clash-prelude$Create a block RAM with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an èNB’: This function might not work for specific combinations of code-generation backends and hardware targets. Please check the support table below:VHDLVerilog SystemVerilogAltera/QuartusBrokenWorksWorks Xilinx/ISEWorksWorksWorksASICUntestedUntestedUntested See also:See  Clash.Prelude.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter C©6 for obtaining write-before-read semantics like this: C©2 clk rst en (blockRamFilePow2' clk en file) rd wrM.See *Clash.Explicit.BlockRam.File#usingramfilesÚ for more information on how to instantiate a block RAM with the contents of a data file.See ¬% for creating a data file with Clash.See &Clash.Explicit.Fixed#creatingdatafiles6 for more ideas on how to create your own data files.« clash-prelude"Create a block RAM with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an èNB’: This function might not work for specific combinations of code-generation backends and hardware targets. Please check the support table below:VHDLVerilog SystemVerilogAltera/QuartusBrokenWorksWorks Xilinx/ISEWorksWorksWorksASICUntestedUntestedUntested See also:See !Clash.Explicit.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter C©6 for obtaining write-before-read semantics like this: C© clk rst en (« clk en size file) rd wrM.See *Clash.Explicit.BlockRam.File#usingramfilesÚ for more information on how to instantiate a block RAM with the contents of a data file.See ¬% for creating a data file with Clash.See #Clash.Sized.Fixed#creatingdatafiles6 for more ideas on how to create your own data files.¬ clash-preludeConvert data to the R contents of a memory file.NB: Not synthesizableÎThe following document the several ways to instantiate components with files:)Clash.Prelude.BlockRam.File#usingramfiles$Clash.Prelude.ROM.File#usingromfiles*Clash.Explicit.BlockRam.File#usingramfiles%Clash.Explicit.ROM.File#usingromfilesSee #Clash.Sized.Fixed#creatingdatafiles6 for more ideas on how to create your own data files.ExampleThe MaybeÄ datatype has don't care bits, where the actual value does not matter. But the bits need a defined value in the memory. Either 0 or 1 can be used, and both are valid representations of the data.3let es = [ Nothing, Just (7 :: Unsigned 8), Just 8]!mapM_ (putStrLn . show . pack) es 0b0_...._.... 0b1_0000_0111 0b1_0000_1000putStr (memFile (Just 0) es) 000000000 100000111 100001000putStr (memFile (Just 1) es) 011111111 100000111 100001000­ clash-preludeblockRamFile primitive® clash-preludeNB: Not synthesizableª clash-preludeå to synchronize to clash-preludeé line clash-prelude/File describing the initial content of the BRAM clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle« clash-preludeå to synchronize to clash-preludeé line clash-preludeSize of the BRAM clash-prelude/File describing the initial content of the BRAM clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle¬ clash-prelude!Value to map don't care bits to. J- means throwing an error on don't care bits. clash-preludeValues to convert clash-preludeContents of the memory file­  clash-preludeå to synchronize to clash-preludeé line clash-preludeSize of the BRAM clash-prelude/File describing the initial content of the BRAM clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycleª«¬­®«ª¬­®9(C) 2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None#$&'(/02356789;<ÇÉÐÑÖ×Ùàâì\ ± clash-prelude*Determine whether a write enable is active² clash-prelude%Merge global enable with write enable³ clash-prelude$Update memory with a defined address´ clash-preludeHelper used in ¹¶ clash-prelude Read/Write conflict for output A· clash-prelude Read/Write conflict for output B¸ clash-preludeWrite/Write conflict¹ clash-preludeîDetermines whether there was a write-write or read-write conflict. A conflict occurs when two ports tried to (potentially, in case of undefined values) access the same address and one or both tried to write to it. See documentation of ´ for more information.º clash-preludeÎStep through a cycle of a TDP block RAM where only one clock is active. Like ¼, it accounts for è6 in all values supplied by the user of the block RAM.» clash-preludeäStep through a cycle of a TDP block RAM where the clock edges of port A and port B coincided. Like ¼, it accounts for è6 in all values supplied by the user of the block RAM.¼ clash-preludeþAccess a RAM and account for undefined values in the address, write enable, and data to write. Return read after write value.½ clash-prelude×Haskell model for a true dual-port block RAM which is polymorphic in its write enables¹ clash-prelude%Port A: enable, write enable, address clash-prelude%Port B: enable, write enable, address clash-preludeK5 if there is a (potential) write conflict, otherwise Jº clash-preludePrevious value clash-preludeMemory clash-prelude/Port: enable, address, write enable, write data clash-preludeUpdated memory, output value» clash-preludePrevious value for port A clash-preludePrevious value for port B clash-preludeMemory clash-prelude1Port A: enable, address, write enable, write data clash-prelude1Port B: enable, address, write enable, write data clash-prelude.Updated memory, output value A, output value B¼ clash-prelude*Determine whether a write enable is active clash-prelude$Update memory with a defined address clash-preludeAddress clash-prelude Byte enable clash-prelude Data to write clash-preludeMemory to write to clash-prelude$(Read after write value, new memory)½ clash-preludeEnable clash-preludeAddress clash-prelude Write enable clash-prelude Write data clash-preludeEnable clash-preludeAddress  clash-preludeWrite byte enable  clash-prelude Write data¯°³±²´µ¸·¶¹º»¼½´µ¸·¶¹º»¼¯°³±²½:Ä(C) 2019, Myrtle Software Ltd 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None!&-./02356789;<>ÀÇÉÐÑÖ×ÙâìƒO¿ clash-preludeþType family that searches a type and checks whether all subtypes that can contain a domain (for example, Signal) contain the sameð domain. Its associated type, GetDomain, will yield a type error if that doesn't hold OR if it can't check it.à clash-preludeÁSame as Merge', but will insert a type error if Merge' got stuck.Ä clash-prelude.Type family to resolve type conflicts (if any)É clash-preludeType that forces dom# to be the same in all subtypes of rÉ that might contain a domain. If given a polymorphic domain not tied to rÈ, GHC will be allowed to infer that that domain is equal to the one in r on the condition that r contains just a single domain.¿ÀÁÂÃÄÅÆÈÇÉÊËÌÍÎÎÍÌËÊÉÅÆÈÇÄÃÂÁ¿À4None&/02356789;<ÇÉÐÑÖ×ÙâìƒÍ ¾¿ÆÁÅÇÈÆÉ ÆÉ¾ÁÅÇÈÆ¿;í(C) 2017, Google Inc. 2019, Myrtle Software Ltd 2022-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None$&'(/02356789;<>?ÀÁÂÇÉÊÐÑÔÖ×Ùâì�¶Ð clash-preludeThe out part of an inout port÷Wraps (multiple) writing signals. The semantics are such that only one of the signals may write at a single time step.BiSignalOut has the Îhttps://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role:i BiSignalOut-type role BiSignalOut nominal nominal nominal...èas it is not safe to coerce the default behaviour, synthesis domain or width of the data in the signal.Ñ clash-preludeThe in part of an inout port. BiSignalIn has the Îhttps://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i BiSignalIn,type role BiSignalIn nominal nominal nominal...èas it is not safe to coerce the default behaviour, synthesis domain or width of the data in the signal.Ò clash-preludeType class for ØÃ: can be used as a constraint and for obtaining the pull-up modeÔ clash-preludeSingleton versions of ØØ clash-preludeUsed to specify the defaultÙ behavior of a "BiSignal", i.e. what value is read when no value is being written to it.Ù clash-preludeinout3 port behaves as if connected to a pull-up resistorÚ clash-preludeinout5 port behaves as if connected to a pull-down resistorÛ clash-preludeinout port behaves as if is floating . Reading a floatingÈ "BiSignal" value in simulation will yield an errorX (undefined value).Ü clash-preludeRead the value from an inout portÝ clash-preludeCombine several inout signals into one.Þ clash-prelude Write to an inout portß clash-prelude Converts the out part of a BiSignal to an in› part. In simulation it checks whether multiple components are writing and will error accordingly. Make sure this is only called ONCE for every BiSignal.æ clash-prelude(Monoid instance to support concatenatingNB: Not synthesizableç clash-preludeNB: Not synthesizableÜ clash-preludeA Ñ+ with a number of bits needed to represent aÞ clash-preludeValue to writeJust a writes an a valueNothing puts the port in a high-impedance stateÐÑÒÓÔÕÖרÛÙÚÜÝÞßÑÐØÛÙÚÔÕÖ×ÒÓÝÜÞßÐ(C) 2013-2016, University of Twente, 2016-2019, Myrtle Software, 2017-2022, Google Inc. 2020 , Ben Gamari, 2021-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy &'(/02356789;<>ÀÁÂÇÉÐÑÔÖ×Ùâ컎é clash-preludeClock generator for the ø clock domain.NB*: Should only be used for simulation, and not for the  testBench function. For the  testBench function, used ªê clash-prelude/Reset generator for use in simulation, for the ø5 clock domain. Asserts the reset for a single cycle.NB : While this can be used in the  testBench1 function, it cannot be synthesized to hardware.Example ÈtopEntity :: Vec 2 (Vec 3 (Unsigned 8)) -> Vec 6 (Unsigned 8) topEntity = concat testBench :: Signal System Bool testBench = done where testInput = pure ((1 :> 2 :> 3 :> Nil) :> (4 :> 5 :> 6 :> Nil) :> Nil) expectedOutput = outputVerifier' ((1:>2:>3:>4:>5:>6:>Nil):>Nil) done = exposeClockResetEnable (expectedOutput (topEntity <$> testInput)) clk rst clk = tbSystemClockGen (not <$> done) rst = ê ë clash-preludeThe ë¦ function is a primitive that must be used to connect one clock domain to the other, and will be synthesized to a (bundle of) wire(s) in the eventual circuit. This function should only be used as part of a proper synchronization component, such as the following dual flip-flop synchronizer: ªdualFlipFlop :: Clock domA -> Clock domB -> Enable domA -> Enable domB -> Bit -> Signal domA Bit -> Signal domB Bit dualFlipFlop clkA clkB enA enB dflt = ï clkB enB dflt . ï clkB enB dflt . ë clkA clkB The ë* works in such a way that, given 2 clocks: 7createDomain vSystem{vName="Dom7", vPeriod=7} clk7 :: å Dom7 clk7 = Ä en7 :: é Dom7 en7 = à and 7createDomain vSystem{vName="Dom2", vPeriod=2} clk2 :: å Dom2 clk2 = Ä en2 :: é Dom2 en2 = à ÕOversampling followed by compression is the identity function plus 2 initial values: ï clkB enB dflt $ ë clkA clkB $ ï clkA enA dflt $ ë clkB clkA $ ï# clkB enB s == dflt :- dflt :- s  Something we can easily observe: (oversampling clkA clkB enA enB dflt = ï clkB enB dflt . ë clkA clkB . ï3 clkA enA dflt almostId clkA clkB enA enB dflt = ï clkB enB dflt . ë clkA clkB . ï clkA enA dflt . ë clkB clkA . ï clkB enB dflt ÇsampleN 37 (oversampling clk7 clk2 en7 en2 0 (fromList [(1::Int)..10]))Ï[0,0,1,1,1,2,2,2,2,3,3,3,4,4,4,4,5,5,5,6,6,6,6,7,7,7,8,8,8,8,9,9,9,10,10,10,10]ÃsampleN 12 (almostId clk2 clk7 en2 en7 0 (fromList [(1::Int)..10]))[0,0,1,2,3,4,5,6,7,8,9,10]ì clash-preludeSame as ë+, but with manually supplied clock periods.ëNote: this unsafeSynchronizer is defined to be consistent with the vhdl and verilog implementations however as only synchronous signals are represented in Clash this cannot be done precisely and can lead to odd behavior. For example, sample $ unsafeSynchronizer Dom2 Dom7 . unsafeSynchronizer Dom7 6Dom2 $ fromList [0..10] > [0,4,4,4,7,7,7,7,11,11,11.. %is quite different from the identity, 6sample $ fromList [0..10] > [0,1,2,3,4,5,6,7,8,9,10.. (with values appearing from the "future".í clash-preludeÐMerge enable signal with signal of bools by applying the boolean AND operation.î clash-preludeSpecial version of ïÐ that doesn't take enable signals of any kind. Initial value will be undefined.ï clash-prelude"ï clk s" delays the values in ë s) for once cycle, the value at time 0 is dflt.ÁsampleN 3 (delay systemClockGen enableGen 0 (fromList [1,2,3,4]))[0,1,2]ð clash-prelude Version of ï0 that only updates when its third argument is a K value.Ölet input = fromList [Just 1, Just 2, Nothing, Nothing, Just 5, Just 6, Just (7::Int)]7sampleN 7 (delayMaybe systemClockGen enableGen 0 input)[0,1,2,2,2,5,6]ñ clash-prelude Version of ï7 that only updates when its third argument is asserted.)let input = fromList [1,2,3,4,5,6,7::Int] that only updates its content when its fourth argument is a K value. So given: &sometimes1 clk rst en = s where s = ò clk rst en Nothing (switch Ãé s) switch Nothing = Just 1 switch _ = Nothing countSometimes clk rst en = s where s = ó clk rst en 0 (plusM (! Ã; s) (sometimes1 clk rst en)) plusM = liftA2 (liftA2 (+)) We get:8sampleN 9 (sometimes1 systemClockGen resetGen enableGen)Å[Nothing,Nothing,Just 1,Nothing,Just 1,Nothing,Just 1,Nothing,Just 1]3sampleN 9 (count systemClockGen resetGen enableGen)[0,0,0,1,1,2,2,3,3]ô clash-prelude Version of òÏ that only updates its content when its fourth argument is asserted. So given: oscillate clk rst en = let s = òú clk rst en False (not <$> s) in s count clk rst en = let s = 'regEn clk rst en 0 (oscillate clk rst en) (s + 1) in s We get:7sampleN 9 (oscillate systemClockGen resetGen enableGen)3[False,False,True,False,True,False,True,False,True]3sampleN 9 (count systemClockGen resetGen enableGen)[0,0,0,1,1,2,2,3,3]õ clash-preludeSame as é', but with the reset line asserted for n cycles. Similar to é, õ÷ will drop the output values produced while the reset is asserted. While the reset is asserted, the first value from [a] is fed to the circuit.ö clash-preludeSame as õ, but only sample the first Int output values.÷ clash-prelude Simulate a (… a -> … b,) function given a list of samples of type aüsimulateB (unbundle . register systemClockGen resetGen enableGen (8,8) . bundle) [(1,1), (1,1), (2,2), (3,3)] :: [(Int,Int)]![(8,8),(8,8),(1,1),(2,2),(3,3)......NB$: This function is not synthesizableø clash-preludeLazily simulate a (… a -> … b,) function given a list of samples of type aüsimulateB (unbundle . register systemClockGen resetGen enableGen (8,8) . bundle) [(1,1), (1,1), (2,2), (3,3)] :: [(Int,Int)]![(8,8),(8,8),(1,1),(2,2),(3,3)......NB$: This function is not synthesizableù clash-preludeLike è4, but resets on reset and has a defined reset value.Ñlet rst = unsafeFromActiveHigh (fromList [True, True, False, False, True, False])Îlet res = fromListWithReset @System rst Nothing [Just 'a', Just 'b', Just 'c'] sampleN 6 res4[Nothing,Nothing,Just 'a',Just 'b',Nothing,Just 'a']NB$: This function is not synthesizableú clash-preludeGet a list of samples from a ë&, while asserting the reset line for n clock cycles. ú does not return the first n+ cycles, i.e., when the reset is asserted.NB$: This function is not synthesizableû clash-preludeGet a fine list of m samples from a ë&, while asserting the reset line for n clock cycles. ú does not return the first n, cycles, i.e., while the reset is asserted.NB$: This function is not synthesizableü clash-prelude1Simulate a component until it matches a conditionIt prints a message of the form *Signal sampled for N cycles until value X NB$: This function is not synthesizableExample with test bench+A common usage is with a test bench using ‰.NB: Since this uses �, when using clashi, read the note at &Clash.Explicit.Testbench#assert-clashi. Åimport Clash.Prelude import Clash.Explicit.Testbench topEntity :: ë ø Int -> ë ø$ Int topEntity = id testBench :: ë ø, Bool testBench = done where testInput = ‡ clk rst $(û* [1 :: Int .. 10]) expectedOutput = « clk rst $(û $ [1 :: Int .. 9] = [42]) done = expectedOutput $ topEntity testInput clk = ª (not <$> done) rst = ê  ¥> runUntil id testBench cycle(): 10, outputVerifier expected value: 42, not equal to actual value: 10 Signal sampled for 11 cycles until value True ØWhen you need to verify multiple test benches, the following invocations come in handy: > p* (runUntil id) [ testBenchA, testBenchB ] 8or when the test benches are in different clock domains: >testBenchA :: Signal DomA Bool testBenchB :: Signal DomB Bool > o4 [ runUntil id testBenchA, runUntil id testBenchB ] ë clash-preludeå of the incoming signal clash-preludeå of the outgoing signalì clash-preludePeriod of clock belonging to dom1. M if clock has a static period, N if periods are dynamic. clash-preludePeriod of clock belonging to dom2. M if clock has a static period, N if periods are dynamic.ï clash-preludeClock clash-prelude Global enable clash-prelude Initial valueð clash-preludeClock clash-prelude Global enable clash-prelude Initial valueñ clash-preludeClock clash-prelude Global enable clash-prelude Initial value clash-preludeEnableò clash-preludeclock clash-preludeReset, ò1 outputs the reset value when the reset is active clash-prelude Global enable clash-preludeçReset value. If the domain has initial values enabled, the reset value will also be the initial value.ó clash-preludeClock clash-preludeReset, ó7 outputs the reset value when the reset value is active clash-prelude Global enable clash-preludeçReset value. If the domain has initial values enabled, the reset value will also be the initial value.ô clash-preludeClock clash-preludeReset, ô7 outputs the reset value when the reset value is active clash-prelude Global enable clash-preludeçReset value. If the domain has initial values enabled, the reset value will also be the initial value. clash-prelude Enable signalõ clash-prelude$Number of cycles to assert the reset clash-prelude Reset value clash-preludeCircuit to simulateö clash-prelude$Number of cycles to assert the reset clash-prelude Reset value clash-prelude=Number of cycles to simulate (excluding cycle spent in reset) clash-preludeCircuit to simulate÷ clash-prelude The function we want to simulate clash-prelude Input samplesø clash-prelude The function we want to simulate clash-prelude Input samplesú clash-prelude$Number of cycles to assert the reset clash-preludeë to sampleû clash-prelude$Number of cycles to assert the reset clash-preludeNumber of samples to produce clash-preludeë to sampleü clash-prelude+Condition checking function, should return True to finish run clash-preludeë$ we want to sample for the condition›Üàåéëíîïðñòóôõö÷øùúûüýþÿ€�‚ƒ„…†‡ˆ‰Š‹Œ’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±³´µ¶·ÁÂÃÄÊËÌÍÎÏÐÑÒÓÔÕרÞßàáâãäåæçèéêëìíîðòøùúûüý„…‡†–—˜™ÐÑØÛÙÚÜÝÞßéêëìíîïðñòóôõö÷øùúûü›ëÑÐØÛÙÚíùúûü¯°±¬­®�žŸš›œ©ª«¦§¨£¤¥ ¡¢’“”•–—˜™ýþÿ€�‚ƒ„Œ‹Š‡…‰ˆ†øö÷³´µîïðñòóôõ¶·ýøùúûüéÂÁÃåàðîëìÜÑÐÌÎÓÕíîïðñòóôÞÄÊËéêØ×„…‡†˜™–—é÷õöüíøòæçúûèùêëìåßàáâäãßÜÞÝÒÔÍÏ<¹(C) 2013-2016, University of Twente, 2017 , Google Inc. 2019 , Myrtle Software Ltd 2021 , LUMI GUIDE FIETSDETECTIE B.V.BSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&'(/02356789;<ÁÂÇÉÐÑÖ×ÙâìÉñý clash-preludeDelay a ’  for d periods. Ïdelay3 :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> ’  dom n Int -> ’ % dom (n + 3) Int delay3 clk rst en = ý clk rst en (-1 � -1 � -1 � š) ÆsampleN 7 (delay3 systemClockGen resetGen enableGen (dfromList [0..]))[-1,-1,-1,-1,1,2,3]þ clash-preludeDelay a ’  for d periods, where d is derived from the context. Ødelay2 :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> Int -> ’  dom n Int -> ’  dom (n + 2) Int delay2 = þ ÍsampleN 7 (delay2 systemClockGen resetGen enableGen (-1) (dfromList ([0..])))[-1,-1,-1,1,2,3,4]d. can also be specified using type application::t delayedI @3 delayedI @3 :: ... => Clock dom -> Reset dom -> Enable dom -> a -> DSignal dom n a -> DSignal dom (n + 3) aÿ clash-preludeDelay a ’  for d% cycles, the value at time 0..d-1 is a.  delayN2 :: ù dom => Int -> é dom -> å dom -> ’  dom n Int -> ’  dom (n + 2) Int delayN2 = ÿ d2 ÌprintX $ sampleN 6 (delayN2 (-1) enableGen systemClockGen (dfromList [1..]))[-1,-1,1,2,3,4]€ clash-preludeDelay a ’  for d cycles, where dË is derived from the context. The value at time 0..d-1 is a default value.  delayI2 :: ù dom => Int -> é dom -> å dom -> ’  dom n Int -> ’  dom (n + 2) Int delayI2 = € ÃsampleN 6 (delayI2 (-1) enableGen systemClockGen (dfromList [1..]))[-1,-1,1,2,3,4]1You can also use type application to do the same:ÅsampleN 6 (delayI @2 (-1) enableGen systemClockGen (dfromList [1..]))[-1,-1,1,2,3,4]� clash-preludeTree fold over a à of ’ /s with a combinatorial function, and delaying delayÕ cycles after each application. Values at times 0..(delay*k)-1 are set to a default. ØcountingSignals :: Vec 4 (DSignal dom 0 Int) countingSignals = repeat (dfromList [0..]) ÖprintX $ sampleN 6 (delayedFold d1 (-1) (+) enableGen systemClockGen countingSignals)[-1,-2,0,4,8,12]ÕprintX $ sampleN 8 (delayedFold d2 (-1) (*) enableGen systemClockGen countingSignals)[-1,-1,1,1,0,1,16,81]ý clash-preludeInitial valuesþ clash-prelude Initial valueÿ clash-prelude Initial value€ clash-prelude Initial value� clash-preludeDelay applied after each step clash-prelude Initial value clash-preludeFold operation to apply clash-preludeVector input of size 2^k clash-prelude$Output Signal delayed by (delay * k)’ ” • – — ˜ ™ š › ýþÿ€�’ ýþÿ€�— ˜ ” • – ™ š › =­(C) 2015-2016, University of Twente, 2017 , Google Inc., 2019 , Myrtle Software Ltd., 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe&/02356789;«(C) 2015-2016, University of Twente, 2017 , Google Inc. 2019 , Myrtle Software Ltd, 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789;Safe&/02356789;<ÇÉÐÑÖ×ÙâìèÞˆ clash-prelude×Create a synchronous function from a combinational function describing a moore machine ƒmacT :: Int -- Current state -> (Int,Int) -- Input -> (Int,Int) -- Updated state macT s (x,y) = x * y + s mac :: ù dom => å dom -> Ü dom -> é dom -> ë dom (Int, Int) -> ë dom Int mac clk rst en = ˆ clk rst en macT id 0 Ösimulate (mac systemClockGen systemResetGen enableGen) [(0,0),(1,1),(2,2),(3,3),(4,4)][0,0,1,5,14......ÜSynchronous sequential functions can be composed just like their combinational counterpart:  dualMac :: ù dom => å dom -> Ü dom -> é dom -> (ë dom Int, ë dom Int) -> (ë dom Int, ë dom Int) -> ëà dom Int dualMac clk rst en (a,b) (x,y) = s1 + s2 where s1 = ˆ clk rst en macT id 0 († (a,x)) s2 = ˆ clk rst en macT id 0 († (b,y)) ‰ clash-preludeðCreate a synchronous function from a combinational function describing a moore machine without any output logicŠ clash-prelude A version of ˆ that does automatic „ingGiven a functions t and o of types: t :: Int -> (Bool, Int) -> Int o :: Int -> (Int, Bool) %When we want to make compositions of t and o in g using ˆ, we have to write: 6g clk rst en a b c = (b1,b2,i2) where (i1,b1) = ‡ (moore clk rst en t o 0 († (a,b))) (i2,b2) = ‡ (moore clk rst en t o 3 († (c,i1))) Using Š however we can write: 6g clk rst en a b c = (b1,b2,i2) where (i1,b1) = Š& clk rst en t o 0 (a,b) (i2,b2) = Š clk rst en t o 3 (c,i1) ‹ clash-prelude A version of ‰ that does automatic „ingˆ clash-preludeå to synchronize to clash-prelude)Transfer function in moore machine form: state -> input -> newstate clash-prelude'Output function in moore machine form: state -> output clash-prelude Initial state clash-preludeÙSynchronous sequential function with input and output matching that of the moore machineŠ clash-prelude*Transfer function in moore machine form: state -> input -> newstate clash-prelude(Output function in moore machine form: state -> output clash-prelude Initial state clash-preludeÙSynchronous sequential function with input and output matching that of the moore machineˆ‰Š‹ˆŠ‰‹@¬(C) 2013-2016, University of Twente, 2017 , Google Inc. 2019 , Myrtle Software Ltd 2023 , Alex MasonBSD2 (see the file LICENSE)-Christiaan Baaij Safe&/02356789;<ÇÉÐÑÖ×Ùâìù~Œ clash-prelude×Create a synchronous function from a combinational function describing a mealy machine Æimport qualified Data.List as L macT :: Int -- Current state -> (Int,Int) -- Input -> (Int,Int) -- (Updated state, output) macT s (x,y) = (s',s) where s' = x * y + s mac :: ù dom => å dom -> Ü dom -> é dom -> ë dom (Int, Int) -> ë dom Int mac clk rst en = Œ clk rst en macT 0 Ösimulate (mac systemClockGen systemResetGen enableGen) [(0,0),(1,1),(2,2),(3,3),(4,4)][0,0,1,5,14......ÜSynchronous sequential functions can be composed just like their combinational counterpart:  dualMac :: ù dom => å dom -> Ü dom -> é dom -> (ë dom Int, ë dom Int) -> (ë dom Int, ë dom Int) -> ëà dom Int dualMac clk rst en (a,b) (x,y) = s1 + s2 where s1 = Œ clk rst en macT 0 († (a,x)) s2 = Œ clk rst en macT 0 († (b,y)) � clash-prelude×Create a synchronous function from a combinational function describing a mealy machine using the state monad. This can be particularly useful when combined with lenses or optics to replicate imperative algorithms. Çdata DelayState = DelayState { _history :: Vec 4 Int , _untilValid :: Index 4 } deriving (Generic, NFDataX) makeLenses ''DelayState initialDelayState = DelayState (repeat 0) maxBound delayS :: Int -> State DelayState (Maybe Int) delayS n = do history %= (n +>>) remaining <- use untilValid if remaining > 0 then do untilValid -= 1 return Nothing else do out <- uses history last return (Just out) delayTop ::ù dom => å dom -> Ü dom -> é dom -> (ë dom Int -> ë( dom (Maybe Int)) delayTop clk rst en = �% clk rst en delayS initialDelayState ÝL.take 7 $ simulate (delayTop systemClockGen systemResetGen enableGen) [-100,1,2,3,4,5,6,7,8]6[Nothing,Nothing,Nothing,Nothing,Just 1,Just 2,Just 3]Ž clash-prelude A version of Œ that does automatic „ingGiven a function f of type: f* :: Int -> (Bool,Int) -> (Int,(Int,Bool)) %When we want to make compositions of f in g using Œ, we have to write: 6g clk rst en a b c = (b1,b2,i2) where (i1,b1) = ‡ (mealy clk rst en f 0 († (a,b))) (i2,b2) = ‡ (mealy clk rst en f 3 († (c,i1))) Using Ž however we can write: 6g clk rst en a b c = (b1,b2,i2) where (i1,b1) = Ž$ clk rst en f 0 (a,b) (i2,b2) = Ž clk rst en f 3 (c,i1) � clash-prelude A version of � that does automatic „ ing, see Ž for details.Œ clash-preludeå to synchronize to clash-prelude Global enable clash-prelude)Transfer function in mealy machine form: #state -> input -> (newstate,output) clash-prelude Initial state clash-preludeÙSynchronous sequential function with input and output matching that of the mealy machine� clash-preludeå to synchronize to clash-prelude Global enable clash-prelude9Transfer function in mealy machine handling inputs using Control.Monad.Strict.State s. clash-prelude Initial state clash-preludeÙSynchronous sequential function with input and output matching that of the mealy machineŽ clash-prelude)Transfer function in mealy machine form: #state -> input -> (newstate,output) clash-prelude Initial state clash-preludeÙSynchronous sequential function with input and output matching that of the mealy machine� clash-prelude9Transfer function in mealy machine handling inputs using Control.Monad.Strict.State s. clash-prelude Initial state clash-preludeÙSynchronous sequential function with input and output matching that of the mealy machineŒ�Ž�Œ�Ž�A(C) 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789;<ÇÉÐÑÖ×Ùâì Ü� clash-prelude"Create a block RAM with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an è See also:See  Clash.Prelude.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter C©7 for obtaining write-before-read semantics like this: C© clk rst en (� clk en content) rd wrM.‘ clash-prelude$Create a block RAM with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an è See also:See  Clash.Prelude.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter C©7 for obtaining write-before-read semantics like this: C© clk rst en (‘ clk en content) rd wrM.’ clash-preludeblockRAMBlob primitive“ clash-prelude Create a ï binding from a list of valuesÅSince this uses Template Haskell, nothing in the arguments given to “3 can refer to something defined in the same module.Example “ "content" J( [15 :: Unsigned 8 .. 17] ram clk en = � clk en content The z¬Ä datatype has don't care bits, where the actual value does not matter. But the bits need a defined value in the memory. Either 0 or 1 can be used, and both are valid representations of the data.import qualified Prelude as P4let es = [ Nothing, Just (7 :: Unsigned 8), Just 8 ]:{$createMemBlob "content0" (Just 0) es$createMemBlob "content1" (Just 1) esx = 1:} let pr = mapM_ (putStrLn . show)pr $ P.map pack es 0b0_...._.... 0b1_0000_0111 0b1_0000_1000pr $ unpackMemBlob content0 0b0_0000_0000 0b1_0000_0111 0b1_0000_1000pr $ unpackMemBlob content1 0b0_1111_1111 0b1_0000_0111 0b1_0000_1000:{#createMemBlob "contentN" Nothing esx = 1:}:...: error:...Ü packBVs: cannot convert don't care values. Please specify a mapping to a definite value.Note how we hinted to clashiÚ that our multi-line command was a list of declarations by including a dummy declaration x = 1. Without this trick, clashiÄ would expect an expression and the Template Haskell would not work.” clash-prelude Create a ï from a list of valuesÅSince this uses Template Haskell, nothing in the arguments given to ”3 can refer to something defined in the same module.Example  ram clk en = �6 clk en $(memBlobTH Nothing [15 :: Unsigned 8 .. 17]) The z¬Ä datatype has don't care bits, where the actual value does not matter. But the bits need a defined value in the memory. Either 0 or 1 can be used, and both are valid representations of the data. import qualified Prelude as P4let es = [ Nothing, Just (7 :: Unsigned 8), Just 8 ]#content0 = $(memBlobTH (Just 0) es)#content1 = $(memBlobTH (Just 1) es) let pr = mapM_ (putStrLn . show)pr $ P.map pack es 0b0_...._.... 0b1_0000_0111 0b1_0000_1000pr $ unpackMemBlob content0 0b0_0000_0000 0b1_0000_0111 0b1_0000_1000pr $ unpackMemBlob content1 0b0_1111_1111 0b1_0000_0111 0b1_0000_1000$(memBlobTH Nothing es):...: error:...Þ ¢@ packBVs: cannot convert don't care values. Please specify a mapping to a definite value.4 ¢@ In the untyped splice: $(memBlobTH Nothing es)� clash-preludeå to synchronize to clash-preludeé line clash-prelude7Initial content of the BRAM, also determines the size, n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle‘ clash-preludeå to synchronize to clash-preludeé line clash-prelude9Initial content of the BRAM, also determines the size, 2^n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle’ clash-preludeå to synchronize to clash-preludeé line clash-prelude7Initial content of the BRAM, also determines the size, n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle“ clash-preludeName of the binding to generate clash-prelude!Value to map don't care bits to. J- means throwing an error on don't care bits. clash-preludeThe content for the ï” clash-prelude!Value to map don't care bits to. J- means throwing an error on don't care bits. clash-preludeThe content for the ïïõ�‘’“”�‘ï“”õ’B(C) 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789;<ÇÉÐÑÖ×Ùâìl• clash-prelude3A ROM with a synchronous read port, with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an Ÿ See also:See #Clash.Sized.Fixed#creatingdatafiles and !Clash.Explicit.BlockRam#usingrams' for ideas on how to use ROMs and RAMs.– clash-prelude5A ROM with a synchronous read port, with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an Ÿ See also:See #Clash.Sized.Fixed#creatingdatafiles and !Clash.Explicit.BlockRam#usingrams' for ideas on how to use ROMs and RAMs.— clash-prelude ROM primitive• clash-preludeå to synchronize to clash-preludeé line clash-prelude'ROM content, also determines the size, n , of the ROMNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle– clash-preludeå to synchronize to clash-preludeé line clash-prelude)ROM content, also determines the size, 2^n , of the ROMNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle— clash-preludeå to synchronize to clash-preludeé line clash-prelude'ROM content, also determines the size, n , of the ROMNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycleïõ“”•–—•–ï“”õ—C×(C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , Google Inc., 2021-2023, QBayLogic B.V., 2022 , Google Inc.,BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&'(/02356789:;<ÇÉÐÑÖ×Ùâì2˜ clash-preludePort operation™ clash-preludeRead from addressš clash-preludeWrite data to address› clash-prelude No operationŸ clash-prelude"Create a block RAM with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an è See also:See !Clash.Explicit.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter ¦7 for obtaining write-before-read semantics like this: ¦ clk rst en (Ÿ clk inits) rd wrM.A large ÃÚ for the initial content may be too inefficient, depending on how it is constructed. See 8­ and A®+ for different approaches that scale well.Example  bram40 :: å dom -> é dom -> ë dom (˜ 6) -> ë dom (Maybe (˜ 6, •)) -> ë dom • bram40 clk en = Ÿ clk en (â d40 1)   clash-prelude$Create a block RAM with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an è See also:See  Clash.Prelude.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter ¦7 for obtaining write-before-read semantics like this: ¦ clk rst en (  clk inits) rd wrM.A large ÃÚ for the initial content may be too inefficient, depending on how it is constructed. See 8¯ and A°+ for different approaches that scale well.Example  bram32 :: å dom -> é dom -> ë dom (˜ 5) -> ë dom (Maybe (˜ 5, •)) -> ë dom • bram32 clk en =   clk en (â d32 1) ¡ clash-prelude A version of ŸÞ that has no default values set. May be cleared to an arbitrary state using a reset function.¢ clash-preludeblockRAMU primitive£ clash-prelude A version of ŸÁ that is initialized with the same value on all memory positions¤ clash-preludeblockRAM1 primitive¥ clash-preludeblockRAM primitive¦ clash-preludeÀCreate a read-after-write block RAM from a read-before-write one§ clash-preludeÑProduces vendor-agnostic HDL that will be inferred as a true dual-port block RAM£Any value that is being written on a particular port is also the value that will be read on that port, i.e. the same-port read/write behavior is: WriteFirst. For mixed-port read/write, when port A writes to the address port B reads from, the output of port B is undefined, and vice versa.¨ clash-preludePrimitive for § Ÿ clash-preludeå to synchronize to clash-preludeé line clash-prelude7Initial content of the BRAM, also determines the size, n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle  clash-preludeå to synchronize to clash-preludeé line clash-preludeInitial content of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude(Write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle¡  clash-preludeå to synchronize to clash-preludeÜ. line. This needs to be asserted for at least nÀ cycles in order for the BRAM to be reset to its initial state. clash-preludeé line clash-prelude)Whether to clear BRAM on asserted reset (� ) or not (ž/). The reset needs to be asserted for at least n cycles to clear the BRAM. clash-preludeNumber of elements in BRAM clash-preludeIf applicable (see œ* argument), reset BRAM using this function clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle¢ clash-preludeå to synchronize to clash-preludeé line clash-preludeNumber of elements in BRAM clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle£  clash-preludeå to synchronize to clash-preludeÜ. line. This needs to be asserted for at least nÀ cycles in order for the BRAM to be reset to its initial state. clash-preludeé line clash-prelude)Whether to clear BRAM on asserted reset (� ) or not (ž/). The reset needs to be asserted for at least n cycles to clear the BRAM. clash-preludeNumber of elements in BRAM clash-prelude(Initial content of the BRAM (replicated n times) clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle¤  clash-preludeå to synchronize to clash-preludeé line clash-preludeNumber of elements in BRAM clash-prelude(Initial content of the BRAM (replicated n times) clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle¥ clash-preludeå to synchronize to clash-preludeé line clash-prelude7Initial content of the BRAM, also determines the size, n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle¦ clash-preludeThe BRAM component clash-prelude Read address r clash-prelude(Write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle§ clash-preludeClock for port A clash-preludeClock for port B clash-preludeRAM operation for port A clash-preludeRAM operation for port B clash-preludeOutputs data on nextà cycle. When writing, the data written will be echoed. When reading, the read data is returned.¨ clash-preludeEnable clash-prelude Write enable clash-preludeAddress clash-prelude Write data clash-preludeEnable clash-prelude Write enable clash-preludeAddress  clash-prelude Write data˜™š›œ�žŸ ¡¢£¤¥¦§¨Ÿ ¡£œ�ž¦§˜™š›¥¢¤¨D¯(C) 2015-2016, University of Twente, 2016-2019, Myrtle Software Ltd, 2017 , Google Inc., 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Safe&/02356789;<ÇÉÐÑÖ×Ùâì<ú¬ clash-preludeNone&/02356789:;<>ÀÇÉÐÑÖ×ÙâìfÖ ® clash-preludeA reset that is never asserted¯ clash-preludeÎOutput reset will be asserted when either one of the input resets is asserted° clash-prelude†Output reset will be asserted when either one of the input resets is asserted. This function is considered unsafe because it can be used on domains with components with asynchronous resets, where use of this function can introduce glitches triggering a reset.± clash-preludeÁOutput reset will be asserted when both input resets are asserted² clash-preludeúOutput reset will be asserted when both input resets are asserted. This function is considered unsafe because it can be used on domains with components with asynchronous resets, where use of this function can introduce glitches triggering a reset.³ clash-preludeùThe resetSynchronizer will synchronize an incoming reset according to whether the domain is synchronous or asynchronous.âFor asynchronous resets this synchronizer ensures the reset will only be de-asserted synchronously but it can still be asserted asynchronously. The reset assert is immediate, but reset de-assertion is delayed by two cycles.ÐNormally, asynchronous resets can be both asynchronously asserted and de-asserted. Asynchronous de-assertion can induce meta-stability in the component which is being reset. To ensure this doesn't happen, ³ê ensures that de-assertion of a reset happens synchronously. Assertion of the reset remains asynchronous.¸Note that asynchronous assertion does not induce meta-stability in the component whose reset is asserted. However, when a component "A" in another clock or reset domain depends on the value of a component "B" being reset, then asynchronous assertion of the reset of component "B" can induce meta-stability in component "A". To prevent this from happening you need to use a proper synchronizer, for example one of the synchronizers in Clash.Explicit.Synchronizer.´For synchronous resets this function ensures that the reset is asserted and de-asserted synchronously. Both the assertion and de-assertion of the reset are delayed by two cycles. Example 1ÈThe circuit below detects a rising bit (i.e., a transition from 0 to 1) in a given argument. It takes a reset that is not synchronized to any of the other incoming signals and synchronizes it using ³. ÅtopEntity :: Clock System -> Reset System -> Signal System Bit -> Signal System (BitVector 8) topEntity clk asyncRst key1 = withClockResetEnable clk rst enableGen leds where rst = ³Õ clk asyncRst key1R = isRising 1 key1 leds = mealy blinkerT (1, False, 0) key1R  Example 2 Similar to  Example 1… this circuit detects a rising bit (i.e., a transition from 0 to 1) in a given argument. It takes a clock that is not stable yet and a reset signal that is not synchronized to any other signals. It stabilizes the clock and then synchronizes the reset signal.Note that the function H±Ì provides this functionality in a convenient form, obviating the need for resetSynchronizer for this use case. ÒtopEntity :: Clock System -> Reset System -> Signal System Bit -> Signal System (BitVector 8) topEntity clk rst key1 = let (pllOut,pllStable) = unsafeAltpll clk rst rstSync = ³» pllOut (unsafeFromActiveLow pllStable) in exposeClockResetEnable leds pllOut rstSync enableGen where key1R = isRising 1 key1 leds = mealy blinkerT (1, False, 0) key1R Implementation details³; implements the following circuit for asynchronous domains: Ž rst --------------------------------------+ | | +----v----+ +----v----+ deasserted | | | | ---------------> +-------> +--------> | | | | +---|> | +---|> | | | | | | | | +---------+ | +---------+ clk | | -----------------------------+ !This corresponds to figure 3d at æhttps://www.embedded.com/asynchronous-reset-synchronization-and-distribution-challenges-and-solutions/;For synchronous domains two sequential dflipflops are used: ” +---------+ +---------+ rst | | | | ---------------> +-------> +--------> | | | | +---|> | +---|> | | | | | | | | +---------+ | +---------+ clk | | -----------------------------+ ´ clash-preludeÞFilter glitches from reset signals by only triggering a reset after it has been asserted for glitchlessPeriod3 cycles. Similarly, it will stay asserted until a glitchlessPeriod1 number of deasserted cycles have been observed.öThis circuit can only be used on platforms supporting initial values. This restriction can be worked around by using µ but this is not recommended.=On platforms without initial values, you should instead use ¶( with an additional power-on reset, or ·, if filtering is only needed on deassertion.ÿAt power-on, the reset will be asserted. If the filtered reset input remains unasserted, the output reset will deassert after glitchlessPeriod clock cycles.If resetGlitchFilter0 is used in a domain with asynchronous resets (ª), resetGlitchFilter. will first synchronize the reset input with ¬. Example 13let sampleResetN n = sampleN n . unsafeToActiveHigh3let resetFromList = unsafeFromActiveHigh . fromListålet rst = resetFromList [True, True, False, False, True, False, False, True, True, False, True, True]ÃsampleResetN 12 (resetGlitchFilter d2 (clockGen @XilinxSystem) rst)Â[True,True,True,True,False,False,False,False,False,True,True,True]µ clash-preludeÞFilter glitches from reset signals by only triggering a reset after it has been asserted for glitchlessPeriod3 cycles. Similarly, it will stay asserted until a glitchlessPeriod1 number of deasserted cycles have been observed.%On platforms without initial values (ž), ´$ cannot be used and you should use ¶( with an additional power-on reset, or ·, if filtering is only needed on deassertion.unsafeResetGlitchFilter† allows breaking the requirement of initial values, but by doing so it is possible that the design starts up with a period of up to 2 * glitchlessPeriodå clock cycles where the reset output is unasserted (or longer in the case of glitches on the filtered reset input). This can cause a number of problems. The outputs/tri-states of the design might output random things, including coherent but incorrect streams of data. This might have grave repercussions in the design's environment (sending network packets, overwriting non-volatile memory, in extreme cases destroying controlled equipment or causing harm to living beings, ...).2Without initial values, the synthesized result of unsafeResetGlitchFilterû eventually correctly outputs a filtered version of the reset input. However, in simulation, it will indefinitely output an undefined value. This happens both in Clash simulation and in HDL simulation. Therefore, simulation should not include the unsafeResetGlitchFilter.If unsafeResetGlitchFilter0 is used in a domain with asynchronous resets (ª), unsafeResetGlitchFilter. will first synchronize the reset input with ¬.¶ clash-preludeÞFilter glitches from reset signals by only triggering a reset after it has been asserted for glitchlessPeriod3 cycles. Similarly, it will stay asserted until a glitchlessPeriod1 number of deasserted cycles have been observed. Compared to ´Ù, this function adds an additional power-on reset input. As soon as the power-on reset asserts, the reset output will assert, and after the power-on reset deasserts, the reset output will stay asserted for another glitchlessPeriod. clock cycles. This is identical behavior to ·÷ where it concerns the power-on reset, and differs from the filtered reset, which will only cause an assertion after glitchlessPeriod cycles.If resetGlitchFilterWithReset0 is used in a domain with asynchronous resets (ª), resetGlitchFilterWithReset. will first synchronize the reset input with ¬.· clash-preludeÇHold reset for a number of cycles relative to an incoming reset signal.Example:4let sampleWithReset = sampleN 8 . unsafeToActiveHighÖsampleWithReset (holdReset @System clockGen enableGen (SNat @2) (resetGenN (SNat @3))),[True,True,True,True,True,False,False,False]·î holds the reset for an additional 2 clock cycles for a total of 5 clock cycles where the reset is asserted. ·< also works on intermediate assertions of the reset signal:Élet rst = fromList [True, False, False, False, True, False, False, False]ÛsampleWithReset (holdReset @System clockGen enableGen (SNat @2) (unsafeFromActiveHigh rst))+[True,True,True,False,True,True,True,False]¸ clash-preludeèConvert between different types of reset, adding a synchronizer when the domains are not the same. See ³2 for further details about reset synchronization.If domA has «$ resets, a flip-flop is inserted in domA$ to filter glitches. This adds one domA clock cycle delay.´ clash-preludeÚConsider a reset signal to be properly asserted after having seen the reset asserted for glitchlessPeriod cycles straight.µ clash-preludeÚConsider a reset signal to be properly asserted after having seen the reset asserted for glitchlessPeriod cycles straight.¶ clash-preludeÚConsider a reset signal to be properly asserted after having seen the reset asserted for glitchlessPeriod cycles straight. clash-prelude/The power-on reset for the glitch filter itself clash-preludeThe reset that will be filtered· clash-prelude Global enable clash-prelude Hold for nÐ cycles, counting from the moment the incoming reset signal becomes deasserted. clash-preludeReset to extendÜÊËÌÍÎÏÐÑÒÓÔÕúꮯ°±²³´µ¶·¸³´¶µ·¸®±²¯°ÜÊËúêÑÐÌÎÓÕÒÔÍϲö(C) 2018-2022, Google Inc 2019, Myrtle Software Ltd 2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<ÁÇÉÐÑÖ×Ùâìi�¹ clash-preludeNB/: The documentation only shows instances up to 3; output clocks. By default, instances up to and including 18 clocks will exist.½ clash-preludeNB/: The documentation only shows instances up to 3; output clocks. By default, instances up to and including 18 clocks will exist. ¹º»¼½¾¿À’“Fì(C) 2018, Google Inc 2019, Myrtle Software Ltd 2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&-/02356789;<>?ÀÇÉÐÑÖ×Ùâìjš ¹º»¼½¾¿ÀÁ ½¾¿À¹º»¼ÂÁG<(C) 2017, Google Inc, 2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&'(/02356789;None&/02356789; Trustworthy &'(-/02356789; Vec 6 (Unsigned 8) topEntity = concat testBench :: Signal System Bool testBench = done where testInput = pure ((1 :> 2 :> 3 :> Nil) :> (4 :> 5 :> 6 :> Nil) :> Nil) expectedOutput = outputVerifier' ((1:>2:>3:>4:>5:>6:>Nil):>Nil) done = exposeClockResetEnable (expectedOutput (topEntity <$> testInput)) clk rst en clk = tbSystemClockGen (not <$> done) rst = systemResetGen en = enableGen ‡ clash-prelude Hide the å, Ü, and é= arguments of a component, so they can be routed implicitly. %Clash-Signal.html#hiddenclockandresetÀClick here to read more about hidden clocks, resets, and enablesˆ clash-preludeConnect an explicit å, Ü, and é to a function with a hidden å, Ü, and é. # 1550 "srcClash Signal.hs" %Clash-Signal.html#hiddenclockandresetÀClick here to read more about hidden clocks, resets, and enablesExample Usage with a  polymorphic domain:reg = register 5 (reg + 1):sig = withClockResetEnable clockGen resetGen enableGen regsampleN @System 10 sig[5,5,6,7,8,9,10,11,12,13]Force ˆ to work on ø (hence ‘' not needing an explicit domain later):reg = register 5 (reg + 1)Âsig = withClockResetEnable @System clockGen resetGen enableGen regsampleN 10 sig[5,5,6,7,8,9,10,11,12,13]‰ clash-preludeSpecial version of ŠÐ that doesn't take enable signals of any kind. Initial value will be undefined.Š clash-preludeŠ dflt s delays the values in ë s) for once cycle, the value at time 0 is dflt.0sampleN @System 3 (delay 0 (fromList [1,2,3,4]))[0,1,2]‹ clash-prelude Version of Š1 that only updates when its second argument is a K value.Ölet input = fromList [Just 1, Just 2, Nothing, Nothing, Just 5, Just 6, Just (7::Int)]&sampleN @System 7 (delayMaybe 0 input)[0,1,2,2,2,5,6]Œ clash-prelude Version of Š8 that only updates when its second argument is asserted.)let input = fromList [1,2,3,4,5,6,7::Int] that only updates its content when its second argument is a K value. So given: sometimes1 = s where s = � Nothing (switch ÃÞ s) switch Nothing = Just 1 switch _ = Nothing countSometimes = s where s = Ž 0 (plusM (! à s) sometimes1) plusM = ´µ (liftA2 (+)) We get:sampleN @System 9 sometimes1Å[Nothing,Nothing,Just 1,Nothing,Just 1,Nothing,Just 1,Nothing,Just 1] sampleN @System 9 countSometimes[0,0,0,1,1,2,2,3,3]� clash-prelude Version of �Ï that only updates its content when its second argument is asserted. So given:  oscillate = � False (” à oscillate) count = � 0 oscillate (count + 1) We get:sampleN @System 9 oscillate3[False,False,True,False,True,False,True,False,True]sampleN @System 9 count[0,0,0,1,1,2,2,3,3]� clash-prelude'Get an infinite list of samples from a ë9The elements in the list correspond to the values of the ë at consecutive clock cycles  sample s == [s0, s1, s2, s3, ...ÏIf the given component has not yet been given a clock, reset, or enable line, �à will supply them. The reset will be asserted for a single cycle. �¡ will not drop the value produced by the circuit while the reset was asserted. If you want this, or if you want more than a single cycle reset, consider using ’.NB$: This function is not synthesizable‘ clash-preludeGet a list of n samples from a ë9The elements in the list correspond to the values of the ë at consecutive clock cycles #sampleN @System 3 s == [s0, s1, s2]ÏIf the given component has not yet been given a clock, reset, or enable line, ‘à will supply them. The reset will be asserted for a single cycle. ‘¡ will not drop the value produced by the circuit while the reset was asserted. If you want this, or if you want more than a single cycle reset, consider using “.NB$: This function is not synthesizable’ clash-prelude'Get an infinite list of samples from a ë&, while asserting the reset line for m clock cycles. ’ does not return the first m+ cycles, i.e., when the reset is asserted.NB$: This function is not synthesizable“ clash-preludeGet a list of n samples from a ë&, while asserting the reset line for m clock cycles. ’ does not return the first m, cycles, i.e., while the reset is asserted.NB$: This function is not synthesizable” clash-preludeLazily( get an infinite list of samples from a ë9The elements in the list correspond to the values of the ë at consecutive clock cycles  sample s == [s0, s1, s2, s3, ...ÏIf the given component has not yet been given a clock, reset, or enable line, ”à will supply them. The reset will be asserted for a single cycle. ”Ï will not drop the value produced by the circuit while the reset was asserted.NB$: This function is not synthesizable• clash-preludeLazily get a list of n samples from a ë9The elements in the list correspond to the values of the ë at consecutive clock cycles #sampleN @System 3 s == [s0, s1, s2]ÏIf the given component has not yet been given a clock, reset, or enable line, •à will supply them. The reset will be asserted for a single cycle. •Ï will not drop the value produced by the circuit while the reset was asserted.NB$: This function is not synthesizable– clash-prelude Simulate a (ë a -> ë b,) function given a list of samples of type a'simulate @System (register 8) [1, 2, 3] [8,1,2,3......Where ø denotes the domain¼ to simulate on. The reset line is asserted for a single cycle. The first value is therefore supplied twice to the circuit: once while reset is high, and once directly after. The first outputà value (the value produced while the reset is asserted) is dropped.=If you only want to simulate a finite number of samples, see —ï. If you need the reset line to be asserted for more than one cycle or if you need a custom reset value, see ˜ and ™.NB$: This function is not synthesizable— clash-preludeSame as –, but only sample the first Int output values.NB$: This function is not synthesizable˜ clash-preludeSame as –', but with the reset line asserted for n cycles. Similar to –, ˜ñ will drop the output values produced while the reset is asserted. While the reset is asserted, the reset value a is supplied to the circuit.™ clash-preludeSame as ˜, but only sample the first Int output values.š clash-preludeLazily simulate a (ë a -> ë b,) function given a list of samples of type a'simulate @System (register 8) [1, 2, 3] [8,1,2,3......NB$: This function is not synthesizable› clash-prelude Simulate a (… a -> … b,) function given a list of samples of type aÛsimulateB @System (unbundle . register (8,8) . bundle) [(1,1), (2,2), (3,3)] :: [(Int,Int)][(8,8),(1,1),(2,2),(3,3)......NB$: This function is not synthesizableœ clash-preludeLazily simulate a (… a -> … b,) function given a list of samples of type aÛsimulateB @System (unbundle . register (8,8) . bundle) [(1,1), (2,2), (3,3)] :: [(Int,Int)][(8,8),(1,1),(2,2),(3,3)......NB$: This function is not synthesizable� clash-prelude1Simulate a component until it matches a conditionÏIf the given component has not yet been given a clock, reset, or enable line, � will supply them. The reset will be asserted for a single cycle.It prints a message of the form *Signal sampled for N cycles until value X NB$: This function is not synthesizableExample with test bench+A common usage is with a test bench using ‰.NB: Since this uses �, when using clashi, read the note at &Clash.Explicit.Testbench#assert-clashi. Åimport Clash.Prelude import Clash.Explicit.Testbench topEntity :: ë ø Int -> ë ø$ Int topEntity = id testBench :: ë ø, Bool testBench = done where testInput = ‡ clk rst $(ˆ* [1 :: Int .. 10]) expectedOutput = « clk rst $(ˆ $ [1 :: Int .. 9] = [42]) done = expectedOutput $ topEntity testInput clk = ª (not <$> done) rst = ê  ¥> runUntil id testBench cycle(): 10, outputVerifier expected value: 42, not equal to actual value: 10 Signal sampled for 11 cycles until value True ØWhen you need to verify multiple test benches, the following invocations come in handy: > p* (runUntil id) [ testBenchA, testBenchB ] 8or when the test benches are in different clock domains: >testBenchA :: Signal DomA Bool testBenchB :: Signal DomB Bool > o4 [ runUntil id testBenchA, runUntil id testBenchB ] ž clash-prelude testFor n s tests the signal s for n cycles.NB$: This function is not synthesizableŸ clash-preludeÇHold reset for a number of cycles relative to an implicit reset signal.Example: