4f0acf319760946a632e5a5b45970164c1b8e0dc
[matthijs/master-project/cλash.git] / Generate.hs
1 {-# LANGUAGE PackageImports #-}
2
3 module Generate where
4
5 -- Standard modules
6 import qualified Control.Monad as Monad
7 import qualified Data.Map as Map
8 import qualified Maybe
9 import qualified Data.Either as Either
10 import qualified Control.Monad.Trans.State as State
11 import qualified "transformers" Control.Monad.Identity as Identity
12 import Data.Accessor
13 import Data.Accessor.MonadState as MonadState
14 import Debug.Trace
15
16 -- ForSyDe
17 import qualified ForSyDe.Backend.VHDL.AST as AST
18
19 -- GHC API
20 import CoreSyn
21 import Type
22 import qualified Var
23 import qualified IdInfo
24 import qualified Literal
25 import qualified Name
26 import qualified TyCon
27
28 -- Local imports
29 import Constants
30 import VHDLTypes
31 import VHDLTools
32 import CoreTools
33 import Pretty
34
35 -----------------------------------------------------------------------------
36 -- Functions to generate VHDL for builtin functions
37 -----------------------------------------------------------------------------
38
39 -- | A function to wrap a builder-like function that expects its arguments to
40 -- be expressions.
41 genExprArgs ::
42   TypeState
43   -> (dst -> func -> [AST.Expr] -> res)
44   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
45 genExprArgs ty_state wrap dst func args = wrap dst func args'
46   where args' = map (either ((varToVHDLExpr ty_state).exprToVar) id) args
47
48 -- | A function to wrap a builder-like function that expects its arguments to
49 -- be variables.
50 genVarArgs ::
51   (dst -> func -> [Var.Var] -> res)
52   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
53 genVarArgs wrap dst func args = wrap dst func args'
54   where
55     args' = map exprToVar exprargs
56     -- Check (rather crudely) that all arguments are CoreExprs
57     (exprargs, []) = Either.partitionEithers args
58
59 -- | A function to wrap a builder-like function that expects its arguments to
60 -- be Literals
61 genLitArgs ::
62   (dst -> func -> [Literal.Literal] -> res)
63   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
64 genLitArgs wrap dst func args = wrap dst func args'
65   where
66     args' = map exprToLit litargs
67     -- FIXME: Check if we were passed an CoreSyn.App
68     litargs = concat (map getLiterals exprargs)
69     (exprargs, []) = Either.partitionEithers args
70
71 -- | A function to wrap a builder-like function that produces an expression
72 -- and expects it to be assigned to the destination.
73 genExprRes ::
74   ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession AST.Expr)
75   -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession [AST.ConcSm])
76 genExprRes wrap dst func args = do
77   expr <- wrap dst func args
78   return $ [mkUncondAssign dst expr]
79
80 -- | Generate a binary operator application. The first argument should be a
81 -- constructor from the AST.Expr type, e.g. AST.And.
82 genOperator2 :: TypeState -> (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder 
83 genOperator2 ty_state op = (genExprArgs ty_state) $ genExprRes (genOperator2' op)
84 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
85 genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
86
87 -- | Generate a unary operator application
88 genOperator1 :: TypeState -> (AST.Expr -> AST.Expr) -> BuiltinBuilder 
89 genOperator1 ty_state op = (genExprArgs ty_state) $ genExprRes (genOperator1' op)
90 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
91 genOperator1' op _ f [arg] = return $ op arg
92
93 -- | Generate a unary operator application
94 genNegation :: TypeState -> BuiltinBuilder 
95 genNegation ty_state = genVarArgs $ genExprRes (genNegation' ty_state)
96 genNegation' :: TypeState -> dst -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession AST.Expr
97 genNegation' ty_state _ f [arg] = return $ op ((varToVHDLExpr ty_state) arg)
98   where
99     ty = Var.varType arg
100     (tycon, args) = Type.splitTyConApp ty
101     name = Name.getOccString (TyCon.tyConName tycon)
102     op = case name of
103       "SizedInt" -> AST.Neg
104       otherwise -> error $ "\nGenerate.genNegation': Negation allowed for type: " ++ show name 
105
106 -- | Generate a function call from the destination binder, function name and a
107 -- list of expressions (its arguments)
108 genFCall :: TypeState -> Bool -> BuiltinBuilder 
109 genFCall ty_state switch = (genExprArgs ty_state) $ genExprRes (genFCall' switch)
110 genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
111 genFCall' switch (Left res) f args = do
112   let fname = varToString f
113   let el_ty = if switch then (Var.varType res) else ((tfvec_elem . Var.varType) res)
114   id <- MonadState.lift vsType $ vectorFunId el_ty fname
115   return $ AST.PrimFCall $ AST.FCall (AST.NSimple id)  $
116              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
117 genFCall' _ (Right name) _ _ = error $ "\nGenerate.genFCall': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
118
119 genFromSizedWord :: TypeState -> BuiltinBuilder
120 genFromSizedWord ty_state = (genExprArgs ty_state) $ genExprRes genFromSizedWord'
121 genFromSizedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
122 genFromSizedWord' (Left res) f args = do
123   let fname = varToString f
124   return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId toIntegerId))  $
125              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
126 genFromSizedWord' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
127
128 -- FIXME: I'm calling genLitArgs which is very specific function,
129 -- which needs to be fixed as well
130 genFromInteger :: BuiltinBuilder
131 genFromInteger = genLitArgs $ genExprRes genFromInteger'
132 genFromInteger' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [Literal.Literal] -> VHDLSession AST.Expr
133 genFromInteger' (Left res) f lits = do {
134   ; let { ty = Var.varType res
135         ; (tycon, args) = Type.splitTyConApp ty
136         ; name = Name.getOccString (TyCon.tyConName tycon)
137         } ;
138   ; len <- case name of
139     "SizedInt" -> MonadState.lift vsType $ tfp_to_int (sized_int_len_ty ty)
140     "SizedWord" -> MonadState.lift vsType $ tfp_to_int (sized_word_len_ty ty)
141   ; let fname = case name of "SizedInt" -> toSignedId ; "SizedWord" -> toUnsignedId
142   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId fname)) 
143             [Nothing AST.:=>: AST.ADExpr (AST.PrimLit (show (last lits))), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
144   }
145
146 genFromInteger' (Right name) _ _ = error $ "\nGenerate.genFromInteger': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
147
148
149 -- | Generate a generate statement for the builtin function "map"
150 genMap :: BuiltinBuilder
151 genMap (Left res) f [Left mapped_f, Left (Var arg)] = do {
152   -- mapped_f must be a CoreExpr (since we can't represent functions as VHDL
153   -- expressions). arg must be a CoreExpr (and should be a CoreSyn.Var), since
154   -- we must index it (which we couldn't if it was a VHDL Expr, since only
155   -- VHDLNames can be indexed).
156   -- Setup the generate scheme
157   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
158           -- TODO: Use something better than varToString
159   ; let { label       = mkVHDLExtId ("mapVector" ++ (varToString res))
160         ; n_id        = mkVHDLBasicId "n"
161         ; n_expr      = idToVHDLExpr n_id
162         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
163         ; genScheme   = AST.ForGn n_id range
164           -- Create the content of the generate statement: Applying the mapped_f to
165           -- each of the elements in arg, storing to each element in res
166         ; resname     = mkIndexedName (varToVHDLName res) n_expr
167         ; argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
168         ; (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
169         ; valargs = get_val_args (Var.varType real_f) already_mapped_args
170         } ;
171   ; app_concsms <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
172     -- Return the generate statement
173   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
174   }
175
176 genMap' (Right name) _ _ = error $ "\nGenerate.genMap': Cannot generate map function call assigned to a VHDLName: " ++ show name
177     
178 genZipWith :: BuiltinBuilder
179 genZipWith = genVarArgs genZipWith'
180 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
181 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] = do {
182   -- Setup the generate scheme
183   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
184           -- TODO: Use something better than varToString
185   ; let { label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
186         ; n_id        = mkVHDLBasicId "n"
187         ; n_expr      = idToVHDLExpr n_id
188         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
189         ; genScheme   = AST.ForGn n_id range
190           -- Create the content of the generate statement: Applying the zipped_f to
191           -- each of the elements in arg1 and arg2, storing to each element in res
192         ; resname     = mkIndexedName (varToVHDLName res) n_expr
193         ; argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
194         ; argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
195         } ;
196   ; app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
197     -- Return the generate functions
198   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
199   }
200
201 genFoldl :: TypeState -> BuiltinBuilder
202 genFoldl ty_state = genFold ty_state True
203
204 genFoldr :: TypeState -> BuiltinBuilder
205 genFoldr ty_state = genFold ty_state False
206
207 genFold :: TypeState -> Bool -> BuiltinBuilder
208 genFold ty_state left = genVarArgs (genFold' ty_state left)
209 genFold' :: TypeState -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
210 -- Special case for an empty input vector, just assign start to res
211 genFold' ty_state left (Left res) _ [_, start, vec] | len == 0 = return [mkUncondAssign (Left res) ((varToVHDLExpr ty_state) start)]
212   where 
213     len = State.evalState (tfp_to_int $ (tfvec_len_ty . Var.varType) vec) ty_state
214     
215 genFold' ty_state left (Left res) f [folded_f, start, vec] = do
216   -- The vector length
217   len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
218   -- An expression for len-1
219   let len_min_expr = (AST.PrimLit $ show (len-1))
220   -- evec is (TFVec n), so it still needs an element type
221   let (nvec, _) = splitAppTy (Var.varType vec)
222   -- Put the type of the start value in nvec, this will be the type of our
223   -- temporary vector
224   let tmp_ty = Type.mkAppTy nvec (Var.varType start)
225   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
226   tmp_vhdl_ty <- MonadState.lift vsType $ vhdl_ty error_msg tmp_ty
227   -- Setup the generate scheme
228   let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
229   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString start))
230   let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
231                   else AST.DownRange len_min_expr (AST.PrimLit "0")
232   let gen_scheme   = AST.ForGn n_id gen_range
233   -- Make the intermediate vector
234   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
235   -- Create the generate statement
236   cells <- sequence [genFirstCell, genOtherCell]
237   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
238   -- Assign tmp[len-1] or tmp[0] to res
239   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
240                     (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
241                     (mkIndexedName tmp_name (AST.PrimLit "0")))      
242   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
243   return [AST.CSBSm block]
244   where
245     -- An id for the counter
246     n_id = mkVHDLBasicId "n"
247     n_cur = idToVHDLExpr n_id
248     -- An expression for previous n
249     n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
250                      else (n_cur AST.:+: (AST.PrimLit "1"))
251     -- An id for the tmp result vector
252     tmp_id = mkVHDLBasicId "tmp"
253     tmp_name = AST.NSimple tmp_id
254     -- Generate parts of the fold
255     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
256     genFirstCell = do
257       len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
258       let cond_label = mkVHDLExtId "firstcell"
259       -- if n == 0 or n == len-1
260       let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
261                                                   else (AST.PrimLit $ show (len-1)))
262       -- Output to tmp[current n]
263       let resname = mkIndexedName tmp_name n_cur
264       -- Input from start
265       let argexpr1 = (varToVHDLExpr ty_state) start
266       -- Input from vec[current n]
267       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
268       app_concsms <- genApplication (Right resname) folded_f  ( if left then
269                                                                   [Right argexpr1, Right argexpr2]
270                                                                 else
271                                                                   [Right argexpr2, Right argexpr1]
272                                                               )
273       -- Return the conditional generate part
274       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
275
276     genOtherCell = do
277       len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
278       let cond_label = mkVHDLExtId "othercell"
279       -- if n > 0 or n < len-1
280       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
281                                                    else (AST.PrimLit $ show (len-1)))
282       -- Output to tmp[current n]
283       let resname = mkIndexedName tmp_name n_cur
284       -- Input from tmp[previous n]
285       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
286       -- Input from vec[current n]
287       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
288       app_concsms <- genApplication (Right resname) folded_f  ( if left then
289                                                                   [Right argexpr1, Right argexpr2]
290                                                                 else
291                                                                   [Right argexpr2, Right argexpr1]
292                                                               )
293       -- Return the conditional generate part
294       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
295
296 -- | Generate a generate statement for the builtin function "zip"
297 genZip :: BuiltinBuilder
298 genZip = genVarArgs genZip'
299 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
300 genZip' (Left res) f args@[arg1, arg2] = do {
301     -- Setup the generate scheme
302   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
303           -- TODO: Use something better than varToString
304   ; let { label           = mkVHDLExtId ("zipVector" ++ (varToString res))
305         ; n_id            = mkVHDLBasicId "n"
306         ; n_expr          = idToVHDLExpr n_id
307         ; range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
308         ; genScheme       = AST.ForGn n_id range
309         ; resname'        = mkIndexedName (varToVHDLName res) n_expr
310         ; argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
311         ; argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
312         } ; 
313   ; labels <- MonadState.lift vsType $ getFieldLabels (tfvec_elem (Var.varType res))
314   ; let { resnameA    = mkSelectedName resname' (labels!!0)
315         ; resnameB    = mkSelectedName resname' (labels!!1)
316         ; resA_assign = mkUncondAssign (Right resnameA) argexpr1
317         ; resB_assign = mkUncondAssign (Right resnameB) argexpr2
318         } ;
319     -- Return the generate functions
320   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
321   }
322     
323 -- | Generate a generate statement for the builtin function "unzip"
324 genUnzip :: BuiltinBuilder
325 genUnzip = genVarArgs genUnzip'
326 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
327 genUnzip' (Left res) f args@[arg] = do {
328     -- Setup the generate scheme
329   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
330     -- TODO: Use something better than varToString
331   ; let { label           = mkVHDLExtId ("unzipVector" ++ (varToString res))
332         ; n_id            = mkVHDLBasicId "n"
333         ; n_expr          = idToVHDLExpr n_id
334         ; range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
335         ; genScheme       = AST.ForGn n_id range
336         ; resname'        = varToVHDLName res
337         ; argexpr'        = mkIndexedName (varToVHDLName arg) n_expr
338         } ;
339   ; reslabels <- MonadState.lift vsType $ getFieldLabels (Var.varType res)
340   ; arglabels <- MonadState.lift vsType $ getFieldLabels (tfvec_elem (Var.varType arg))
341   ; let { resnameA    = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
342         ; resnameB    = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
343         ; argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
344         ; argexprB    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
345         ; resA_assign = mkUncondAssign (Right resnameA) argexprA
346         ; resB_assign = mkUncondAssign (Right resnameB) argexprB
347         } ;
348     -- Return the generate functions
349   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
350   }
351
352 genCopy :: BuiltinBuilder 
353 genCopy = genVarArgs genCopy'
354 genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
355 genCopy' (Left res) f args@[arg] =
356   let
357     resExpr = AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
358                 (AST.PrimName $ (varToVHDLName arg))]
359     out_assign = mkUncondAssign (Left res) resExpr
360   in 
361     return [out_assign]
362     
363 genConcat :: BuiltinBuilder
364 genConcat = genVarArgs genConcat'
365 genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
366 genConcat' (Left res) f args@[arg] = do {
367     -- Setup the generate scheme
368   ; len1 <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
369   ; let (_, nvec) = splitAppTy (Var.varType arg)
370   ; len2 <- MonadState.lift vsType $ tfp_to_int $ tfvec_len_ty nvec
371           -- TODO: Use something better than varToString
372   ; let { label       = mkVHDLExtId ("concatVector" ++ (varToString res))
373         ; n_id        = mkVHDLBasicId "n"
374         ; n_expr      = idToVHDLExpr n_id
375         ; fromRange   = n_expr AST.:*: (AST.PrimLit $ show len2)
376         ; genScheme   = AST.ForGn n_id range
377           -- Create the content of the generate statement: Applying the mapped_f to
378           -- each of the elements in arg, storing to each element in res
379         ; toRange     = (n_expr AST.:*: (AST.PrimLit $ show len2)) AST.:+: (AST.PrimLit $ show (len2-1))
380         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len1-1))
381         ; resname     = vecSlice fromRange toRange
382         ; argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
383         ; out_assign  = mkUncondAssign (Right resname) argexpr
384         } ;
385     -- Return the generate statement
386   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [out_assign]]
387   }
388   where
389     vecSlice init last =  AST.NSlice (AST.SliceName (varToVHDLName res) 
390                             (AST.ToRange init last))
391
392 genIteraten :: TypeState -> BuiltinBuilder
393 genIteraten ty_state dst f args = genIterate ty_state dst f (tail args)
394
395 genIterate :: TypeState -> BuiltinBuilder
396 genIterate ty_state = genIterateOrGenerate ty_state True
397
398 genGeneraten :: TypeState -> BuiltinBuilder
399 genGeneraten ty_state dst f args = genGenerate ty_state dst f (tail args)
400
401 genGenerate :: TypeState -> BuiltinBuilder
402 genGenerate ty_state = genIterateOrGenerate ty_state False
403
404 genIterateOrGenerate :: TypeState -> Bool -> BuiltinBuilder
405 genIterateOrGenerate ty_state iter = genVarArgs (genIterateOrGenerate' ty_state iter)
406 genIterateOrGenerate' :: TypeState -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
407 -- Special case for an empty input vector, just assign start to res
408 genIterateOrGenerate' ty_state iter (Left res) _ [app_f, start] | len == 0 = return [mkUncondAssign (Left res) (AST.PrimLit "\"\"")]
409     where len = State.evalState (tfp_to_int $ (tfvec_len_ty . Var.varType) res) ty_state
410 genIterateOrGenerate' ty_state iter (Left res) f [app_f, start] = do
411   -- The vector length
412   len <- MonadState.lift vsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
413   -- An expression for len-1
414   let len_min_expr = (AST.PrimLit $ show (len-1))
415   -- -- evec is (TFVec n), so it still needs an element type
416   -- let (nvec, _) = splitAppTy (Var.varType vec)
417   -- -- Put the type of the start value in nvec, this will be the type of our
418   -- -- temporary vector
419   let tmp_ty = Var.varType res
420   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
421   tmp_vhdl_ty <- MonadState.lift vsType $ vhdl_ty error_msg tmp_ty
422   -- Setup the generate scheme
423   let gen_label = mkVHDLExtId ("iterateVector" ++ (varToString start))
424   let block_label = mkVHDLExtId ("iterateVector" ++ (varToString res))
425   let gen_range = AST.ToRange (AST.PrimLit "0") len_min_expr
426   let gen_scheme   = AST.ForGn n_id gen_range
427   -- Make the intermediate vector
428   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
429   -- Create the generate statement
430   cells <- sequence [genFirstCell, genOtherCell]
431   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
432   -- Assign tmp[len-1] or tmp[0] to res
433   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr tmp_name    
434   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
435   return [AST.CSBSm block]
436   where
437     -- An id for the counter
438     n_id = mkVHDLBasicId "n"
439     n_cur = idToVHDLExpr n_id
440     -- An expression for previous n
441     n_prev = n_cur AST.:-: (AST.PrimLit "1")
442     -- An id for the tmp result vector
443     tmp_id = mkVHDLBasicId "tmp"
444     tmp_name = AST.NSimple tmp_id
445     -- Generate parts of the fold
446     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
447     genFirstCell = do
448       let cond_label = mkVHDLExtId "firstcell"
449       -- if n == 0 or n == len-1
450       let cond_scheme = AST.IfGn $ n_cur AST.:=: (AST.PrimLit "0")
451       -- Output to tmp[current n]
452       let resname = mkIndexedName tmp_name n_cur
453       -- Input from start
454       let argexpr = (varToVHDLExpr ty_state) start
455       let startassign = mkUncondAssign (Right resname) argexpr
456       app_concsms <- genApplication (Right resname) app_f  [Right argexpr]
457       -- Return the conditional generate part
458       return $ AST.GenerateSm cond_label cond_scheme [] (if iter then 
459                                                           [startassign]
460                                                          else 
461                                                           app_concsms
462                                                         )
463
464     genOtherCell = do
465       let cond_label = mkVHDLExtId "othercell"
466       -- if n > 0 or n < len-1
467       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (AST.PrimLit "0")
468       -- Output to tmp[current n]
469       let resname = mkIndexedName tmp_name n_cur
470       -- Input from tmp[previous n]
471       let argexpr = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
472       app_concsms <- genApplication (Right resname) app_f [Right argexpr]
473       -- Return the conditional generate part
474       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
475
476
477 -----------------------------------------------------------------------------
478 -- Function to generate VHDL for applications
479 -----------------------------------------------------------------------------
480 genApplication ::
481   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
482   -> CoreSyn.CoreBndr -- ^ The function to apply
483   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
484   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
485 genApplication dst f args = do
486   ty_state <- getA vsType
487   case Var.globalIdVarDetails f of
488     IdInfo.DataConWorkId dc -> case dst of
489       -- It's a datacon. Create a record from its arguments.
490       Left bndr -> do
491         -- We have the bndr, so we can get at the type
492         labels <- MonadState.lift vsType $ getFieldLabels (Var.varType bndr)
493         return $ zipWith mkassign labels $ map (either (exprToVHDLExpr ty_state) id) args
494         where
495           mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
496           mkassign label arg =
497             let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
498             mkUncondAssign (Right sel_name) arg
499       Right _ -> error $ "\nGenerate.genApplication: Can't generate dataconstructor application without an original binder"
500     IdInfo.VanillaGlobal -> do
501       -- It's a global value imported from elsewhere. These can be builtin
502       -- functions. Look up the function name in the name table and execute
503       -- the associated builder if there is any and the argument count matches
504       -- (this should always be the case if it typechecks, but just to be
505       -- sure...).
506       case (Map.lookup (varToString f) (globalNameTable ty_state)) of
507         Just (arg_count, builder) ->
508           if length args == arg_count then
509             builder dst f args
510           else
511             error $ "\nGenerate.genApplication(VanillaGlobal): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
512         Nothing -> error $ "\nGenerate.genApplication(VanillaGlobal): Using function from another module that is not a known builtin: " ++ pprString f
513     IdInfo.NotGlobalId -> do
514       signatures <- getA vsSignatures
515       -- This is a local id, so it should be a function whose definition we
516       -- have and which can be turned into a component instantiation.
517       case (Map.lookup f signatures) of
518         Just signature -> let
519           -- We have a signature, this is a top level binding. Generate a
520           -- component instantiation.
521           entity_id = ent_id signature
522           -- TODO: Using show here isn't really pretty, but we'll need some
523           -- unique-ish value...
524           label = "comp_ins_" ++ (either show prettyShow) dst
525           portmaps = mkAssocElems (map (either (exprToVHDLExpr ty_state) id) args) ((either varToVHDLName id) dst) signature
526           in
527             return [mkComponentInst label entity_id portmaps]
528         Nothing -> do
529           -- No signature, so this must be a local variable reference. It
530           -- should have a representable type (and thus, no arguments) and a
531           -- signal should be generated for it. Just generate an
532           -- unconditional assignment here.
533           ty_state <- getA vsType
534           return $ [mkUncondAssign dst ((varToVHDLExpr ty_state) f)]
535             
536     IdInfo.ClassOpId cls -> do
537       -- FIXME: Not looking for what instance this class op is called for
538       -- Is quite stupid of course.
539       case (Map.lookup (varToString f) (globalNameTable ty_state)) of
540         Just (arg_count, builder) ->
541           if length args == arg_count then
542             builder dst f args
543           else
544             error $ "\nGenerate.genApplication(ClassOpId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
545         Nothing -> error $ "\nGenerate.genApplication(ClassOpId): Using function from another module that is not a known builtin: " ++ pprString f
546     details -> error $ "\nGenerate.genApplication: Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
547
548 -----------------------------------------------------------------------------
549 -- Functions to generate functions dealing with vectors.
550 -----------------------------------------------------------------------------
551
552 -- Returns the VHDLId of the vector function with the given name for the given
553 -- element type. Generates -- this function if needed.
554 vectorFunId :: Type.Type -> String -> TypeSession AST.VHDLId
555 vectorFunId el_ty fname = do
556   let error_msg = "\nGenerate.vectorFunId: Can not construct vector function for element: " ++ pprString el_ty
557   elemTM <- vhdl_ty error_msg el_ty
558   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
559   -- the VHDLState or something.
560   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
561   typefuns <- getA vsTypeFuns
562   case Map.lookup (OrdType el_ty, fname) typefuns of
563     -- Function already generated, just return it
564     Just (id, _) -> return id
565     -- Function not generated yet, generate it
566     Nothing -> do
567       let functions = genUnconsVectorFuns elemTM vectorTM
568       case lookup fname functions of
569         Just body -> do
570           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, (fst body))
571           mapM_ (vectorFunId el_ty) (snd body)
572           return function_id
573         Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
574   where
575     function_id = mkVHDLExtId fname
576
577 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
578                     -> AST.TypeMark -- ^ type of the vector
579                     -> [(String, (AST.SubProgBody, [String]))]
580 genUnconsVectorFuns elemTM vectorTM  = 
581   [ (exId, (AST.SubProgBody exSpec      []                  [exExpr],[]))
582   , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet],[]))
583   , (headId, (AST.SubProgBody headSpec    []                  [headExpr],[]))
584   , (lastId, (AST.SubProgBody lastSpec    []                  [lastExpr],[]))
585   , (initId, (AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet],[]))
586   , (tailId, (AST.SubProgBody tailSpec    [AST.SPVD tailVar]  [tailExpr, tailRet],[]))
587   , (takeId, (AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet],[]))
588   , (dropId, (AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet],[]))
589   , (plusgtId, (AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
590   , (emptyId, (AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr],[]))
591   , (singletonId, (AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet],[]))
592   , (copynId, (AST.SubProgBody copynSpec    [AST.SPVD copynVar]      [copynExpr],[]))
593   , (selId, (AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet],[]))
594   , (ltplusId, (AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet],[]))  
595   , (plusplusId, (AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet],[]))
596   , (lengthTId, (AST.SubProgBody lengthTSpec [] [lengthTExpr],[]))
597   , (shiftlId, (AST.SubProgBody shiftlSpec [AST.SPVD shiftlVar] [shiftlExpr, shiftlRet], [initId]))
598   , (shiftrId, (AST.SubProgBody shiftrSpec [AST.SPVD shiftrVar] [shiftrExpr, shiftrRet], [tailId]))
599   , (nullId, (AST.SubProgBody nullSpec [] [nullExpr], []))
600   , (rotlId, (AST.SubProgBody rotlSpec [AST.SPVD rotlVar] [rotlExpr, rotlRet], [nullId, lastId, initId]))
601   , (rotrId, (AST.SubProgBody rotrSpec [AST.SPVD rotrVar] [rotrExpr, rotrRet], [nullId, tailId, headId]))
602   , (reverseId, (AST.SubProgBody reverseSpec [AST.SPVD reverseVar] [reverseFor, reverseRet], []))
603   ]
604   where 
605     ixPar   = AST.unsafeVHDLBasicId "ix"
606     vecPar  = AST.unsafeVHDLBasicId "vec"
607     vec1Par = AST.unsafeVHDLBasicId "vec1"
608     vec2Par = AST.unsafeVHDLBasicId "vec2"
609     nPar    = AST.unsafeVHDLBasicId "n"
610     iId     = AST.unsafeVHDLBasicId "i"
611     iPar    = iId
612     aPar    = AST.unsafeVHDLBasicId "a"
613     fPar = AST.unsafeVHDLBasicId "f"
614     sPar = AST.unsafeVHDLBasicId "s"
615     resId   = AST.unsafeVHDLBasicId "res"
616     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
617                                AST.IfaceVarDec ixPar  naturalTM] elemTM
618     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
619               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
620                 AST.NSimple ixPar]))
621     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
622                                           , AST.IfaceVarDec iPar   naturalTM
623                                           , AST.IfaceVarDec aPar   elemTM
624                                           ] vectorTM 
625        -- variable res : fsvec_x (0 to vec'length-1);
626     replaceVar =
627          AST.VarDec resId 
628                 (AST.SubtypeIn vectorTM
629                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
630                    [AST.ToRange (AST.PrimLit "0")
631                             (AST.PrimName (AST.NAttribute $ 
632                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
633                                 (AST.PrimLit "1"))   ]))
634                 Nothing
635        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
636     replaceExpr = AST.NSimple resId AST.:=
637            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
638             AST.PrimName (AST.NSimple aPar) AST.:&: 
639              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
640                       ((AST.PrimName (AST.NAttribute $ 
641                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
642                                                               AST.:-: AST.PrimLit "1"))
643     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
644     vecSlice init last =  AST.PrimName (AST.NSlice 
645                                         (AST.SliceName 
646                                               (AST.NSimple vecPar) 
647                                               (AST.ToRange init last)))
648     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
649        -- return vec(0);
650     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
651                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
652     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
653        -- return vec(vec'length-1);
654     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
655                     (AST.NSimple vecPar) 
656                     [AST.PrimName (AST.NAttribute $ 
657                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
658                                                              AST.:-: AST.PrimLit "1"])))
659     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
660        -- variable res : fsvec_x (0 to vec'length-2);
661     initVar = 
662          AST.VarDec resId 
663                 (AST.SubtypeIn vectorTM
664                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
665                    [AST.ToRange (AST.PrimLit "0")
666                             (AST.PrimName (AST.NAttribute $ 
667                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
668                                 (AST.PrimLit "2"))   ]))
669                 Nothing
670        -- resAST.:= vec(0 to vec'length-2)
671     initExpr = AST.NSimple resId AST.:= (vecSlice 
672                                (AST.PrimLit "0") 
673                                (AST.PrimName (AST.NAttribute $ 
674                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
675                                                              AST.:-: AST.PrimLit "2"))
676     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
677     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
678        -- variable res : fsvec_x (0 to vec'length-2); 
679     tailVar = 
680          AST.VarDec resId 
681                 (AST.SubtypeIn vectorTM
682                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
683                    [AST.ToRange (AST.PrimLit "0")
684                             (AST.PrimName (AST.NAttribute $ 
685                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
686                                 (AST.PrimLit "2"))   ]))
687                 Nothing       
688        -- res AST.:= vec(1 to vec'length-1)
689     tailExpr = AST.NSimple resId AST.:= (vecSlice 
690                                (AST.PrimLit "1") 
691                                (AST.PrimName (AST.NAttribute $ 
692                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
693                                                              AST.:-: AST.PrimLit "1"))
694     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
695     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
696                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
697        -- variable res : fsvec_x (0 to n-1);
698     takeVar = 
699          AST.VarDec resId 
700                 (AST.SubtypeIn vectorTM
701                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
702                    [AST.ToRange (AST.PrimLit "0")
703                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
704                                 (AST.PrimLit "1"))   ]))
705                 Nothing
706        -- res AST.:= vec(0 to n-1)
707     takeExpr = AST.NSimple resId AST.:= 
708                     (vecSlice (AST.PrimLit "1") 
709                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
710     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
711     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
712                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
713        -- variable res : fsvec_x (0 to vec'length-n-1);
714     dropVar = 
715          AST.VarDec resId 
716                 (AST.SubtypeIn vectorTM
717                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
718                    [AST.ToRange (AST.PrimLit "0")
719                             (AST.PrimName (AST.NAttribute $ 
720                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
721                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
722                Nothing
723        -- res AST.:= vec(n to vec'length-1)
724     dropExpr = AST.NSimple resId AST.:= (vecSlice 
725                                (AST.PrimName $ AST.NSimple nPar) 
726                                (AST.PrimName (AST.NAttribute $ 
727                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
728                                                              AST.:-: AST.PrimLit "1"))
729     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
730     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
731                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
732     -- variable res : fsvec_x (0 to vec'length);
733     plusgtVar = 
734       AST.VarDec resId 
735              (AST.SubtypeIn vectorTM
736                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
737                 [AST.ToRange (AST.PrimLit "0")
738                         (AST.PrimName (AST.NAttribute $ 
739                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
740              Nothing
741     plusgtExpr = AST.NSimple resId AST.:= 
742                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
743                     (AST.PrimName $ AST.NSimple vecPar))
744     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
745     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
746     emptyVar = 
747           AST.ConstDec resId 
748               (AST.SubtypeIn vectorTM Nothing)
749               (Just $ AST.PrimLit "\"\"")
750     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
751     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
752                                          vectorTM
753     -- variable res : fsvec_x (0 to 0) := (others => a);
754     singletonVar = 
755       AST.VarDec resId 
756              (AST.SubtypeIn vectorTM
757                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
758                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
759              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
760                                           (AST.PrimName $ AST.NSimple aPar)])
761     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
762     copynSpec = AST.Function (mkVHDLExtId copynId) [AST.IfaceVarDec nPar   naturalTM,
763                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
764     -- variable res : fsvec_x (0 to n-1) := (others => a);
765     copynVar = 
766       AST.VarDec resId 
767              (AST.SubtypeIn vectorTM
768                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
769                 [AST.ToRange (AST.PrimLit "0")
770                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
771                              (AST.PrimLit "1"))   ]))
772              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
773                                           (AST.PrimName $ AST.NSimple aPar)])
774     -- return res
775     copynExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
776     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
777                                AST.IfaceVarDec sPar   naturalTM,
778                                AST.IfaceVarDec nPar   naturalTM,
779                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
780     -- variable res : fsvec_x (0 to n-1);
781     selVar = 
782       AST.VarDec resId 
783                 (AST.SubtypeIn vectorTM
784                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
785                     [AST.ToRange (AST.PrimLit "0")
786                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
787                       (AST.PrimLit "1"))   ])
788                 )
789                 Nothing
790     -- for i res'range loop
791     --   res(i) := vec(f+i*s);
792     -- end loop;
793     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [selAssign]
794     -- res(i) := vec(f+i*s);
795     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
796                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
797                                   AST.PrimName (AST.NSimple sPar)) in
798                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
799                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
800     -- return res;
801     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
802     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
803                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
804      -- variable res : fsvec_x (0 to vec'length);
805     ltplusVar = 
806       AST.VarDec resId 
807         (AST.SubtypeIn vectorTM
808           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
809             [AST.ToRange (AST.PrimLit "0")
810               (AST.PrimName (AST.NAttribute $ 
811                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
812         Nothing
813     ltplusExpr = AST.NSimple resId AST.:= 
814                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
815                       (AST.PrimName $ AST.NSimple aPar))
816     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
817     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
818                                              AST.IfaceVarDec vec2Par vectorTM] 
819                                              vectorTM 
820     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
821     plusplusVar = 
822       AST.VarDec resId 
823         (AST.SubtypeIn vectorTM
824           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
825             [AST.ToRange (AST.PrimLit "0")
826               (AST.PrimName (AST.NAttribute $ 
827                 AST.AttribName (AST.NSimple vec1Par) (mkVHDLBasicId lengthId) Nothing) AST.:+:
828                   AST.PrimName (AST.NAttribute $ 
829                 AST.AttribName (AST.NSimple vec2Par) (mkVHDLBasicId lengthId) Nothing) AST.:-:
830                   AST.PrimLit "1")]))
831        Nothing
832     plusplusExpr = AST.NSimple resId AST.:= 
833                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
834                       (AST.PrimName $ AST.NSimple vec2Par))
835     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
836     lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
837     lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $ 
838                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))
839     shiftlSpec = AST.Function (mkVHDLExtId shiftlId) [AST.IfaceVarDec vecPar vectorTM,
840                                    AST.IfaceVarDec aPar   elemTM  ] vectorTM 
841     -- variable res : fsvec_x (0 to vec'length-1);
842     shiftlVar = 
843      AST.VarDec resId 
844             (AST.SubtypeIn vectorTM
845               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
846                [AST.ToRange (AST.PrimLit "0")
847                         (AST.PrimName (AST.NAttribute $ 
848                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
849                            (AST.PrimLit "1")) ]))
850             Nothing
851     -- res := a & init(vec)
852     shiftlExpr = AST.NSimple resId AST.:=
853                     (AST.PrimName (AST.NSimple aPar) AST.:&:
854                      (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
855                        [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
856     shiftlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
857     shiftrSpec = AST.Function (mkVHDLExtId shiftrId) [AST.IfaceVarDec vecPar vectorTM,
858                                        AST.IfaceVarDec aPar   elemTM  ] vectorTM 
859     -- variable res : fsvec_x (0 to vec'length-1);
860     shiftrVar = 
861      AST.VarDec resId 
862             (AST.SubtypeIn vectorTM
863               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
864                [AST.ToRange (AST.PrimLit "0")
865                         (AST.PrimName (AST.NAttribute $ 
866                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
867                            (AST.PrimLit "1")) ]))
868             Nothing
869     -- res := tail(vec) & a
870     shiftrExpr = AST.NSimple resId AST.:=
871                   ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
872                     [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
873                   (AST.PrimName (AST.NSimple aPar)))
874                 
875     shiftrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)      
876     nullSpec = AST.Function (mkVHDLExtId nullId) [AST.IfaceVarDec vecPar vectorTM] booleanTM
877     -- return vec'length = 0
878     nullExpr = AST.ReturnSm (Just $ 
879                 AST.PrimName (AST.NAttribute $ 
880                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:=:
881                     AST.PrimLit "0")
882     rotlSpec = AST.Function (mkVHDLExtId rotlId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
883     -- variable res : fsvec_x (0 to vec'length-1);
884     rotlVar = 
885      AST.VarDec resId 
886             (AST.SubtypeIn vectorTM
887               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
888                [AST.ToRange (AST.PrimLit "0")
889                         (AST.PrimName (AST.NAttribute $ 
890                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
891                            (AST.PrimLit "1")) ]))
892             Nothing
893     -- if null(vec) then res := vec else res := last(vec) & init(vec)
894     rotlExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
895                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
896                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
897                         []
898                         (Just $ AST.Else [rotlExprRet])
899       where rotlExprRet = 
900                 AST.NSimple resId AST.:= 
901                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId lastId))  
902                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
903                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
904                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
905     rotlRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
906     rotrSpec = AST.Function (mkVHDLExtId rotrId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
907     -- variable res : fsvec_x (0 to vec'length-1);
908     rotrVar = 
909      AST.VarDec resId 
910             (AST.SubtypeIn vectorTM
911               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
912                [AST.ToRange (AST.PrimLit "0")
913                         (AST.PrimName (AST.NAttribute $ 
914                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
915                            (AST.PrimLit "1")) ]))
916             Nothing
917     -- if null(vec) then res := vec else res := tail(vec) & head(vec)
918     rotrExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
919                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
920                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
921                         []
922                         (Just $ AST.Else [rotrExprRet])
923       where rotrExprRet = 
924                 AST.NSimple resId AST.:= 
925                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
926                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
927                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId headId))  
928                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
929     rotrRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
930     reverseSpec = AST.Function (mkVHDLExtId reverseId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
931     reverseVar = 
932       AST.VarDec resId 
933              (AST.SubtypeIn vectorTM
934                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
935                 [AST.ToRange (AST.PrimLit "0")
936                          (AST.PrimName (AST.NAttribute $ 
937                            AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
938                             (AST.PrimLit "1")) ]))
939              Nothing
940     -- for i in 0 to res'range loop
941     --   res(vec'length-i-1) := vec(i);
942     -- end loop;
943     reverseFor = 
944        AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [reverseAssign]
945     -- res(vec'length-i-1) := vec(i);
946     reverseAssign = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [destExp]) AST.:=
947       (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) 
948                            [AST.PrimName $ AST.NSimple iId]))
949         where destExp = AST.PrimName (AST.NAttribute $ AST.AttribName (AST.NSimple vecPar) 
950                                    (mkVHDLBasicId lengthId) Nothing) AST.:-: 
951                         AST.PrimName (AST.NSimple iId) AST.:-: 
952                         (AST.PrimLit "1") 
953     -- return res;
954     reverseRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
955     
956 -----------------------------------------------------------------------------
957 -- A table of builtin functions
958 -----------------------------------------------------------------------------
959
960 -- | The builtin functions we support. Maps a name to an argument count and a
961 -- builder function.
962 globalNameTable :: TypeState -> NameTable
963 globalNameTable ty_state = Map.fromList
964   [ (exId             , (2, genFCall ty_state False         ) )
965   , (replaceId        , (3, genFCall ty_state False         ) )
966   , (headId           , (1, genFCall ty_state True          ) )
967   , (lastId           , (1, genFCall ty_state True          ) )
968   , (tailId           , (1, genFCall ty_state False         ) )
969   , (initId           , (1, genFCall ty_state False         ) )
970   , (takeId           , (2, genFCall ty_state False         ) )
971   , (dropId           , (2, genFCall ty_state False         ) )
972   , (selId            , (4, genFCall ty_state False         ) )
973   , (plusgtId         , (2, genFCall ty_state False         ) )
974   , (ltplusId         , (2, genFCall ty_state False         ) )
975   , (plusplusId       , (2, genFCall ty_state False         ) )
976   , (mapId            , (2, genMap                          ) )
977   , (zipWithId        , (3, genZipWith                      ) )
978   , (foldlId          , (3, genFoldl ty_state               ) )
979   , (foldrId          , (3, genFoldr ty_state               ) )
980   , (zipId            , (2, genZip                          ) )
981   , (unzipId          , (1, genUnzip                        ) )
982   , (shiftlId         , (2, genFCall ty_state False         ) )
983   , (shiftrId         , (2, genFCall ty_state False         ) )
984   , (rotlId           , (1, genFCall ty_state False         ) )
985   , (rotrId           , (1, genFCall ty_state False         ) )
986   , (concatId         , (1, genConcat                       ) )
987   , (reverseId        , (1, genFCall ty_state False         ) )
988   , (iteratenId       , (3, genIteraten ty_state            ) )
989   , (iterateId        , (2, genIterate ty_state             ) )
990   , (generatenId      , (3, genGeneraten ty_state           ) )
991   , (generateId       , (2, genGenerate ty_state            ) )
992   , (emptyId          , (0, genFCall ty_state False         ) )
993   , (singletonId      , (1, genFCall ty_state False         ) )
994   , (copynId          , (2, genFCall ty_state False         ) )
995   , (copyId           , (1, genCopy                         ) )
996   , (lengthTId        , (1, genFCall ty_state False         ) )
997   , (nullId           , (1, genFCall ty_state False         ) )
998   , (hwxorId          , (2, genOperator2 ty_state AST.Xor   ) )
999   , (hwandId          , (2, genOperator2 ty_state AST.And   ) )
1000   , (hworId           , (2, genOperator2 ty_state AST.Or    ) )
1001   , (hwnotId          , (1, genOperator1 ty_state AST.Not   ) )
1002   , (plusId           , (2, genOperator2 ty_state (AST.:+:) ) )
1003   , (timesId          , (2, genOperator2 ty_state (AST.:*:) ) )
1004   , (negateId         , (1, genNegation ty_state            ) )
1005   , (minusId          , (2, genOperator2 ty_state (AST.:-:) ) )
1006   , (fromSizedWordId  , (1, genFromSizedWord ty_state       ) )
1007   , (fromIntegerId    , (1, genFromInteger                  ) )
1008   ]