Merge branch 'master' of git://github.com/christiaanb/clash into cλash
authorMatthijs Kooijman <m.kooijman@student.utwente.nl>
Wed, 5 Aug 2009 15:10:41 +0000 (17:10 +0200)
committerMatthijs Kooijman <m.kooijman@student.utwente.nl>
Wed, 5 Aug 2009 15:10:41 +0000 (17:10 +0200)
* 'master' of git://github.com/christiaanb/clash:
  Fix builtin functions (!),take and RangedWord

Conflicts:
cλash/CLasH/VHDL/Generate.hs

1  2 
cλash/CLasH/VHDL/Generate.hs

index aca4e9570ff0e23dceaf7e7c1c1bf38b9200544e,5618532c2f1771fd18d88ba417120072e94206fb..5360cff1234cc226039dc2a25881bf7aa7e8b9ea
@@@ -1,9 -1,7 +1,9 @@@
  module CLasH.VHDL.Generate where
  
  -- Standard modules
 +import qualified Data.List as List
  import qualified Data.Map as Map
 +import qualified Control.Monad as Monad
  import qualified Maybe
  import qualified Data.Either as Either
  import Data.Accessor
@@@ -17,173 -15,17 +17,173 @@@ import qualified Language.VHDL.AST as A
  import qualified CoreSyn
  import qualified Type
  import qualified Var
 +import qualified Id
  import qualified IdInfo
  import qualified Literal
  import qualified Name
  import qualified TyCon
  
  -- Local imports
 +import CLasH.Translator.TranslatorTypes
  import CLasH.VHDL.Constants
  import CLasH.VHDL.VHDLTypes
  import CLasH.VHDL.VHDLTools
 +import qualified CLasH.Utils as Utils
  import CLasH.Utils.Core.CoreTools
  import CLasH.Utils.Pretty
 +import qualified CLasH.Normalize as Normalize
 +
 +-----------------------------------------------------------------------------
 +-- Functions to generate VHDL for user-defined functions.
 +-----------------------------------------------------------------------------
 +
 +-- | Create an entity for a given function
 +getEntity ::
 +  CoreSyn.CoreBndr
 +  -> TranslatorSession Entity -- ^ The resulting entity
 +
 +getEntity fname = Utils.makeCached fname tsEntities $ do
 +      expr <- Normalize.getNormalized fname
 +      -- Strip off lambda's, these will be arguments
 +      let (args, letexpr) = CoreSyn.collectBinders expr
 +      args' <- mapM mkMap args
 +      -- There must be a let at top level 
 +      let (CoreSyn.Let binds (CoreSyn.Var res)) = letexpr
 +      res' <- mkMap res
 +      let vhdl_id = mkVHDLBasicId $ varToString fname ++ "_" ++ varToStringUniq fname
 +      let ent_decl = createEntityAST vhdl_id args' res'
 +      let signature = Entity vhdl_id args' res' ent_decl
 +      return signature
 +  where
 +    mkMap ::
 +      --[(SignalId, SignalInfo)] 
 +      CoreSyn.CoreBndr 
 +      -> TranslatorSession Port
 +    mkMap = (\bndr ->
 +      let
 +        --info = Maybe.fromMaybe
 +        --  (error $ "Signal not found in the name map? This should not happen!")
 +        --  (lookup id sigmap)
 +        --  Assume the bndr has a valid VHDL id already
 +        id = varToVHDLId bndr
 +        ty = Var.varType bndr
 +        error_msg = "\nVHDL.createEntity.mkMap: Can not create entity: " ++ pprString fname ++ "\nbecause no type can be created for port: " ++ pprString bndr 
 +      in do
 +        type_mark <- MonadState.lift tsType $ vhdl_ty error_msg ty
 +        return (id, type_mark)
 +     )
 +
 +-- | Create the VHDL AST for an entity
 +createEntityAST ::
 +  AST.VHDLId                   -- ^ The name of the function
 +  -> [Port]                    -- ^ The entity's arguments
 +  -> Port                      -- ^ The entity's result
 +  -> AST.EntityDec             -- ^ The entity with the ent_decl filled in as well
 +
 +createEntityAST vhdl_id args res =
 +  AST.EntityDec vhdl_id ports
 +  where
 +    -- Create a basic Id, since VHDL doesn't grok filenames with extended Ids.
 +    ports = map (mkIfaceSigDec AST.In) args
 +              ++ [mkIfaceSigDec AST.Out res]
 +              ++ [clk_port]
 +    -- Add a clk port if we have state
 +    clk_port = AST.IfaceSigDec clockId AST.In std_logicTM
 +
 +-- | Create a port declaration
 +mkIfaceSigDec ::
 +  AST.Mode                         -- ^ The mode for the port (In / Out)
 +  -> (AST.VHDLId, AST.TypeMark)    -- ^ The id and type for the port
 +  -> AST.IfaceSigDec               -- ^ The resulting port declaration
 +
 +mkIfaceSigDec mode (id, ty) = AST.IfaceSigDec id mode ty
 +
 +-- | Create an architecture for a given function
 +getArchitecture ::
 +  CoreSyn.CoreBndr -- ^ The function to get an architecture for
 +  -> TranslatorSession (Architecture, [CoreSyn.CoreBndr])
 +  -- ^ The architecture for this function
 +
 +getArchitecture fname = Utils.makeCached fname tsArchitectures $ do
 +  expr <- Normalize.getNormalized fname
 +  signature <- getEntity fname
 +  let entity_id = ent_id signature
 +  -- Strip off lambda's, these will be arguments
 +  let (args, letexpr) = CoreSyn.collectBinders expr
 +  -- There must be a let at top level 
 +  let (CoreSyn.Let (CoreSyn.Rec binds) (CoreSyn.Var res)) = letexpr
 +
 +  -- Create signal declarations for all binders in the let expression, except
 +  -- for the output port (that will already have an output port declared in
 +  -- the entity).
 +  sig_dec_maybes <- mapM (mkSigDec' . fst) (filter ((/=res).fst) binds)
 +  let sig_decs = Maybe.catMaybes $ sig_dec_maybes
 +
 +  (statementss, used_entitiess) <- Monad.mapAndUnzipM mkConcSm binds
 +  let statements = concat statementss
 +  let used_entities = concat used_entitiess
 +  let arch = AST.ArchBody (mkVHDLBasicId "structural") (AST.NSimple entity_id) (map AST.BDISD sig_decs) (statements ++ procs')
 +  return (arch, used_entities)
 +  where
 +    procs = [] --map mkStateProcSm [] -- (makeStatePairs flatfunc)
 +    procs' = map AST.CSPSm procs
 +    -- mkSigDec only uses tsTypes from the state
 +    mkSigDec' = mkSigDec
 +
 +-- | Transforms a core binding into a VHDL concurrent statement
 +mkConcSm ::
 +  (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The binding to process
 +  -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]) 
 +  -- ^ The corresponding VHDL concurrent statements and entities
 +  --   instantiated.
 +
 +
 +-- Ignore Cast expressions, they should not longer have any meaning as long as
 +-- the type works out.
 +mkConcSm (bndr, CoreSyn.Cast expr ty) = mkConcSm (bndr, expr)
 +
 +-- Simple a = b assignments are just like applications, but without arguments.
 +-- We can't just generate an unconditional assignment here, since b might be a
 +-- top level binding (e.g., a function with no arguments).
 +mkConcSm (bndr, CoreSyn.Var v) = do
 +  genApplication (Left bndr) v []
 +
 +mkConcSm (bndr, app@(CoreSyn.App _ _))= do
 +  let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
 +  let valargs = get_val_args (Var.varType f) args
 +  genApplication (Left bndr) f (map Left valargs)
 +
 +-- A single alt case must be a selector. This means thee scrutinee is a simple
 +-- variable, the alternative is a dataalt with a single non-wild binder that
 +-- is also returned.
 +mkConcSm (bndr, expr@(CoreSyn.Case (CoreSyn.Var scrut) b ty [alt])) =
 +  case alt of
 +    (CoreSyn.DataAlt dc, bndrs, (CoreSyn.Var sel_bndr)) -> do
 +      case List.elemIndex sel_bndr bndrs of
 +        Just i -> do
 +          labels <- MonadState.lift tsType $ getFieldLabels (Id.idType scrut)
 +          let label = labels!!i
 +          let sel_name = mkSelectedName (varToVHDLName scrut) label
 +          let sel_expr = AST.PrimName sel_name
 +          return ([mkUncondAssign (Left bndr) sel_expr], [])
 +        Nothing -> error $ "\nVHDL.mkConcSM: Not in normal form: Not a selector case:\n" ++ (pprString expr)
 +      
 +    _ -> error $ "\nVHDL.mkConcSM: Not in normal form: Not a selector case:\n" ++ (pprString expr)
 +
 +-- Multiple case alt are be conditional assignments and have only wild
 +-- binders in the alts and only variables in the case values and a variable
 +-- for a scrutinee. We check the constructor of the second alt, since the
 +-- first is the default case, if there is any.
 +mkConcSm (bndr, (CoreSyn.Case (CoreSyn.Var scrut) b ty [(_, _, CoreSyn.Var false), (con, _, CoreSyn.Var true)])) = do
 +  scrut' <- MonadState.lift tsType $ varToVHDLExpr scrut
 +  let cond_expr = scrut' AST.:=: (altconToVHDLExpr con)
 +  true_expr <- MonadState.lift tsType $ varToVHDLExpr true
 +  false_expr <- MonadState.lift tsType $ varToVHDLExpr false
 +  return ([mkCondAssign (Left bndr) cond_expr true_expr false_expr], [])
 +
 +mkConcSm (_, (CoreSyn.Case (CoreSyn.Var _) _ _ alts)) = error "\nVHDL.mkConcSm: Not in normal form: Case statement with more than two alternatives"
 +mkConcSm (_, CoreSyn.Case _ _ _ _) = error "\nVHDL.mkConcSm: Not in normal form: Case statement has does not have a simple variable as scrutinee"
 +mkConcSm (bndr, expr) = error $ "\nVHDL.mkConcSM: Unsupported binding in let expression: " ++ pprString bndr ++ " = " ++ pprString expr
  
  -----------------------------------------------------------------------------
  -- Functions to generate VHDL for builtin functions
@@@ -195,17 -37,8 +195,17 @@@ genExprArgs wrap dst func args = d
    args' <- eitherCoreOrExprArgs args
    wrap dst func args'
  
 -eitherCoreOrExprArgs :: [Either CoreSyn.CoreExpr AST.Expr] -> VHDLSession [AST.Expr]
 -eitherCoreOrExprArgs args = mapM (Either.either ((MonadState.lift vsType) . varToVHDLExpr . exprToVar) return) args
 +eitherCoreOrExprArgs :: [Either CoreSyn.CoreExpr AST.Expr] -> TranslatorSession [AST.Expr]
 +eitherCoreOrExprArgs args = mapM (Either.either ((MonadState.lift tsType) . varToVHDLExpr . exprToVar) return) args
 +
 +-- A function to wrap a builder-like function that generates no component
 +-- instantiations
 +genNoInsts ::
 +  (dst -> func -> args -> TranslatorSession [AST.ConcSm])
 +  -> (dst -> func -> args -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]))
 +genNoInsts wrap dst func args = do
 +  concsms <- wrap dst func args
 +  return (concsms, [])
  
  -- | A function to wrap a builder-like function that expects its arguments to
  -- be variables.
@@@ -233,8 -66,8 +233,8 @@@ genLitArgs wrap dst func args = wrap ds
  -- | A function to wrap a builder-like function that produces an expression
  -- and expects it to be assigned to the destination.
  genExprRes ::
 -  ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession AST.Expr)
 -  -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession [AST.ConcSm])
 +  ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> TranslatorSession AST.Expr)
 +  -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> TranslatorSession [AST.ConcSm])
  genExprRes wrap dst func args = do
    expr <- wrap dst func args
    return $ [mkUncondAssign dst expr]
  -- | Generate a binary operator application. The first argument should be a
  -- constructor from the AST.Expr type, e.g. AST.And.
  genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder 
 -genOperator2 op = genExprArgs $ genExprRes (genOperator2' op)
 -genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
 +genOperator2 op = genNoInsts $ genExprArgs $ genExprRes (genOperator2' op)
 +genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
  genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
  
  -- | Generate a unary operator application
  genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder 
 -genOperator1 op = genExprArgs $ genExprRes (genOperator1' op)
 -genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
 +genOperator1 op = genNoInsts $ genExprArgs $ genExprRes (genOperator1' op)
 +genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
  genOperator1' op _ f [arg] = return $ op arg
  
  -- | Generate a unary operator application
  genNegation :: BuiltinBuilder 
 -genNegation = genVarArgs $ genExprRes genNegation'
 -genNegation' :: dst -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession AST.Expr
 +genNegation = genNoInsts $ genVarArgs $ genExprRes genNegation'
 +genNegation' :: dst -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession AST.Expr
  genNegation' _ f [arg] = do
 -  arg1 <- MonadState.lift vsType $ varToVHDLExpr arg
 +  arg1 <- MonadState.lift tsType $ varToVHDLExpr arg
    let ty = Var.varType arg
    let (tycon, args) = Type.splitTyConApp ty
    let name = Name.getOccString (TyCon.tyConName tycon)
  -- | Generate a function call from the destination binder, function name and a
  -- list of expressions (its arguments)
  genFCall :: Bool -> BuiltinBuilder 
 -genFCall switch = genExprArgs $ genExprRes (genFCall' switch)
 -genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
 +genFCall switch = genNoInsts $ genExprArgs $ genExprRes (genFCall' switch)
 +genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
  genFCall' switch (Left res) f args = do
    let fname = varToString f
    let el_ty = if switch then (Var.varType res) else ((tfvec_elem . Var.varType) res)
 -  id <- MonadState.lift vsType $ vectorFunId el_ty fname
 +  id <- MonadState.lift tsType $ vectorFunId el_ty fname
    return $ AST.PrimFCall $ AST.FCall (AST.NSimple id)  $
               map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
  genFCall' _ (Right name) _ _ = error $ "\nGenerate.genFCall': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
  
  genFromSizedWord :: BuiltinBuilder
 -genFromSizedWord = genExprArgs $ genExprRes genFromSizedWord'
 -genFromSizedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
 +genFromSizedWord = genNoInsts $ genExprArgs $ genExprRes genFromSizedWord'
 +genFromSizedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
  genFromSizedWord' (Left res) f args = do
    let fname = varToString f
    return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId toIntegerId))  $
  genFromSizedWord' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
  
  genResize :: BuiltinBuilder
 -genResize = genExprArgs $ genExprRes genResize'
 -genResize' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
 +genResize = genNoInsts $ genExprArgs $ genExprRes genResize'
 +genResize' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
  genResize' (Left res) f [arg] = do {
    ; let { ty = Var.varType res
          ; (tycon, args) = Type.splitTyConApp ty
          ; name = Name.getOccString (TyCon.tyConName tycon)
          } ;
    ; len <- case name of
 -      "SizedInt" -> MonadState.lift vsType $ tfp_to_int (sized_int_len_ty ty)
 -      "SizedWord" -> MonadState.lift vsType $ tfp_to_int (sized_word_len_ty ty)
 +      "SizedInt" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
 +      "SizedWord" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
    ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
               [Nothing AST.:=>: AST.ADExpr arg, Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
    }
@@@ -306,19 -139,24 +306,24 @@@ genResize' (Right name) _ _ = error $ "
  -- FIXME: I'm calling genLitArgs which is very specific function,
  -- which needs to be fixed as well
  genFromInteger :: BuiltinBuilder
 -genFromInteger = genLitArgs $ genExprRes genFromInteger'
 -genFromInteger' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [Literal.Literal] -> VHDLSession AST.Expr
 +genFromInteger = genNoInsts $ genLitArgs $ genExprRes genFromInteger'
 +genFromInteger' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [Literal.Literal] -> TranslatorSession AST.Expr
  genFromInteger' (Left res) f lits = do {
    ; let { ty = Var.varType res
          ; (tycon, args) = Type.splitTyConApp ty
          ; name = Name.getOccString (TyCon.tyConName tycon)
          } ;
-   ; len <- case name of
-     "SizedInt" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
-     "SizedWord" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
-   ; let fname = case name of "SizedInt" -> toSignedId ; "SizedWord" -> toUnsignedId
-   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId fname)) 
-             [Nothing AST.:=>: AST.ADExpr (AST.PrimLit (show (last lits))), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
+   ; case name of
+     "RangedWord" -> return $ AST.PrimLit (show (last lits))
+     otherwise -> do {
+       ; len <- case name of
 -        "SizedInt" -> MonadState.lift vsType $ tfp_to_int (sized_int_len_ty ty)
 -        "SizedWord" -> MonadState.lift vsType $ tfp_to_int (sized_word_len_ty ty)
 -        "RangedWord" -> MonadState.lift vsType $ tfp_to_int (ranged_word_bound_ty ty)
++        "SizedInt" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
++        "SizedWord" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
++        "RangedWord" -> MonadState.lift tsType $ tfp_to_int (ranged_word_bound_ty ty)
+       ; let fname = case name of "SizedInt" -> toSignedId ; "SizedWord" -> toUnsignedId
+       ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId fname))
+                 [Nothing AST.:=>: AST.ADExpr (AST.PrimLit (show (last lits))), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
+       }
    }
  
  genFromInteger' (Right name) _ _ = error $ "\nGenerate.genFromInteger': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
  genSizedInt :: BuiltinBuilder
  genSizedInt = genFromInteger
  
 +{-
  -- | Generate a Builder for the builtin datacon TFVec
  genTFVec :: BuiltinBuilder
  genTFVec (Left res) f [Left (CoreSyn.Let (CoreSyn.Rec letBinders) letRes)] = do {
    -- Get all the Assigned binders
    ; let assignedBinders = Maybe.catMaybes (map fst letAssigns)
    -- Make signal names for all the assigned binders
 -  ; sigs <- mapM (\x -> MonadState.lift vsType $ varToVHDLExpr x) (assignedBinders ++ resBinders)
 +  ; sigs <- mapM (\x -> MonadState.lift tsType $ varToVHDLExpr x) (assignedBinders ++ resBinders)
    -- Assign all the signals to the resulting vector
    ; let { vecsigns = mkAggregateSignal sigs
          ; vecassign = mkUncondAssign (Left res) vecsigns
    ; return $ [AST.CSBSm block]
    }
    where
 -    genBinderAssign :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -> VHDLSession (Maybe CoreSyn.CoreBndr, [AST.ConcSm])
 +    genBinderAssign :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -> TranslatorSession (Maybe CoreSyn.CoreBndr, [AST.ConcSm])
      -- For now we only translate applications
      genBinderAssign (bndr, app@(CoreSyn.App _ _)) = do
        let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
        apps <- genApplication (Left bndr) f (map Left valargs)
        return (Just bndr, apps)
      genBinderAssign _ = return (Nothing,[])
 -    genResAssign :: CoreSyn.CoreExpr -> VHDLSession ([CoreSyn.CoreBndr], [AST.ConcSm])
 +    genResAssign :: CoreSyn.CoreExpr -> TranslatorSession ([CoreSyn.CoreBndr], [AST.ConcSm])
      genResAssign app@(CoreSyn.App _ letexpr) = do
        case letexpr of
          (CoreSyn.Let (CoreSyn.Rec letbndrs) letres) -> do
@@@ -381,7 -218,7 +386,7 @@@ genTFVec (Left res) f [Left app@(CoreSy
                            otherwise -> error $ "\nGenerate.genTFVec: Cannot generate TFVec: " 
                              ++ show res ++ ", with elems:\n" ++ show elems ++ "\n" ++ pprString elems) elems
          } ;
 -  ; sigs <- mapM (\x -> MonadState.lift vsType $ varToVHDLExpr x) binders
 +  ; sigs <- mapM (\x -> MonadState.lift tsType $ varToVHDLExpr x) binders
    -- Assign all the signals to the resulting vector
    ; let { vecsigns = mkAggregateSignal sigs
          ; vecassign = mkUncondAssign (Left res) vecsigns
  genTFVec (Left name) _ [Left xs] = error $ "\nGenerate.genTFVec: Cannot generate TFVec: " ++ show name ++ ", with elems:\n" ++ show xs ++ "\n" ++ pprString xs
  
  genTFVec (Right name) _ _ = error $ "\nGenerate.genTFVec: Cannot generate TFVec assigned to VHDLName: " ++ show name
 -
 +-}
  -- | Generate a generate statement for the builtin function "map"
  genMap :: BuiltinBuilder
  genMap (Left res) f [Left mapped_f, Left (CoreSyn.Var arg)] = do {
    -- we must index it (which we couldn't if it was a VHDL Expr, since only
    -- VHDLNames can be indexed).
    -- Setup the generate scheme
 -  ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
 +  ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
            -- TODO: Use something better than varToString
    ; let { label       = mkVHDLExtId ("mapVector" ++ (varToString res))
          ; n_id        = mkVHDLBasicId "n"
          ; (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
          ; valargs = get_val_args (Var.varType real_f) already_mapped_args
          } ;
 -  ; app_concsms <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
 +  ; (app_concsms, used) <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
      -- Return the generate statement
 -  ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
 +  ; return ([AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms], used)
    }
  
  genMap' (Right name) _ _ = error $ "\nGenerate.genMap': Cannot generate map function call assigned to a VHDLName: " ++ show name
      
  genZipWith :: BuiltinBuilder
  genZipWith = genVarArgs genZipWith'
 -genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
  genZipWith' (Left res) f args@[zipped_f, arg1, arg2] = do {
    -- Setup the generate scheme
 -  ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
 +  ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
            -- TODO: Use something better than varToString
    ; let { label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
          ; n_id        = mkVHDLBasicId "n"
          ; argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
          ; argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
          } ;
 -  ; app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
 +  ; (app_concsms, used) <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
      -- Return the generate functions
 -  ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
 +  ; return ([AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms], used)
    }
  
  genFoldl :: BuiltinBuilder
@@@ -458,20 -295,20 +463,20 @@@ genFoldr = genFold Fals
  genFold :: Bool -> BuiltinBuilder
  genFold left = genVarArgs (genFold' left)
  
 -genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
  genFold' left res f args@[folded_f , start ,vec]= do
 -  len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty (Var.varType vec))
 +  len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty (Var.varType vec))
    genFold'' len left res f args
  
 -genFold'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genFold'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
  -- Special case for an empty input vector, just assign start to res
  genFold'' len left (Left res) _ [_, start, vec] | len == 0 = do
 -  arg <- MonadState.lift vsType $ varToVHDLExpr start
 -  return [mkUncondAssign (Left res) arg]
 +  arg <- MonadState.lift tsType $ varToVHDLExpr start
 +  return ([mkUncondAssign (Left res) arg], [])
      
  genFold'' len left (Left res) f [folded_f, start, vec] = do
    -- The vector length
 -  --len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
 +  --len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
    -- An expression for len-1
    let len_min_expr = (AST.PrimLit $ show (len-1))
    -- evec is (TFVec n), so it still needs an element type
    -- temporary vector
    let tmp_ty = Type.mkAppTy nvec (Var.varType start)
    let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
 -  tmp_vhdl_ty <- MonadState.lift vsType $ vhdl_ty error_msg tmp_ty
 +  tmp_vhdl_ty <- MonadState.lift tsType $ vhdl_ty error_msg tmp_ty
    -- Setup the generate scheme
    let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
    let block_label = mkVHDLExtId ("foldlVector" ++ (varToString res))
    -- Make the intermediate vector
    let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
    -- Create the generate statement
 -  cells <- sequence [genFirstCell, genOtherCell]
 +  cells' <- sequence [genFirstCell, genOtherCell]
 +  let (cells, useds) = unzip cells'
    let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
    -- Assign tmp[len-1] or tmp[0] to res
    let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
                      (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
                      (mkIndexedName tmp_name (AST.PrimLit "0")))      
    let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
 -  return [AST.CSBSm block]
 +  return ([AST.CSBSm block], concat useds)
    where
      -- An id for the counter
      n_id = mkVHDLBasicId "n"
      tmp_id = mkVHDLBasicId "tmp"
      tmp_name = AST.NSimple tmp_id
      -- Generate parts of the fold
 -    genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
 +    genFirstCell, genOtherCell :: TranslatorSession (AST.GenerateSm, [CoreSyn.CoreBndr])
      genFirstCell = do
 -      len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
 +      len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
        let cond_label = mkVHDLExtId "firstcell"
        -- if n == 0 or n == len-1
        let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
        -- Output to tmp[current n]
        let resname = mkIndexedName tmp_name n_cur
        -- Input from start
 -      argexpr1 <- MonadState.lift vsType $ varToVHDLExpr start
 +      argexpr1 <- MonadState.lift tsType $ varToVHDLExpr start
        -- Input from vec[current n]
        let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
 -      app_concsms <- genApplication (Right resname) folded_f  ( if left then
 +      (app_concsms, used) <- genApplication (Right resname) folded_f  ( if left then
                                                                    [Right argexpr1, Right argexpr2]
                                                                  else
                                                                    [Right argexpr2, Right argexpr1]
                                                                )
        -- Return the conditional generate part
 -      return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
 +      return $ (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
  
      genOtherCell = do
 -      len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
 +      len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
        let cond_label = mkVHDLExtId "othercell"
        -- if n > 0 or n < len-1
        let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
        let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
        -- Input from vec[current n]
        let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
 -      app_concsms <- genApplication (Right resname) folded_f  ( if left then
 +      (app_concsms, used) <- genApplication (Right resname) folded_f  ( if left then
                                                                    [Right argexpr1, Right argexpr2]
                                                                  else
                                                                    [Right argexpr2, Right argexpr1]
                                                                )
        -- Return the conditional generate part
 -      return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
 +      return $ (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
  
  -- | Generate a generate statement for the builtin function "zip"
  genZip :: BuiltinBuilder
 -genZip = genVarArgs genZip'
 -genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genZip = genNoInsts $ genVarArgs genZip'
 +genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
  genZip' (Left res) f args@[arg1, arg2] = do {
      -- Setup the generate scheme
 -  ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
 +  ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
            -- TODO: Use something better than varToString
    ; let { label           = mkVHDLExtId ("zipVector" ++ (varToString res))
          ; n_id            = mkVHDLBasicId "n"
          ; argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
          ; argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
          } ; 
 -  ; labels <- MonadState.lift vsType $ getFieldLabels (tfvec_elem (Var.varType res))
 +  ; labels <- MonadState.lift tsType $ getFieldLabels (tfvec_elem (Var.varType res))
    ; let { resnameA    = mkSelectedName resname' (labels!!0)
          ; resnameB    = mkSelectedName resname' (labels!!1)
          ; resA_assign = mkUncondAssign (Right resnameA) argexpr1
      
  -- | Generate a generate statement for the builtin function "unzip"
  genUnzip :: BuiltinBuilder
 -genUnzip = genVarArgs genUnzip'
 -genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genUnzip = genNoInsts $ genVarArgs genUnzip'
 +genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
  genUnzip' (Left res) f args@[arg] = do {
      -- Setup the generate scheme
 -  ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
 +  ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
      -- TODO: Use something better than varToString
    ; let { label           = mkVHDLExtId ("unzipVector" ++ (varToString res))
          ; n_id            = mkVHDLBasicId "n"
          ; resname'        = varToVHDLName res
          ; argexpr'        = mkIndexedName (varToVHDLName arg) n_expr
          } ;
 -  ; reslabels <- MonadState.lift vsType $ getFieldLabels (Var.varType res)
 -  ; arglabels <- MonadState.lift vsType $ getFieldLabels (tfvec_elem (Var.varType arg))
 +  ; reslabels <- MonadState.lift tsType $ getFieldLabels (Var.varType res)
 +  ; arglabels <- MonadState.lift tsType $ getFieldLabels (tfvec_elem (Var.varType arg))
    ; let { resnameA    = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
          ; resnameB    = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
          ; argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
    }
  
  genCopy :: BuiltinBuilder 
 -genCopy = genVarArgs genCopy'
 -genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genCopy = genNoInsts $ genVarArgs genCopy'
 +genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
  genCopy' (Left res) f args@[arg] =
    let
      resExpr = AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
      return [out_assign]
      
  genConcat :: BuiltinBuilder
 -genConcat = genVarArgs genConcat'
 -genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genConcat = genNoInsts $ genVarArgs genConcat'
 +genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
  genConcat' (Left res) f args@[arg] = do {
      -- Setup the generate scheme
 -  ; len1 <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
 +  ; len1 <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
    ; let (_, nvec) = Type.splitAppTy (Var.varType arg)
 -  ; len2 <- MonadState.lift vsType $ tfp_to_int $ tfvec_len_ty nvec
 +  ; len2 <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty nvec
            -- TODO: Use something better than varToString
    ; let { label       = mkVHDLExtId ("concatVector" ++ (varToString res))
          ; n_id        = mkVHDLBasicId "n"
@@@ -662,18 -498,18 +667,18 @@@ genGenerate = genIterateOrGenerate Fals
  genIterateOrGenerate :: Bool -> BuiltinBuilder
  genIterateOrGenerate iter = genVarArgs (genIterateOrGenerate' iter)
  
 -genIterateOrGenerate' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genIterateOrGenerate' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
  genIterateOrGenerate' iter (Left res) f args = do
 -  len <- MonadState.lift vsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
 +  len <- MonadState.lift tsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
    genIterateOrGenerate'' len iter (Left res) f args
  
 -genIterateOrGenerate'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
 +genIterateOrGenerate'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
  -- Special case for an empty input vector, just assign start to res
 -genIterateOrGenerate'' len iter (Left res) _ [app_f, start] | len == 0 = return [mkUncondAssign (Left res) (AST.PrimLit "\"\"")]
 +genIterateOrGenerate'' len iter (Left res) _ [app_f, start] | len == 0 = return ([mkUncondAssign (Left res) (AST.PrimLit "\"\"")], [])
  
  genIterateOrGenerate'' len iter (Left res) f [app_f, start] = do
    -- The vector length
 -  -- len <- MonadState.lift vsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
 +  -- len <- MonadState.lift tsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
    -- An expression for len-1
    let len_min_expr = (AST.PrimLit $ show (len-1))
    -- -- evec is (TFVec n), so it still needs an element type
    -- -- temporary vector
    let tmp_ty = Var.varType res
    let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
 -  tmp_vhdl_ty <- MonadState.lift vsType $ vhdl_ty error_msg tmp_ty
 +  tmp_vhdl_ty <- MonadState.lift tsType $ vhdl_ty error_msg tmp_ty
    -- Setup the generate scheme
    let gen_label = mkVHDLExtId ("iterateVector" ++ (varToString start))
    let block_label = mkVHDLExtId ("iterateVector" ++ (varToString res))
    -- Make the intermediate vector
    let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
    -- Create the generate statement
 -  cells <- sequence [genFirstCell, genOtherCell]
 +  cells' <- sequence [genFirstCell, genOtherCell]
 +  let (cells, useds) = unzip cells'
    let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
    -- Assign tmp[len-1] or tmp[0] to res
    let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr tmp_name    
    let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
 -  return [AST.CSBSm block]
 +  return ([AST.CSBSm block], concat useds)
    where
      -- An id for the counter
      n_id = mkVHDLBasicId "n"
      tmp_id = mkVHDLBasicId "tmp"
      tmp_name = AST.NSimple tmp_id
      -- Generate parts of the fold
 -    genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
 +    genFirstCell, genOtherCell :: TranslatorSession (AST.GenerateSm, [CoreSyn.CoreBndr])
      genFirstCell = do
        let cond_label = mkVHDLExtId "firstcell"
        -- if n == 0 or n == len-1
        -- Output to tmp[current n]
        let resname = mkIndexedName tmp_name n_cur
        -- Input from start
 -      argexpr <- MonadState.lift vsType $ varToVHDLExpr start
 +      argexpr <- MonadState.lift tsType $ varToVHDLExpr start
        let startassign = mkUncondAssign (Right resname) argexpr
 -      app_concsms <- genApplication (Right resname) app_f  [Right argexpr]
 +      (app_concsms, used) <- genApplication (Right resname) app_f  [Right argexpr]
        -- Return the conditional generate part
 -      return $ AST.GenerateSm cond_label cond_scheme [] (if iter then 
 +      let gensm = AST.GenerateSm cond_label cond_scheme [] (if iter then 
                                                            [startassign]
                                                           else 
                                                            app_concsms
                                                          )
 +      return (gensm, used)
  
      genOtherCell = do
        let cond_label = mkVHDLExtId "othercell"
        let resname = mkIndexedName tmp_name n_cur
        -- Input from tmp[previous n]
        let argexpr = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
 -      app_concsms <- genApplication (Right resname) app_f [Right argexpr]
 +      (app_concsms, used) <- genApplication (Right resname) app_f [Right argexpr]
        -- Return the conditional generate part
 -      return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
 +      return $ (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
  
  
  -----------------------------------------------------------------------------
@@@ -747,41 -581,40 +752,41 @@@ genApplication :
    (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
    -> CoreSyn.CoreBndr -- ^ The function to apply
    -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
 -  -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
 +  -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]) 
 +  -- ^ The corresponding VHDL concurrent statements and entities
 +  --   instantiated.
  genApplication dst f args = do
    case Var.isGlobalId f of
 -    False -> do
 -      signatures <- getA vsSignatures
 -      -- This is a local id, so it should be a function whose definition we
 -      -- have and which can be turned into a component instantiation.
 -      case (Map.lookup f signatures) of
 -        Just signature -> do
 -          args' <- eitherCoreOrExprArgs args
 -          -- We have a signature, this is a top level binding. Generate a
 +    False -> do 
 +      top <- isTopLevelBinder f
 +      case top of
 +        True -> do
 +          -- Local binder that references a top level binding.  Generate a
            -- component instantiation.
 +          signature <- getEntity f
 +          args' <- eitherCoreOrExprArgs args
            let entity_id = ent_id signature
            -- TODO: Using show here isn't really pretty, but we'll need some
            -- unique-ish value...
            let label = "comp_ins_" ++ (either show prettyShow) dst
            let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
 -          return [mkComponentInst label entity_id portmaps]
 -        Nothing -> do
 -          -- No signature, so this must be a local variable reference. It
 -          -- should have a representable type (and thus, no arguments) and a
 -          -- signal should be generated for it. Just generate an
 -          -- unconditional assignment here.
 -          f' <- MonadState.lift vsType $ varToVHDLExpr f
 -          return $ [mkUncondAssign dst f']
 +          return ([mkComponentInst label entity_id portmaps], [f])
 +        False -> do
 +          -- Not a top level binder, so this must be a local variable reference.
 +          -- It should have a representable type (and thus, no arguments) and a
 +          -- signal should be generated for it. Just generate an unconditional
 +          -- assignment here.
 +          f' <- MonadState.lift tsType $ varToVHDLExpr f
 +          return $ ([mkUncondAssign dst f'], [])
      True ->
        case Var.idDetails f of
          IdInfo.DataConWorkId dc -> case dst of
            -- It's a datacon. Create a record from its arguments.
            Left bndr -> do
              -- We have the bndr, so we can get at the type
 -            labels <- MonadState.lift vsType $ getFieldLabels (Var.varType bndr)
 +            labels <- MonadState.lift tsType $ getFieldLabels (Var.varType bndr)
              args' <- eitherCoreOrExprArgs args
 -            return $ zipWith mkassign labels $ args'
 +            return $ (zipWith mkassign labels $ args', [])
              where
                mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
                mkassign label arg =
@@@ -837,7 -670,7 +842,7 @@@ vectorFunId el_ty fname = d
    -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
    -- the VHDLState or something.
    let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
 -  typefuns <- getA vsTypeFuns
 +  typefuns <- getA tsTypeFuns
    case Map.lookup (OrdType el_ty, fname) typefuns of
      -- Function already generated, just return it
      Just (id, _) -> return id
        let functions = genUnconsVectorFuns elemTM vectorTM
        case lookup fname functions of
          Just body -> do
 -          modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, (fst body))
 +          modA tsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, (fst body))
            mapM_ (vectorFunId el_ty) (snd body)
            return function_id
          Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
@@@ -861,7 -694,8 +866,8 @@@ genUnconsVectorFuns elemTM vectorTM  
    , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet],[]))
    , (lastId, (AST.SubProgBody lastSpec    []                  [lastExpr],[]))
    , (initId, (AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet],[]))
-   , (takeId, (AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet],[]))
+   , (minimumId, (AST.SubProgBody minimumSpec [] [minimumExpr],[]))
+   , (takeId, (AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet],[minimumId]))
    , (dropId, (AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet],[]))
    , (plusgtId, (AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
    , (emptyId, (AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr],[]))
      vec1Par = AST.unsafeVHDLBasicId "vec1"
      vec2Par = AST.unsafeVHDLBasicId "vec2"
      nPar    = AST.unsafeVHDLBasicId "n"
+     leftPar = AST.unsafeVHDLBasicId "nLeft"
+     rightPar = AST.unsafeVHDLBasicId "nRight"
      iId     = AST.unsafeVHDLBasicId "i"
      iPar    = iId
      aPar    = AST.unsafeVHDLBasicId "a"
      fPar = AST.unsafeVHDLBasicId "f"
      sPar = AST.unsafeVHDLBasicId "s"
-     resId   = AST.unsafeVHDLBasicId "res"
+     resId   = AST.unsafeVHDLBasicId "res"    
      exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
                                 AST.IfaceVarDec ixPar  naturalTM] elemTM
      exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
                                    AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
                                                               AST.:-: AST.PrimLit "2"))
      initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
+     minimumSpec = AST.Function (mkVHDLExtId minimumId) [AST.IfaceVarDec leftPar   naturalTM,
+                                    AST.IfaceVarDec rightPar naturalTM ] naturalTM
+     minimumExpr = AST.IfSm ((AST.PrimName $ AST.NSimple leftPar) AST.:<: (AST.PrimName $ AST.NSimple rightPar))
+                         [AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple leftPar)]
+                         []
+                         (Just $ AST.Else [minimumExprRet])
+       where minimumExprRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple rightPar)
      takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
                                     AST.IfaceVarDec vecPar vectorTM ] vectorTM
-        -- variable res : fsvec_x (0 to n-1);
+        -- variable res : fsvec_x (0 to (minimum (n,vec'length))-1);
+     minLength = AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId minimumId))  
+                               [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple nPar)
+                               ,Nothing AST.:=>: AST.ADExpr (AST.PrimName (AST.NAttribute $ 
+                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]
      takeVar = 
           AST.VarDec resId 
                  (AST.SubtypeIn vectorTM
                    (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
                     [AST.ToRange (AST.PrimLit "0")
-                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
+                                (minLength AST.:-:
                                  (AST.PrimLit "1"))   ]))
                  Nothing
         -- res AST.:= vec(0 to n-1)
      takeExpr = AST.NSimple resId AST.:= 
-                     (vecSlice (AST.PrimLit "1") 
-                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
+                     (vecSlice (AST.PrimLit "0") 
+                               (minLength AST.:-: AST.PrimLit "1"))
      takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
      dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
                                     AST.IfaceVarDec vecPar vectorTM ] vectorTM 
  -- A table of builtin functions
  -----------------------------------------------------------------------------
  
 +-- A function that generates VHDL for a builtin function
 +type BuiltinBuilder = 
 +  (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ The destination signal and it's original type
 +  -> CoreSyn.CoreBndr -- ^ The function called
 +  -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The value arguments passed (excluding type and
 +                    --   dictionary arguments).
 +  -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]) 
 +  -- ^ The corresponding VHDL concurrent statements and entities
 +  --   instantiated.
 +
 +-- A map of a builtin function to VHDL function builder 
 +type NameTable = Map.Map String (Int, BuiltinBuilder )
 +
  -- | The builtin functions we support. Maps a name to an argument count and a
  -- builder function.
  globalNameTable :: NameTable
  globalNameTable = Map.fromList
-   [ (exId             , (2, genFCall False          ) )
+   [ (exId             , (2, genFCall True          ) )
    , (replaceId        , (3, genFCall False          ) )
    , (headId           , (1, genFCall True           ) )
    , (lastId           , (1, genFCall True           ) )
    , (fromIntegerId    , (1, genFromInteger          ) )
    , (resizeId         , (1, genResize               ) )
    , (sizedIntId       , (1, genSizedInt             ) )
 -  , (tfvecId          , (1, genTFVec                ) )
 +  --, (tfvecId          , (1, genTFVec                ) )
+   , (minimumId        , (2, error $ "\nFunction name: \"minimum\" is used internally, use another name"))
    ]