clash-ghc 1.10.3 → 1.10.4
raw patch · 9 files changed
+291/−128 lines, 9 filesdep ~clash-libdep ~clash-preludePVP: major bump suggested
API removals or changes: PVP suggests a major version bump
Dependency ranges changed: clash-lib, clash-prelude
API changes (from Hackage documentation)
- Clash.GHC.LoadModules: instance GHC.Exception.Type.Exception Clash.GHC.LoadModules.LoadModulesException
- Clash.GHC.LoadModules: instance GHC.Show.Show Clash.GHC.LoadModules.LoadModulesException
- Clash.GHC.Evaluator: scrutinise :: Value -> Type -> [Alt] -> Machine -> Machine
+ Clash.GHC.Evaluator: scrutinise :: TyConMap -> Value -> Type -> [Alt] -> Machine -> Machine
- Clash.GHC.Evaluator: substInAlt :: DataCon -> [TyVar] -> [Id] -> [Either Term Type] -> Term -> Term
+ Clash.GHC.Evaluator: substInAlt :: DataCon -> [TyVar] -> [Id] -> [Type] -> [Term] -> Term -> Term
Files
- CHANGELOG.md +62/−0
- clash-ghc.cabal +3/−3
- src-ghc/Clash/GHC/Evaluator.hs +26/−15
- src-ghc/Clash/GHC/Evaluator/Primitive.hs +10/−9
- src-ghc/Clash/GHC/GHC2Core.hs +101/−11
- src-ghc/Clash/GHC/GenerateBindings.hs +5/−5
- src-ghc/Clash/GHC/LoadInterfaceFiles.hs +7/−5
- src-ghc/Clash/GHC/LoadModules.hs +48/−55
- src-ghc/Clash/GHC/Util.hs +29/−25
CHANGELOG.md view
@@ -1,5 +1,67 @@ # Changelog for the Clash project +## 1.10.4 - *17 Nov, 2026*++### Changed:++- Clash now derives more names in the generated HDL from the source code:++ * Arguments of data constructors are named after the record field they are passed to, e.g. `c$baudCount` instead of `c$app_arg` for the second field of `Tx { txState, baudCount }`.+ * Arguments of functions are named after the function and its parameter, e.g. `c$txStep_s` for the state of `mealy txStep`.+ * Case alternatives are named after the constructor they match, e.g. `c$x_case_Idle` instead of `c$x_case_alt` for the alternative `Idle -> ...` of `x = case s of ...`.+ * Pattern bindings such as `(nextState, output) = ...` are named after their variables, e.g. `nextState_output` instead of `ds`.+ * Variables made up by GHC, such as `eta`, are named after the parameter of the user-defined function they're passed to. This also names ports of top entities without a `Synthesize` annotation.+ * User-written names are kept when they are aliases of variables Clash made up. For example, `dSCL` in `let dSCL = fst _dI2C` now names the register holding that field.++ [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Fields of SystemVerilog structs for records are now named after the record fields, e.g. `baudCount` instead of `Tx_sel1` for the field `baudCount` of a record `Tx`. When a record field isn't a valid SystemVerilog identifier, such as a keyword like `input` or a name with a `'`, the struct's fields are named like `Tx_sel1_baudCount` instead. Fields of tuples and other products without field names keep names like `Tuple2_sel0`.+ [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Removing unused declarations no longer shuffles the order of the remaining declarations in the generated HDL.+ [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Comparing constructors of enumerations with derived `==`, such as `mode == Done`, no longer produces an `Int`-wide signal named `c$case_scrut` in the HDL.+ [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Alternatives of case statements in the generated HDL now mention the constructor they match in a comment, e.g. `2'b00 : busy = 1'b0; // Idle`.+ [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Signals holding a record field that the HDL matches on are now named after the record and the field, e.g. `s_mode` for the field `mode` of a signal `s`.+ [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Clash now reports errors in the module it compiles directly, instead of wrapping them in a message about loading the module from both precompiled and local sources.+ [#2365](https://github.com/clash-lang/clash-compiler/issues/2365) [#2680](https://github.com/clash-lang/clash-compiler/issues/2680)+- Improved the documentation on converting between number types.+ [#3537](https://github.com/clash-lang/clash-compiler/pull/3537)+- The error for an inline primitive with a mismatched name now points at the annotated function.+ [#2365](https://github.com/clash-lang/clash-compiler/issues/2365)++### Fixed:++- Clash's internal `split#` unfolding now returns zero for zero-width halves, matching its Haskell counterpart.+ [#3490](https://github.com/clash-lang/clash-compiler/pull/3490)+- `GHC.Num.Integer.integerLogBase#` and `GHC.Num.Natural.naturalLogBase#` are now constant folded accurately, even in cases where these functions return errors.+ [#3492](https://github.com/clash-lang/clash-compiler/pull/3492)+- Unhandled `error` calls are reported with their `HasCallStack` backtrace again on GHC 9.12 and later.+ [#3449](https://github.com/clash-lang/clash-compiler/pull/3449)+- Errors raised while compiling top entities concurrently now report the backtrace they were thrown with, instead of one pointing into `async`.+ [#3449](https://github.com/clash-lang/clash-compiler/pull/3449)+- Clash no longer takes quadratic or exponential time to compile designs that use `iterateI` with a function that inspects its argument more than once, e.g. `iterateI (\(Just n) -> if n == maxBound then Nothing else Just (n + 1)) (Just 0)`, when the resulting vector is consumed by functions such as `takeI` or `foldr`.+ [#3477](https://github.com/clash-lang/clash-compiler/issues/3477) [#3539](https://github.com/clash-lang/clash-compiler/pull/3539)+- Clash now reports an error when `clash-lib`'s `mkFunInput` gets called with a local variable as its function input.+ [#3499](https://github.com/clash-lang/clash-compiler/pull/3499)+- The VHDL backend now generates valid VHDL for entities without ports, such as a top entity whose ports are all zero-width. This can be helpful when creating self-contained VHDL test benches.+ [#3500](https://github.com/clash-lang/clash-compiler/pull/3500)+- Clash's evaluator no longer produces an `SNat` newtype constructor when evaluating `withSomeSNat`.+ [#3491](https://github.com/clash-lang/clash-compiler/pull/3491)+- Clash no longer crashes on `iterateI` with functions such as `map f` or `resize`.+ [#3495](https://github.com/clash-lang/clash-compiler/issues/3495)+- Constant `BitVector` indices in Verilog and SystemVerilog are now rendered as plain integers, avoiding `64'sd` prefixes that caused warnings in tools such as Verilator.+ [#3056](https://github.com/clash-lang/clash-compiler/issues/3056)+- Clash no longer duplicates components whose result is projected out of more than once.+ [#3517](https://github.com/clash-lang/clash-compiler/issues/3517) [#3519](https://github.com/clash-lang/clash-compiler/pull/3519)+- Clash no longer duplicates components when applying a primitive to another instantiation of a primitive in certain situations.+ [#3516](https://github.com/clash-lang/clash-compiler/issues/3516) [#3518](https://github.com/clash-lang/clash-compiler/pull/3518)+- Clash now reports a clear error for functions returning a non-representable type that it can't inline away.+ [#3521](https://github.com/clash-lang/clash-compiler/issues/3521)+- Generating Verilog or SystemVerilog for `BitVector` indexing now uses the built-in blackbox function directly, avoiding unnecessary interpreter sessions that slowed compilation and could crash the compiler.+ [#3522](https://github.com/clash-lang/clash-compiler/pull/3522)+ ## 1.10.3 - *14 Oct, 2026* ### Added:
clash-ghc.cabal view
@@ -1,6 +1,6 @@ Cabal-version: 2.2 Name: clash-ghc-Version: 1.10.3+Version: 1.10.4 Synopsis: Clash: a functional hardware description language - GHC frontend Description: Clash is a functional hardware description language that borrows both its@@ -176,8 +176,8 @@ text >= 1.2.2 && < 2.2, transformers >= 0.5.2.0 && < 0.7, unordered-containers >= 0.2.1.0 && < 0.3,- clash-lib == 1.10.3,- clash-prelude == 1.10.3,+ clash-lib == 1.10.4,+ clash-prelude == 1.10.4, ghc-typelits-extra, ghc-typelits-knownnat, ghc-typelits-natnormalise,
src-ghc/Clash/GHC/Evaluator.hs view
@@ -310,7 +310,7 @@ go (Apply x) = return . apply tcm v x go (Instantiate ty) = return . instantiate tcm v ty go (PrimApply p tys vs tms) = ghcPrimUnwind tcm p tys vs v tms- go (Scrutinise altTy as) = return . scrutinise v altTy as+ go (Scrutinise altTy as) = return . scrutinise tcm v altTy as go (Tickish _) = return . setTerm (valToTerm v) -- | Update the Heap with the evaluated term@@ -372,15 +372,15 @@ instantiate _ p _ _ = error $ "Evaluator.instantiate: Not a tylambda: " ++ show p -- | Evaluate a case-expression-scrutinise :: Value -> Type -> [Alt] -> Machine -> Machine-scrutinise v _altTy [] m = setTerm (valToTerm v) m+scrutinise :: TyConMap -> Value -> Type -> [Alt] -> Machine -> Machine+scrutinise _tcm v _altTy [] m = setTerm (valToTerm v) m -- [Note: empty case expressions] -- -- Clash does not have empty case-expressions; instead, empty case-expressions -- are used to indicate that the `whnf` function was called the context of a -- case-expression, which means certain special primitives must be forced. -- See also [Note: forcing special primitives]-scrutinise (Lit l) _altTy alts m = case alts of+scrutinise _tcm (Lit l) _altTy alts m = case alts of (DefaultPat, altE):alts1 -> setTerm (go altE alts1) m _ -> let term = go (error $ "Evaluator.scrutinise: no match " <> showPpr (Case (valToTerm (Lit l)) (ConstTy Arrow) alts)) alts@@ -421,13 +421,26 @@ in substTm "Evaluator.scrutinise" subst1 altE go def (_:alts1) = go def alts1 -scrutinise (DC dc xs) _altTy alts m- | altE:_ <- [substInAlt altDc tvs pxs xs altE- | (DataPat altDc tvs pxs,altE) <- alts, altDc == dc ] ++- [altE | (DefaultPat,altE) <- alts ]- = setTerm altE m+scrutinise tcm (DC dc xs) _altTy alts m+ | (m1,altE):_ <- [ bindFields altDc tvs pxs altE+ | (DataPat altDc tvs pxs,altE) <- alts, altDc == dc ] +++ [ (m,altE) | (DefaultPat,altE) <- alts ]+ = setTerm altE m1+ where+ -- Bind the fields used by the alternative on the heap instead of+ -- substituting them into it, so they are evaluated at most once.+ bindFields altDc tvs pxs altE =+ let altFvs = freeVarsOf altE+ (m1,tms) = mapAccumL (bindField altFvs) m (zip pxs (lefts xs))+ in (m1, substInAlt altDc tvs pxs (rights xs) tms altE) -scrutinise v@(PrimVal p _ vs) altTy alts m+ bindField altFvs m0 (x,tm)+ | x `elemVarSet` altFvs+ = Var <$> newLetBinding tcm m0 tm+ | otherwise+ = (m0,tm)++scrutinise _tcm v@(PrimVal p _ vs) altTy alts m | isUndefinedXPrimVal v = setTerm (TyApp (Prim NP.undefinedX) altTy) m | isUndefinedPrimVal v@@ -457,14 +470,12 @@ | [_,Lit l0] <- vs -> l0 _ -> error ("scrutinise: " ++ showPpr (Case (valToTerm v) (ConstTy Arrow) alts)) -scrutinise v _altTy alts _ =+scrutinise _tcm v _altTy alts _ = error ("scrutinise: " ++ showPpr (Case (valToTerm v) (ConstTy Arrow) alts)) -substInAlt :: DataCon -> [TyVar] -> [Id] -> [Either Term Type] -> Term -> Term-substInAlt dc tvs xs args e = substTm "Evaluator.substInAlt" subst e+substInAlt :: DataCon -> [TyVar] -> [Id] -> [Type] -> [Term] -> Term -> Term+substInAlt dc tvs xs tys tms e = substTm "Evaluator.substInAlt" subst e where- tys = rights args- tms = lefts args substTyMap = zip tvs (drop (length (dcUnivTyVars dc)) tys) substTmMap = zip xs tms inScope = freeVarsOf tys `unionVarSet` freeVarsOf (e:tms)
src-ghc/Clash/GHC/Evaluator/Primitive.hs view
@@ -1528,8 +1528,8 @@ $(namePat 'GHC.Num.Integer.integerLogBase#) | Just (a,b) <- integerLiterals args- , Just c <- flogBase a b- -> (reduce . Literal . WordLiteral . toInteger) c+ -> reduce $ catchArithException+ (Literal (WordLiteral (toInteger (W# (GHC.Num.Integer.integerLogBase# a b))))) $(namePat 'GHC.Float.integerToFloat#) | [v] <- args@@ -1543,8 +1543,9 @@ $(namePat 'GHC.Num.naturalLogBase#) | Just (a,b) <- naturalLiterals args- , Just c <- flogBase a b- -> (reduce . Literal . WordLiteral . toInteger) c+ -> reduce $ catchArithException+ (Literal (WordLiteral (toInteger+ (W# (GHC.Num.naturalLogBase# (fromInteger a) (fromInteger b)))))) $(namePat 'GHC.Num.Integer.integerToInt#)@@ -4645,12 +4646,10 @@ -> reduce (valToTerm arg) $(namePat 'GHC.TypeNats.withSomeSNat) | Lit (NaturalLiteral n) : fun : _ <- args- , _ : funTy : _ <- Either.rights (fst (splitFunForallTy ty))- , (tyView -> TyConApp snatTcNm _) : _ <- Either.rights (fst (splitFunForallTy funTy))- , Just snatTc <- UniqMap.lookup snatTcNm tcm- , [snatDc] <- tyConDataCons snatTc+ -- 'GHC.TypeNats.SNat' is a newtype over 'Natural', which Clash+ -- represents by the value it wraps, so the literal is the 'SNat'. -> let nTy = LitTy (NumTy n)- snat = mkApps (Data snatDc) [Right nTy, Left (Literal (NaturalLiteral n))]+ snat = Literal (NaturalLiteral n) ret = mkApps (valToTerm fun) [Right nTy, Left snat] in reduce ret -- XXX: Does not seem to exist?@@ -4759,6 +4758,8 @@ catchDivByZero = makeUndefinedIf (==DivideByZero) catchErrorCall = makeUndefinedIf (const True :: ErrorCall -> Bool)++ catchArithException = makeUndefinedIf (const True :: ArithException -> Bool) -- Implementation shared by every worker of GHC's powImpl, i.e. the -- internal function behind '(^)'.
src-ghc/Clash/GHC/GHC2Core.hs view
@@ -9,6 +9,7 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE LambdaCase #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE NamedFieldPuns #-}@@ -22,6 +23,7 @@ ( C2C , GHC2CoreState , GHC2CoreEnv (..)+ , mkGHC2CoreEnv , srcSpan , tyConMap , coreToTerm@@ -45,10 +47,11 @@ import GHC.Float (castDoubleToWord64, castFloatToWord32) import qualified Data.ByteString.Char8 as Char8 import Data.Char (isDigit)+import qualified Data.IntMap.Strict as IntMap import Data.Hashable (Hashable (..)) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap-import Data.Maybe (catMaybes,fromMaybe,listToMaybe)+import Data.Maybe (catMaybes,fromMaybe,listToMaybe,mapMaybe) import Data.Text (Text, pack) import qualified Data.Text as Text import Data.Text.Encoding (decodeUtf8)@@ -78,7 +81,7 @@ #if MIN_VERSION_ghc(9,14,0) isTypeArg, isValArg, #endif- collectArgs, rhssOfAlts)+ collectArgs, rhssOfAlts, rhssOfBind) import GHC.Types.Tickish (GenTickish (..)) import GHC.Core.DataCon (DataCon, dataConExTyCoVars, dataConName,@@ -119,6 +122,7 @@ import GHC.Types.Var (Id, TyVar, Var, VarBndr (..), idDetails, isTyVar, varName, varType, varUnique, idInfo, isGlobalId)+import GHC.Types.Var.Env (VarEnv, emptyVarEnv, extendVarEnvList, lookupVarEnv) import GHC.Types.Var.Set (isEmptyVarSet) -- Local imports@@ -233,10 +237,16 @@ = GHC2CoreEnv { _srcSpan :: SrcSpan , _famInstEnvs :: FamInstEnvs+ , _nameOverrides :: VarEnv Text+ -- ^ Names to use for local variables instead of the names GHC gave them. See+ -- 'withPatternBindingNames'. } makeLenses ''GHC2CoreEnv +mkGHC2CoreEnv :: SrcSpan -> FamInstEnvs -> GHC2CoreEnv+mkGHC2CoreEnv sp fiEnvs = GHC2CoreEnv sp fiEnvs emptyVarEnv+ emptyGHC2CoreState :: GHC2CoreState emptyGHC2CoreState = GHC2CoreState mempty HashMap.empty HashMap.empty HashMap.empty@@ -265,7 +275,7 @@ | otherwise = tcm <> tcm' where (tcm,old', _) = RWS.runRWS (T.mapM makeTyCon (new ^. tyConMap))- (GHC2CoreEnv noSrcSpan fiEnvs)+ (mkGHC2CoreEnv noSrcSpan fiEnvs) old tcm' = go old' (old' & tyConMap %~ (`C.difference` (old ^. tyConMap))) @@ -442,7 +452,7 @@ #endif | (Var x,args) <- collectArgs e , let (nm, _) = RWS.evalRWS (qualifiedNameString (varName x))- (GHC2CoreEnv noSrcSpan emptyFamInstEnvs)+ (mkGHC2CoreEnv noSrcSpan emptyFamInstEnvs) emptyGHC2CoreState = go nm args | otherwise@@ -550,17 +560,17 @@ | isTyVar x = C.TyLam <$> coreToTyVar x <*> addUsefull (getSrcSpan x) (term e) | otherwise- = do+ = withPatternBindingNames [x] [e] $ do (e',sp) <- termSP (getSrcSpan x) e x' <- coreToIdSP sp x return (C.Lam x' e')- term' (Let (NonRec x e1) e2) = do+ term' (Let (NonRec x e1) e2) = withPatternBindingNames [x] [e2] $ do (e1',sp) <- termSP (getSrcSpan x) e1 x' <- coreToIdSP sp x e2' <- term e2 return (C.Let (C.NonRec x' e1') e2') - term' (Let (Rec xes) e) = do+ term' (Let (Rec xes) e) = withPatternBindingNames (map fst xes) (e : map snd xes) $ do xes' <- mapM go xes e' <- term e return (C.Let (C.Rec xes') e')@@ -1119,8 +1129,90 @@ coreToVar :: Var -> C2C (C.Name a)-coreToVar = coreToName varName varUnique qualifiedNameStringM+coreToVar v = do+ nm <- coreToName varName varUnique qualifiedNameStringM v+ overrides <- view nameOverrides+ pure $ case lookupVarEnv overrides v of+ Just occ -> nm { C.nameOcc = occ }+ Nothing -> nm +-- | GHC desugars a pattern binding such as @(nextState, txLine) = rhs@ to a+-- binder named @ds@ (or @ds1@, ...) for @rhs@, which it takes apart with case+-- expressions like @case ds of (nextState, txLine) -> nextState@ where needed.+-- The same goes for function arguments that are patterns. Run a translation+-- with such binders named after the variables of the pattern instead, e.g.+-- @nextState_txLine@, so that the HDL shows which values the signal holds.+--+-- The binders keep their 'C.System' name sort, so Clash inlines them just like+-- before. The pattern might come from a library function inlined by GHC (e.g.+-- @(s', o)@ in 'Clash.Prelude.mealy'), so the names aren't necessarily the+-- user's.+withPatternBindingNames ::+ -- | Binders+ [Var] ->+ -- | Expressions in the scope of the binders+ [CoreExpr] ->+ C2C a ->+ C2C a+withPatternBindingNames bndrs scope =+ RWS.local (nameOverrides %~ (`extendVarEnvList` renames))+ where+ renames =+ [ (b, nm)+ | b <- bndrs+ , isSysX ["ds"] (pack (occNameString (nameOccName (varName b))))+ , Just nm <- [patternBindingName b scope]+ ]++-- | Name for a binder based on the user-written names of the pattern variables+-- of case expressions that take it apart. See 'withPatternBindingNames'.+patternBindingName :: Var -> [CoreExpr] -> Maybe Text+patternBindingName x scope =+ case IntMap.elems (IntMap.fromListWith (\_new old -> old) (concatMap go scope)) of+ [] -> Nothing+ names -> Just (Text.intercalate "_" names)+ where+ go :: CoreExpr -> [(Int, Text)]+ go = \case+ Case scrut _ _ alts+ | isScrutinee scrut+ , [Alt (DataAlt _) bs rhs] <- alts+ -> [ (i, nm)+ | (i, b) <- zip [0..] (filter (not . isTyVar) bs)+ , let nm = pack (occNameString (nameOccName (varName b)))+ , not (isGhcSystemName nm)+ ] <> go rhs+ | otherwise -> go scrut <> concat [go rhs | Alt _ _ rhs <- alts]+ App f a -> go f <> go a+ Lam _ e -> go e+ Let b e -> concatMap go (rhssOfBind b) <> go e+ Cast e _ -> go e+ Tick _ e -> go e+ _ -> []++ isScrutinee = \case+ Var v -> v == x+ Cast e _ -> isScrutinee e+ Tick _ e -> isScrutinee e+ _ -> False++-- | Does a name consist of one of the given prefixes, optionally followed by a+-- number? That's how GHC names variables it made up, e.g. @ds@, @ds1@, @ds2@.+isSysX :: [Text] -> Text -> Bool+isSysX prefixes nm =+ case stripAnyPrefix of+ Just suffix | Text.all isDigit suffix -> True+ _ -> False+ where+ stripAnyPrefix = listToMaybe (mapMaybe (`Text.stripPrefix` nm) prefixes)++-- | Is it a name GHC made up, e.g. one of [ds,ds1,ds2,..] or [eta,eta1,..]?+--+-- XXX: GHC tracks these as system names, but tidying turns them into ordinary+-- internal names, so we have to recognize them by their spelling.+isGhcSystemName :: Text -> Bool+isGhcSystemName = isSysX ["ds", "eta", "wild", "lvl", "sat"]+ -- | Convert the type of a variable, memoized on the variable's name. -- -- Only global variables are memoized: their names come from GHC's name cache@@ -1147,9 +1239,7 @@ ns <- toString (toName v) let key = fromGhcUnique (toUnique v) locI = getSrcSpan (toName v)- -- Is it one of [ds,ds1,ds2,..]- isDSX = maybe False (maybe True (isDigit . fst) . Text.uncons) . Text.stripPrefix "ds"- sort | isDSX ns || Text.isPrefixOf "$" ns+ sort | isGhcSystemName ns || Text.isPrefixOf "$" ns = C.System | otherwise = C.User
src-ghc/Clash/GHC/GenerateBindings.hs view
@@ -1,7 +1,7 @@ {-| Copyright : (C) 2013-2016, University of Twente, 2017, QBayLogic, Google Inc.,- 2021-2022, QBayLogic B.V.+ 2021-2026, QBayLogic B.V. License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <devops@qbaylogic.com> -}@@ -75,7 +75,7 @@ import Clash.Driver.Bool (toGhcOverridingBool) import Clash.Driver.Types (BindingMap, Binding(..), IsPrim(..), ClashEnv(..), ClashDesign(..), ClashOpts(..)) import Clash.GHC.GHC2Core- (C2C, GHC2CoreState, GHC2CoreEnv (..), tyConMap, coreToId, coreToName, coreToTerm,+ (C2C, GHC2CoreState, GHC2CoreEnv (..), mkGHC2CoreEnv, tyConMap, coreToId, coreToName, coreToTerm, makeAllTyCons, qualifiedNameString, emptyGHC2CoreState, srcSpan) import Clash.GHC.LoadModules (ghcLibDir, loadModules) import Clash.Netlist.BlackBox.Util (getUsedArguments)@@ -126,7 +126,7 @@ primMapC <- compilePrimitives importDirs dbs tdir primMapR let ((bindingsMap,clsVMap),tcMap,_) = RWS.runRWS (mkBindings primMapC bindings clsOps unlocatable)- (GHC2CoreEnv GHC.noSrcSpan fiEnvs)+ (mkGHC2CoreEnv GHC.noSrcSpan fiEnvs) emptyGHC2CoreState (tcMap',tupTcCache) = mkTupTyCons tcMap tcCache = makeAllTyCons tcMap' fiEnvs@@ -143,7 +143,7 @@ clsVMap allBindings = bindingsMap `unionVarEnv` clsMap topEntities' =- (\m -> fst (RWS.evalRWS m (GHC2CoreEnv GHC.noSrcSpan fiEnvs) tcMap')) $+ (\m -> fst (RWS.evalRWS m (mkGHC2CoreEnv GHC.noSrcSpan fiEnvs) tcMap')) $ mapM (\(topEnt,annM,isTb) -> do topEnt' <- coreToName GHC.varName GHC.varUnique qualifiedNameString topEnt return (topEnt', annM, isTb)) topEntities@@ -429,7 +429,7 @@ (tcNames,tcMap',_) = RWS.runRWS (mapM (\tc -> coreToName GHC.tyConName GHC.tyConUnique qualifiedNameString tc) tupTyCons)- (GHC2CoreEnv GHC.noSrcSpan GHC.emptyFamInstEnvs)+ (mkGHC2CoreEnv GHC.noSrcSpan GHC.emptyFamInstEnvs) tcMap tupTcCache = IMS.fromList (zip [2..GHC.mAX_TUPLE_SIZE] (drop 3 tcNames)) tupHM = UniqMap.fromList (zip tcNames tupTyCons)
src-ghc/Clash/GHC/LoadInterfaceFiles.hs view
@@ -1,7 +1,7 @@ {-| Copyright : (C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd- 2022-2024, QBayLogic B.V.+ 2022-2026, QBayLogic B.V. License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <devops@qbaylogic.com> -}@@ -394,7 +394,7 @@ primName = Text.unpack (name primOrErr) in if primName /= targetName1- then inlineNameError targetName1 primName+ then inlineNameError targetName0 targetName1 primName else pure [Left primOrErr] InlinePrimitive _ contentOrFp ->@@ -416,11 +416,13 @@ primName = Text.unpack (name primOrErr) in if primName /= targetName1- then inlineNameError targetName1 primName+ then inlineNameError targetName0 targetName1 primName else pure [Left primOrErr] where- inlineNameError targetName primName =- error $ concat+ -- Points at the definition of the annotated function if it was compiled+ -- from source. Names loaded from interface files have no source location.+ inlineNameError targetName0 targetName primName =+ throwPlainError (Name.nameSrcSpan targetName0) $ Outputable.text $ concat [ "Function " ++ targetName ++ " was annotated with an inline " , "primitive for " ++ primName ++ ". These names " , "should be the same." ]
src-ghc/Clash/GHC/LoadModules.hs view
@@ -2,16 +2,14 @@ Copyright : (C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017-2024, Google Inc.- 2021-2024, QBayLogic B.V.+ 2021-2026, QBayLogic B.V. License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <devops@qbaylogic.com> -} {-# LANGUAGE CPP #-}-{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-}-{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-}@@ -36,13 +34,11 @@ import Clash.Util (ClashException(..), pkgIdFromTypeable) import qualified Clash.Util.Interpolate as I import Control.Arrow (first)-import Control.Exception (SomeException, throw)+import Control.Exception (throw) import Control.Monad (forM, join, when) import Data.List.Extra (nubSort)-import Control.Exception (Exception, throwIO)+import Control.Exception (throwIO) import Control.Monad (foldM)-import Control.Monad.Catch (catch, throwM)-import Control.Monad.Catch as MC (try) import Control.Monad.IO.Class (liftIO) import Data.Char (isDigit) #if !MIN_VERSION_ghc(9,14,0)@@ -119,8 +115,12 @@ import qualified GHC.Iface.Load as IfaceLoad import qualified GHC.Utils.Monad as MonadUtils import qualified GHC.Utils.Panic as Panic+import GHC.Utils.Misc (looksLikeModuleName) import qualified GHC.Serialized as Serialized (deserializeWithData) import qualified GHC.Unit.Types as UnitTypes (unitIdString)+import qualified GHC.Unit.Finder as Finder+import qualified GHC.Unit.Home as HomeUnit+import qualified GHC.Types.PkgQual as PkgQual import qualified GHC.Tc.Utils.Monad as TcRnMonad import qualified GHC.Tc.Types as TcRnTypes import qualified GHC.Iface.Tidy as TidyPgm@@ -187,6 +187,33 @@ return (output, exitCode) #endif +-- | Resolve a target to load from local sources ('loadLocalModule'), or return+-- 'Nothing' to load it from a package database ('loadExternalModule').+--+-- Resolve module names before 'GHC.guessTarget', which also looks for files in+-- the working directory even when it is excluded from the import path. Sources+-- on the import path still take precedence over packages, as in 'GHC.findModule'.+-- If lookup fails, allow a local filename without an extension; otherwise let+-- 'GHC.findModule' report the missing module, including hidden-package hints.+findLocalTarget :: GHC.GhcMonad m => String -> m (Maybe GHC.Target)+findLocalTarget targetName+ | looksLikeModuleName targetName = do+ hscEnv <- GHC.getSession+ res <- liftIO $ Finder.findImportedModule hscEnv+ (GHC.mkModuleName targetName) PkgQual.NoPkgQual+ case res of+ Finder.Found _ m+ | HomeUnit.isHomeModule (HscTypes.hsc_home_unit hscEnv) m -> localTarget+ | otherwise -> pure Nothing+ _ -> do+ target <- GHC.guessTarget targetName Nothing Nothing+ pure $ case GHC.targetId target of+ GHC.TargetFile{} -> Just target+ GHC.TargetModule{} -> Nothing+ | otherwise = localTarget+ where+ localTarget = Just <$> GHC.guessTarget targetName Nothing Nothing+ -- | Search databases for given module loadExternalModule :: (HasCallStack, GHC.GhcMonad m)@@ -198,15 +225,13 @@ -- ^ Name passed with @-main-is@, if any. When set, only the transitive -- closure of this binder is loaded (instead of the closure of all exports of -- the module). See 'loadSeed'.- -> m (Either- SomeException- ( [CoreSyn.CoreBndr] -- Root binders- , FamInstEnv.FamInstEnv -- Local type family instances- , GHC.ModuleName -- Module name- , LoadedBinders- , [CoreSyn.CoreBind] -- All bindings- ) )-loadExternalModule hdl modName0 mainIsM = MC.try $ do+ -> m ( [CoreSyn.CoreBndr] -- Root binders+ , FamInstEnv.FamInstEnv -- Local type family instances+ , GHC.ModuleName -- Module name+ , LoadedBinders+ , [CoreSyn.CoreBind] -- All bindings+ )+loadExternalModule hdl modName0 mainIsM = do let modName1 = GHC.mkModuleName modName0 foundMod <- GHC.findModule modName1 Nothing loadFamilyInstanceModules foundMod@@ -366,17 +391,15 @@ loadLocalModule :: GHC.GhcMonad m => HDL- -> String- -- ^ Module name. Can either be a filepath pointing to a .hs file, or a- -- qualified module name (example: "Data.List").+ -> GHC.Target+ -- ^ Module to load, see 'GHC.guessTarget' -> m ( [CoreSyn.CoreBndr] -- Root binders , FamInstEnv.FamInstEnv -- Local type family instances , GHC.ModuleName -- Module name , LoadedBinders , [CoreSyn.CoreBind] -- All bindings )-loadLocalModule hdl modName = do- target <- GHC.guessTarget modName Nothing Nothing+loadLocalModule hdl target = do GHC.setTargets [target] modGraph <- GHC.depanal [] False let modGraph' = GHC.mapMG disableOptimizationsFlags modGraph@@ -517,26 +540,6 @@ isMagicName :: Var.Var -> Bool isMagicName v = isTopEntityName v || isTestBenchName v -data LoadModulesException = LoadModulesException- { moduleName :: String- , externalError :: String- , localError :: String- } deriving (Exception)--instance Show LoadModulesException where- showsPrec :: Int -> LoadModulesException -> ShowS- showsPrec _ LoadModulesException{moduleName, externalError, localError} = showString [I.i|- Failed to load module '#{moduleName}'.-- Tried to load it from precompiled sources, error was:-- #{externalError}-- Tried to load it from local sources, error was:-- #{localError}- |]- loadModules :: GHC.Ghc () -- ^ Allows us to have some initial action, such as sharing a linker state@@ -575,21 +578,11 @@ MonadUtils.liftIO $ putStrLn $ "GHC: Setting up GHC took: " ++ setupStartDiff let mainIsM = GHC.mainFunIs =<< dflagsM+ localTarget <- findLocalTarget modName (rootIds, modFamInstEnvs, _rootModule, LoadedBinders{..}, allBinders) <-- -- We need to try and load external modules first, because we can't- -- recover from errors in 'loadLocalModule'.- loadExternalModule hdl modName mainIsM >>= \case- Left loadExternalErr -> do- catch @_ @SomeException- (loadLocalModule hdl modName)- (\localError ->- throwM- (LoadModulesException- { moduleName = modName- , externalError = show loadExternalErr- , localError = show localError- }))- Right res -> pure res+ case localTarget of+ Just target -> loadLocalModule hdl target+ Nothing -> loadExternalModule hdl modName mainIsM let allBinderIds = map fst (CoreSyn.flattenBinds allBinders)
src-ghc/Clash/GHC/Util.hs view
@@ -13,8 +13,8 @@ import GHC.Utils.Outputable (SDoc, neverQualify) import GHC.Utils.Error (mkErrorMsgEnvelope, mkPlainError) import GHC.Plugins- (DynFlags, SourceError, ($$), blankLine, empty, isGoodSrcSpan, liftIO,- noSrcSpan, text, throwOneError)+ (DynFlags, SourceError, SrcSpan, ($$), blankLine, empty,+ isGoodSrcSpan, liftIO, noSrcSpan, text, throwOneError) import GHC.Types.Error (mkSimpleUnknownDiagnostic) #else import GHC.Driver.Errors.Types (GhcMessage(GhcUnknownMessage))@@ -22,8 +22,8 @@ import GHC.Utils.Outputable (SDoc, neverQualify) import GHC.Utils.Error (mkErrorMsgEnvelope, mkPlainError) import GHC.Plugins- (DynFlags, SourceError, ($$), blankLine, empty, isGoodSrcSpan, liftIO,- noSrcSpan, text, throwOneError)+ (DynFlags, SourceError, SrcSpan, ($$), blankLine, empty,+ isGoodSrcSpan, liftIO, noSrcSpan, text, throwOneError) import GHC.Types.Error (UnknownDiagnostic(..)) #endif import GHC (GhcMonad(..), printException)@@ -32,10 +32,12 @@ import Control.Exception (ErrorCall(..)) #endif import Control.Exception (Exception(..))+import Control.Monad.IO.Class (MonadIO) import GHC.Exception (SomeException) import System.Exit (ExitCode(ExitFailure), exitWith) import Clash.Util (ClashException(..))+import Clash.Util.Exception (exceptionBacktrace) import Clash.Util.Interpolate (i) import Clash.Driver.Types (ClashOpts(..)) @@ -46,6 +48,17 @@ textLines :: String -> SDoc textLines s = foldl1 ($$) (map text (lines s)) +-- | Throw an error at the given source location. GHC renders it like its own+-- errors, i.e., with a code snippet if the location is known.+throwPlainError :: MonadIO m => SrcSpan -> SDoc -> m a+throwPlainError sp msg =+ throwOneError $ mkErrorMsgEnvelope sp neverQualify $ GhcUnknownMessage $+#if MIN_VERSION_ghc(9,8,0)+ mkSimpleUnknownDiagnostic $ mkPlainError [] msg+#else+ UnknownDiagnostic $ mkPlainError [] msg+#endif+ handleClashException :: GhcMonad m => DynFlags@@ -56,36 +69,27 @@ Just (ClashException sp s eM) -> do let srcInfo' | isGoodSrcSpan sp = srcInfo | otherwise = empty- throwOneError-#if MIN_VERSION_ghc(9,8,0)- (mkErrorMsgEnvelope sp neverQualify $ GhcUnknownMessage $ mkSimpleUnknownDiagnostic $ mkPlainError []-#else- (mkErrorMsgEnvelope sp neverQualify $ GhcUnknownMessage $ UnknownDiagnostic $ mkPlainError []-#endif- (blankLine $$ textLines s $$ blankLine $$ srcInfo' $$ showExtra (opt_errorExtra opts) eM))+ throwPlainError sp+ (blankLine $$ textLines s $$ blankLine $$ srcInfo' $$ showExtra (opt_errorExtra opts) eM) _ -> case fromException e of #if !MIN_VERSION_ghc(9,12,0) Just (ErrorCallWithLocation _ _) ->- throwOneError-#if MIN_VERSION_ghc(9,8,0)- (mkErrorMsgEnvelope noSrcSpan neverQualify $ GhcUnknownMessage $ mkSimpleUnknownDiagnostic $ mkPlainError []-#else- (mkErrorMsgEnvelope noSrcSpan neverQualify $ GhcUnknownMessage $ UnknownDiagnostic $ mkPlainError []-#endif- (text "Clash error call:" $$ textLines (show e)))+ throwPlainError noSrcSpan+ (text "Clash error call:" $$ textLines (show e)) _ -> case fromException e of #endif Just (e' :: SourceError) -> do GHC.printException e' liftIO $ exitWith (ExitFailure 1)- _ -> throwOneError-#if MIN_VERSION_ghc(9,8,0)- (mkErrorMsgEnvelope noSrcSpan neverQualify $ GhcUnknownMessage $ mkSimpleUnknownDiagnostic $ mkPlainError []-#else- (mkErrorMsgEnvelope noSrcSpan neverQualify $ GhcUnknownMessage $ UnknownDiagnostic $ mkPlainError []-#endif- (text "Other error:" $$ textLines (displayException e)))+ _ -> throwPlainError noSrcSpan+ (text "Other error:" $$ textLines (displayException e) $$ backtrace) where+ -- Since base-4.21 (GHC 9.12), displayException omits the exception context,+ -- so print it separately. On GHC 9.10 it already includes the context.+ backtrace = case exceptionBacktrace e of+ [] -> empty+ ctx -> blankLine $$ textLines ctx+ srcInfo = textLines [i| The source location of the error is not exact, only indicative, as it is acquired after optimizations. The actual location of the error can be