Added "lengthT"
[matthijs/master-project/cλash.git] / Generate.hs
1 module Generate where
2
3 -- Standard modules
4 import qualified Control.Monad as Monad
5 import qualified Data.Map as Map
6 import qualified Maybe
7 import qualified Data.Either as Either
8 import Data.Accessor
9 import Debug.Trace
10
11 -- ForSyDe
12 import qualified ForSyDe.Backend.VHDL.AST as AST
13
14 -- GHC API
15 import CoreSyn
16 import Type
17 import qualified Var
18 import qualified IdInfo
19
20 -- Local imports
21 import Constants
22 import VHDLTypes
23 import VHDLTools
24 import CoreTools
25 import Pretty
26
27 -----------------------------------------------------------------------------
28 -- Functions to generate VHDL for builtin functions
29 -----------------------------------------------------------------------------
30
31 -- | A function to wrap a builder-like function that expects its arguments to
32 -- be expressions.
33 genExprArgs ::
34   (dst -> func -> [AST.Expr] -> res)
35   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
36 genExprArgs wrap dst func args = wrap dst func args'
37   where args' = map (either (varToVHDLExpr.exprToVar) id) args
38   
39 -- | A function to wrap a builder-like function that expects its arguments to
40 -- be variables.
41 genVarArgs ::
42   (dst -> func -> [Var.Var] -> res)
43   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
44 genVarArgs wrap dst func args = wrap dst func args'
45   where
46     args' = map exprToVar exprargs
47     -- Check (rather crudely) that all arguments are CoreExprs
48     (exprargs, []) = Either.partitionEithers args
49
50 -- | A function to wrap a builder-like function that produces an expression
51 -- and expects it to be assigned to the destination.
52 genExprRes ::
53   ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession AST.Expr)
54   -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession [AST.ConcSm])
55 genExprRes wrap dst func args = do
56   expr <- wrap dst func args
57   return $ [mkUncondAssign dst expr]
58
59 -- | Generate a binary operator application. The first argument should be a
60 -- constructor from the AST.Expr type, e.g. AST.And.
61 genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder 
62 genOperator2 op = genExprArgs $ genExprRes (genOperator2' op)
63 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
64 genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
65
66 -- | Generate a unary operator application
67 genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder 
68 genOperator1 op = genExprArgs $ genExprRes (genOperator1' op)
69 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
70 genOperator1' op _ f [arg] = return $ op arg
71
72 -- | Generate a function call from the destination binder, function name and a
73 -- list of expressions (its arguments)
74 genFCall :: BuiltinBuilder 
75 genFCall = genExprArgs $ genExprRes genFCall'
76 genFCall' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
77 genFCall' (Left res) f args = do
78   let fname = varToString f
79   let el_ty = (tfvec_elem . Var.varType) res
80   id <- vectorFunId el_ty fname
81   return $ AST.PrimFCall $ AST.FCall (AST.NSimple id)  $
82              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
83 genFCall' (Right name) _ _ = error $ "Cannot generate builtin function call assigned to a VHDLName: " ++ show name
84
85 -- | Generate a generate statement for the builtin function "map"
86 genMap :: BuiltinBuilder
87 genMap = genVarArgs genMap'
88 genMap' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
89 genMap' (Left res) f [mapped_f, arg] =
90   let
91     -- Setup the generate scheme
92     len         = (tfvec_len . Var.varType) res
93     -- TODO: Use something better than varToString
94     label       = mkVHDLExtId ("mapVector" ++ (varToString res))
95     n_id        = mkVHDLBasicId "n"
96     n_expr      = idToVHDLExpr n_id
97     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
98     genScheme   = AST.ForGn n_id range
99
100     -- Create the content of the generate statement: Applying the mapped_f to
101     -- each of the elements in arg, storing to each element in res
102     resname     = mkIndexedName (varToVHDLName res) n_expr
103     argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
104   in do
105     app_concsms <- genApplication (Right resname) mapped_f [Right argexpr]
106     -- Return the generate statement
107     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
108
109 genMap' (Right name) _ _ = error $ "Cannot generate map function call assigned to a VHDLName: " ++ show name
110     
111 genZipWith :: BuiltinBuilder
112 genZipWith = genVarArgs genZipWith'
113 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
114 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] =
115   let
116     -- Setup the generate scheme
117     len         = (tfvec_len . Var.varType) res
118     -- TODO: Use something better than varToString
119     label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
120     n_id        = mkVHDLBasicId "n"
121     n_expr      = idToVHDLExpr n_id
122     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
123     genScheme   = AST.ForGn n_id range
124
125     -- Create the content of the generate statement: Applying the zipped_f to
126     -- each of the elements in arg1 and arg2, storing to each element in res
127     resname     = mkIndexedName (varToVHDLName res) n_expr
128     argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
129     argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
130   in do
131     app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
132     -- Return the generate functions
133     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
134
135 genFoldl :: BuiltinBuilder
136 genFoldl = genFold True
137
138 genFoldr :: BuiltinBuilder
139 genFoldr = genFold False
140
141 genFold :: Bool -> BuiltinBuilder
142 genFold left = genVarArgs (genFold' left)
143 genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
144 -- Special case for an empty input vector, just assign start to res
145 genFold' left (Left res) _ [_, start, vec] | len == 0 = return [mkUncondAssign (Left res) (varToVHDLExpr start)]
146     where len = (tfvec_len . Var.varType) vec
147 genFold' left (Left res) f [folded_f, start, vec] = do
148   -- evec is (TFVec n), so it still needs an element type
149   let (nvec, _) = splitAppTy (Var.varType vec)
150   -- Put the type of the start value in nvec, this will be the type of our
151   -- temporary vector
152   let tmp_ty = Type.mkAppTy nvec (Var.varType start)
153   tmp_vhdl_ty <- vhdl_ty tmp_ty
154   -- Setup the generate scheme
155   let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
156   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString start))
157   let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
158                   else AST.DownRange len_min_expr (AST.PrimLit "0")
159   let gen_scheme   = AST.ForGn n_id gen_range
160   -- Make the intermediate vector
161   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
162   -- Create the generate statement
163   cells <- sequence [genFirstCell, genOtherCell]
164   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
165   -- Assign tmp[len-1] or tmp[0] to res
166   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
167                     (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
168                     (mkIndexedName tmp_name (AST.PrimLit "0")))      
169   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
170   return [AST.CSBSm block]
171   where
172     -- The vector length
173     len         = (tfvec_len . Var.varType) vec
174     -- An id for the counter
175     n_id = mkVHDLBasicId "n"
176     n_cur = idToVHDLExpr n_id
177     -- An expression for previous n
178     n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
179                      else (n_cur AST.:+: (AST.PrimLit "1"))
180     -- An expression for len-1
181     len_min_expr = (AST.PrimLit $ show (len-1))
182     -- An id for the tmp result vector
183     tmp_id = mkVHDLBasicId "tmp"
184     tmp_name = AST.NSimple tmp_id
185     -- Generate parts of the fold
186     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
187     genFirstCell = do
188       let cond_label = mkVHDLExtId "firstcell"
189       -- if n == 0 or n == len-1
190       let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
191                                                   else (AST.PrimLit $ show (len-1)))
192       -- Output to tmp[current n]
193       let resname = mkIndexedName tmp_name n_cur
194       -- Input from start
195       let argexpr1 = varToVHDLExpr start
196       -- Input from vec[current n]
197       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
198       app_concsms <- genApplication (Right resname) folded_f  ( if left then
199                                                                   [Right argexpr1, Right argexpr2]
200                                                                 else
201                                                                   [Right argexpr2, Right argexpr1]
202                                                               )
203       -- Return the conditional generate part
204       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
205
206     genOtherCell = do
207       let cond_label = mkVHDLExtId "othercell"
208       -- if n > 0 or n < len-1
209       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
210                                                    else (AST.PrimLit $ show (len-1)))
211       -- Output to tmp[current n]
212       let resname = mkIndexedName tmp_name n_cur
213       -- Input from tmp[previous n]
214       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
215       -- Input from vec[current n]
216       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
217       app_concsms <- genApplication (Right resname) folded_f  ( if left then
218                                                                   [Right argexpr1, Right argexpr2]
219                                                                 else
220                                                                   [Right argexpr2, Right argexpr1]
221                                                               )
222       -- Return the conditional generate part
223       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
224
225 -- | Generate a generate statement for the builtin function "zip"
226 genZip :: BuiltinBuilder
227 genZip = genVarArgs genZip'
228 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
229 genZip' (Left res) f args@[arg1, arg2] =
230   let
231     -- Setup the generate scheme
232     len             = (tfvec_len . Var.varType) res
233     -- TODO: Use something better than varToString
234     label           = mkVHDLExtId ("zipVector" ++ (varToString res))
235     n_id            = mkVHDLBasicId "n"
236     n_expr          = idToVHDLExpr n_id
237     range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
238     genScheme       = AST.ForGn n_id range
239     resname'        = mkIndexedName (varToVHDLName res) n_expr
240     argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
241     argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
242   in do
243     labels <- getFieldLabels (tfvec_elem (Var.varType res))
244     let resnameA    = mkSelectedName resname' (labels!!0)
245     let resnameB    = mkSelectedName resname' (labels!!1)
246     let resA_assign = mkUncondAssign (Right resnameA) argexpr1
247     let resB_assign = mkUncondAssign (Right resnameB) argexpr2
248     -- Return the generate functions
249     return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
250     
251 -- | Generate a generate statement for the builtin function "unzip"
252 genUnzip :: BuiltinBuilder
253 genUnzip = genVarArgs genUnzip'
254 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
255 genUnzip' (Left res) f args@[arg] =
256   let
257     -- Setup the generate scheme
258     len             = (tfvec_len . Var.varType) arg
259     -- TODO: Use something better than varToString
260     label           = mkVHDLExtId ("unzipVector" ++ (varToString res))
261     n_id            = mkVHDLBasicId "n"
262     n_expr          = idToVHDLExpr n_id
263     range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
264     genScheme       = AST.ForGn n_id range
265     resname'        = varToVHDLName res
266     argexpr'        = mkIndexedName (varToVHDLName arg) n_expr
267   in do
268     reslabels <- getFieldLabels (Var.varType res)
269     arglabels <- getFieldLabels (tfvec_elem (Var.varType arg))
270     let resnameA    = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
271     let resnameB    = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
272     let argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
273     let argexprB    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
274     let resA_assign = mkUncondAssign (Right resnameA) argexprA
275     let resB_assign = mkUncondAssign (Right resnameB) argexprB
276     -- Return the generate functions
277     return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
278
279 -----------------------------------------------------------------------------
280 -- Function to generate VHDL for applications
281 -----------------------------------------------------------------------------
282 genApplication ::
283   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
284   -> CoreSyn.CoreBndr -- ^ The function to apply
285   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
286   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
287 genApplication dst f args =
288   case Var.globalIdVarDetails f of
289     IdInfo.DataConWorkId dc -> case dst of
290       -- It's a datacon. Create a record from its arguments.
291       Left bndr -> do
292         -- We have the bndr, so we can get at the type
293         labels <- getFieldLabels (Var.varType bndr)
294         return $ zipWith mkassign labels $ map (either exprToVHDLExpr id) args
295         where
296           mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
297           mkassign label arg =
298             let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
299             mkUncondAssign (Right sel_name) arg
300       Right _ -> error $ "Generate.genApplication Can't generate dataconstructor application without an original binder"
301     IdInfo.VanillaGlobal -> do
302       -- It's a global value imported from elsewhere. These can be builtin
303       -- functions. Look up the function name in the name table and execute
304       -- the associated builder if there is any and the argument count matches
305       -- (this should always be the case if it typechecks, but just to be
306       -- sure...).
307       case (Map.lookup (varToString f) globalNameTable) of
308         Just (arg_count, builder) ->
309           if length args == arg_count then
310             builder dst f args
311           else
312             error $ "Generate.genApplication Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
313         Nothing -> error $ "Using function from another module that is not a known builtin: " ++ pprString f
314     IdInfo.NotGlobalId -> do
315       signatures <- getA vsSignatures
316       -- This is a local id, so it should be a function whose definition we
317       -- have and which can be turned into a component instantiation.
318       let  
319         signature = Maybe.fromMaybe 
320           (error $ "Using function '" ++ (varToString f) ++ "' without signature? This should not happen!") 
321           (Map.lookup f signatures)
322         entity_id = ent_id signature
323         -- TODO: Using show here isn't really pretty, but we'll need some
324         -- unique-ish value...
325         label = "comp_ins_" ++ (either show prettyShow) dst
326         portmaps = mkAssocElems (map (either exprToVHDLExpr id) args) ((either varToVHDLName id) dst) signature
327         in
328           return [mkComponentInst label entity_id portmaps]
329     details -> error $ "Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
330
331 -----------------------------------------------------------------------------
332 -- Functions to generate functions dealing with vectors.
333 -----------------------------------------------------------------------------
334
335 -- Returns the VHDLId of the vector function with the given name for the given
336 -- element type. Generates -- this function if needed.
337 vectorFunId :: Type.Type -> String -> VHDLSession AST.VHDLId
338 vectorFunId el_ty fname = do
339   elemTM <- vhdl_ty el_ty
340   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
341   -- the VHDLState or something.
342   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
343   typefuns <- getA vsTypeFuns
344   case Map.lookup (OrdType el_ty, fname) typefuns of
345     -- Function already generated, just return it
346     Just (id, _) -> return id
347     -- Function not generated yet, generate it
348     Nothing -> do
349       let functions = genUnconsVectorFuns elemTM vectorTM
350       case lookup fname functions of
351         Just body -> do
352           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, body)
353           return function_id
354         Nothing -> error $ "I don't know how to generate vector function " ++ fname
355   where
356     function_id = mkVHDLExtId fname
357
358 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
359                     -> AST.TypeMark -- ^ type of the vector
360                     -> [(String, AST.SubProgBody)]
361 genUnconsVectorFuns elemTM vectorTM  = 
362   [ (exId, AST.SubProgBody exSpec      []                  [exExpr])
363   , (replaceId, AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet])
364   , (headId, AST.SubProgBody headSpec    []                  [headExpr])
365   , (lastId, AST.SubProgBody lastSpec    []                  [lastExpr])
366   , (initId, AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet])
367   , (tailId, AST.SubProgBody tailSpec    [AST.SPVD tailVar]  [tailExpr, tailRet])
368   , (takeId, AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet])
369   , (dropId, AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet])
370   , (plusgtId, AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet])
371   , (emptyId, AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr])
372   , (singletonId, AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet])
373   , (copyId, AST.SubProgBody copySpec    [AST.SPVD copyVar]      [copyExpr])
374   , (selId, AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet])
375   , (ltplusId, AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet]  )  
376   , (plusplusId, AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet])
377   , (lengthTId, AST.SubProgBody lengthTSpec [] [lengthTExpr])
378   ]
379   where 
380     ixPar   = AST.unsafeVHDLBasicId "ix"
381     vecPar  = AST.unsafeVHDLBasicId "vec"
382     vec1Par = AST.unsafeVHDLBasicId "vec1"
383     vec2Par = AST.unsafeVHDLBasicId "vec2"
384     nPar    = AST.unsafeVHDLBasicId "n"
385     iId     = AST.unsafeVHDLBasicId "i"
386     iPar    = iId
387     aPar    = AST.unsafeVHDLBasicId "a"
388     fPar = AST.unsafeVHDLBasicId "f"
389     sPar = AST.unsafeVHDLBasicId "s"
390     resId   = AST.unsafeVHDLBasicId "res"
391     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
392                                AST.IfaceVarDec ixPar  naturalTM] elemTM
393     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
394               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
395                 AST.NSimple ixPar]))
396     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
397                                           , AST.IfaceVarDec iPar   naturalTM
398                                           , AST.IfaceVarDec aPar   elemTM
399                                           ] vectorTM 
400        -- variable res : fsvec_x (0 to vec'length-1);
401     replaceVar =
402          AST.VarDec resId 
403                 (AST.SubtypeIn vectorTM
404                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
405                    [AST.ToRange (AST.PrimLit "0")
406                             (AST.PrimName (AST.NAttribute $ 
407                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
408                                 (AST.PrimLit "1"))   ]))
409                 Nothing
410        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
411     replaceExpr = AST.NSimple resId AST.:=
412            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
413             AST.PrimName (AST.NSimple aPar) AST.:&: 
414              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
415                       ((AST.PrimName (AST.NAttribute $ 
416                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
417                                                               AST.:-: AST.PrimLit "1"))
418     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
419     vecSlice init last =  AST.PrimName (AST.NSlice 
420                                         (AST.SliceName 
421                                               (AST.NSimple vecPar) 
422                                               (AST.ToRange init last)))
423     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
424        -- return vec(0);
425     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
426                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
427     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
428        -- return vec(vec'length-1);
429     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
430                     (AST.NSimple vecPar) 
431                     [AST.PrimName (AST.NAttribute $ 
432                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
433                                                              AST.:-: AST.PrimLit "1"])))
434     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
435        -- variable res : fsvec_x (0 to vec'length-2);
436     initVar = 
437          AST.VarDec resId 
438                 (AST.SubtypeIn vectorTM
439                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
440                    [AST.ToRange (AST.PrimLit "0")
441                             (AST.PrimName (AST.NAttribute $ 
442                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
443                                 (AST.PrimLit "2"))   ]))
444                 Nothing
445        -- resAST.:= vec(0 to vec'length-2)
446     initExpr = AST.NSimple resId AST.:= (vecSlice 
447                                (AST.PrimLit "0") 
448                                (AST.PrimName (AST.NAttribute $ 
449                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
450                                                              AST.:-: AST.PrimLit "2"))
451     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
452     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
453        -- variable res : fsvec_x (0 to vec'length-2); 
454     tailVar = 
455          AST.VarDec resId 
456                 (AST.SubtypeIn vectorTM
457                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
458                    [AST.ToRange (AST.PrimLit "0")
459                             (AST.PrimName (AST.NAttribute $ 
460                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
461                                 (AST.PrimLit "2"))   ]))
462                 Nothing       
463        -- res AST.:= vec(1 to vec'length-1)
464     tailExpr = AST.NSimple resId AST.:= (vecSlice 
465                                (AST.PrimLit "1") 
466                                (AST.PrimName (AST.NAttribute $ 
467                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
468                                                              AST.:-: AST.PrimLit "1"))
469     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
470     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
471                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
472        -- variable res : fsvec_x (0 to n-1);
473     takeVar = 
474          AST.VarDec resId 
475                 (AST.SubtypeIn vectorTM
476                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
477                    [AST.ToRange (AST.PrimLit "0")
478                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
479                                 (AST.PrimLit "1"))   ]))
480                 Nothing
481        -- res AST.:= vec(0 to n-1)
482     takeExpr = AST.NSimple resId AST.:= 
483                     (vecSlice (AST.PrimLit "1") 
484                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
485     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
486     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
487                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
488        -- variable res : fsvec_x (0 to vec'length-n-1);
489     dropVar = 
490          AST.VarDec resId 
491                 (AST.SubtypeIn vectorTM
492                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
493                    [AST.ToRange (AST.PrimLit "0")
494                             (AST.PrimName (AST.NAttribute $ 
495                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
496                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
497                Nothing
498        -- res AST.:= vec(n to vec'length-1)
499     dropExpr = AST.NSimple resId AST.:= (vecSlice 
500                                (AST.PrimName $ AST.NSimple nPar) 
501                                (AST.PrimName (AST.NAttribute $ 
502                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
503                                                              AST.:-: AST.PrimLit "1"))
504     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
505     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
506                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
507     -- variable res : fsvec_x (0 to vec'length);
508     plusgtVar = 
509       AST.VarDec resId 
510              (AST.SubtypeIn vectorTM
511                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
512                 [AST.ToRange (AST.PrimLit "0")
513                         (AST.PrimName (AST.NAttribute $ 
514                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
515              Nothing
516     plusgtExpr = AST.NSimple resId AST.:= 
517                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
518                     (AST.PrimName $ AST.NSimple vecPar))
519     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
520     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
521     emptyVar = 
522           AST.ConstDec resId 
523               (AST.SubtypeIn vectorTM Nothing)
524               (Just $ AST.PrimLit "\"\"")
525     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
526     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
527                                          vectorTM
528     -- variable res : fsvec_x (0 to 0) := (others => a);
529     singletonVar = 
530       AST.VarDec resId 
531              (AST.SubtypeIn vectorTM
532                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
533                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
534              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
535                                           (AST.PrimName $ AST.NSimple aPar)])
536     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
537     copySpec = AST.Function (mkVHDLExtId copyId) [AST.IfaceVarDec nPar   naturalTM,
538                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
539     -- variable res : fsvec_x (0 to n-1) := (others => a);
540     copyVar = 
541       AST.VarDec resId 
542              (AST.SubtypeIn vectorTM
543                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
544                 [AST.ToRange (AST.PrimLit "0")
545                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
546                              (AST.PrimLit "1"))   ]))
547              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
548                                           (AST.PrimName $ AST.NSimple aPar)])
549     -- return res
550     copyExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
551     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
552                                AST.IfaceVarDec sPar   naturalTM,
553                                AST.IfaceVarDec nPar   naturalTM,
554                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
555     -- variable res : fsvec_x (0 to n-1);
556     selVar = 
557       AST.VarDec resId 
558                 (AST.SubtypeIn vectorTM
559                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
560                     [AST.ToRange (AST.PrimLit "0")
561                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
562                       (AST.PrimLit "1"))   ])
563                 )
564                 Nothing
565     -- for i res'range loop
566     --   res(i) := vec(f+i*s);
567     -- end loop;
568     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [selAssign]
569     -- res(i) := vec(f+i*s);
570     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
571                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
572                                   AST.PrimName (AST.NSimple sPar)) in
573                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
574                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
575     -- return res;
576     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
577     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
578                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
579      -- variable res : fsvec_x (0 to vec'length);
580     ltplusVar = 
581       AST.VarDec resId 
582         (AST.SubtypeIn vectorTM
583           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
584             [AST.ToRange (AST.PrimLit "0")
585               (AST.PrimName (AST.NAttribute $ 
586                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
587         Nothing
588     ltplusExpr = AST.NSimple resId AST.:= 
589                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
590                       (AST.PrimName $ AST.NSimple aPar))
591     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
592     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
593                                              AST.IfaceVarDec vec2Par vectorTM] 
594                                              vectorTM 
595     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
596     plusplusVar = 
597       AST.VarDec resId 
598         (AST.SubtypeIn vectorTM
599           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
600             [AST.ToRange (AST.PrimLit "0")
601               (AST.PrimName (AST.NAttribute $ 
602                 AST.AttribName (AST.NSimple vec1Par) (mkVHDLBasicId lengthId) Nothing) AST.:+:
603                   AST.PrimName (AST.NAttribute $ 
604                 AST.AttribName (AST.NSimple vec2Par) (mkVHDLBasicId lengthId) Nothing) AST.:-:
605                   AST.PrimLit "1")]))
606        Nothing
607     plusplusExpr = AST.NSimple resId AST.:= 
608                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
609                       (AST.PrimName $ AST.NSimple vec2Par))
610     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
611     lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
612     lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $ 
613                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))
614
615 -----------------------------------------------------------------------------
616 -- A table of builtin functions
617 -----------------------------------------------------------------------------
618
619 -- | The builtin functions we support. Maps a name to an argument count and a
620 -- builder function.
621 globalNameTable :: NameTable
622 globalNameTable = Map.fromList
623   [ (exId             , (2, genFCall                ) )
624   , (replaceId        , (3, genFCall                ) )
625   , (headId           , (1, genFCall                ) )
626   , (lastId           , (1, genFCall                ) )
627   , (tailId           , (1, genFCall                ) )
628   , (initId           , (1, genFCall                ) )
629   , (takeId           , (2, genFCall                ) )
630   , (dropId           , (2, genFCall                ) )
631   , (selId            , (4, genFCall                ) )
632   , (plusgtId         , (2, genFCall                ) )
633   , (ltplusId         , (2, genFCall                ) )
634   , (plusplusId       , (2, genFCall                ) )
635   , (mapId            , (2, genMap                  ) )
636   , (zipWithId        , (3, genZipWith              ) )
637   , (foldlId          , (3, genFoldl                ) )
638   , (foldrId          , (3, genFoldr                ) )
639   , (zipId            , (2, genZip                  ) )
640   , (unzipId          , (1, genUnzip                ) )
641   , (emptyId          , (0, genFCall                ) )
642   , (singletonId      , (1, genFCall                ) )
643   , (copyId           , (2, genFCall                ) )
644   , (lengthTId        , (1, genFCall                ) )
645   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
646   , (hwandId          , (2, genOperator2 AST.And    ) )
647   , (hworId           , (2, genOperator2 AST.Or     ) )
648   , (hwnotId          , (1, genOperator1 AST.Not    ) )
649   ]