Only save normalized tfp integers in the tfp-cache
[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       let  
518         signature = Maybe.fromMaybe 
519           (error $ "\nGenerate.genApplication: Using function '" ++ (varToString f) ++ "' without signature? This should not happen!") 
520           (Map.lookup f signatures)
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     IdInfo.ClassOpId cls -> do
529       -- FIXME: Not looking for what instance this class op is called for
530       -- Is quite stupid of course.
531       case (Map.lookup (varToString f) (globalNameTable ty_state)) of
532         Just (arg_count, builder) ->
533           if length args == arg_count then
534             builder dst f args
535           else
536             error $ "\nGenerate.genApplication(ClassOpId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
537         Nothing -> error $ "\nGenerate.genApplication(ClassOpId): Using function from another module that is not a known builtin: " ++ pprString f
538     details -> error $ "\nGenerate.genApplication: Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
539
540 -----------------------------------------------------------------------------
541 -- Functions to generate functions dealing with vectors.
542 -----------------------------------------------------------------------------
543
544 -- Returns the VHDLId of the vector function with the given name for the given
545 -- element type. Generates -- this function if needed.
546 vectorFunId :: Type.Type -> String -> TypeSession AST.VHDLId
547 vectorFunId el_ty fname = do
548   let error_msg = "\nGenerate.vectorFunId: Can not construct vector function for element: " ++ pprString el_ty
549   elemTM <- vhdl_ty error_msg el_ty
550   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
551   -- the VHDLState or something.
552   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
553   typefuns <- getA vsTypeFuns
554   case Map.lookup (OrdType el_ty, fname) typefuns of
555     -- Function already generated, just return it
556     Just (id, _) -> return id
557     -- Function not generated yet, generate it
558     Nothing -> do
559       let functions = genUnconsVectorFuns elemTM vectorTM
560       case lookup fname functions of
561         Just body -> do
562           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, (fst body))
563           mapM_ (vectorFunId el_ty) (snd body)
564           return function_id
565         Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
566   where
567     function_id = mkVHDLExtId fname
568
569 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
570                     -> AST.TypeMark -- ^ type of the vector
571                     -> [(String, (AST.SubProgBody, [String]))]
572 genUnconsVectorFuns elemTM vectorTM  = 
573   [ (exId, (AST.SubProgBody exSpec      []                  [exExpr],[]))
574   , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet],[]))
575   , (headId, (AST.SubProgBody headSpec    []                  [headExpr],[]))
576   , (lastId, (AST.SubProgBody lastSpec    []                  [lastExpr],[]))
577   , (initId, (AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet],[]))
578   , (tailId, (AST.SubProgBody tailSpec    [AST.SPVD tailVar]  [tailExpr, tailRet],[]))
579   , (takeId, (AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet],[]))
580   , (dropId, (AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet],[]))
581   , (plusgtId, (AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
582   , (emptyId, (AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr],[]))
583   , (singletonId, (AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet],[]))
584   , (copynId, (AST.SubProgBody copynSpec    [AST.SPVD copynVar]      [copynExpr],[]))
585   , (selId, (AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet],[]))
586   , (ltplusId, (AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet],[]))  
587   , (plusplusId, (AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet],[]))
588   , (lengthTId, (AST.SubProgBody lengthTSpec [] [lengthTExpr],[]))
589   , (shiftlId, (AST.SubProgBody shiftlSpec [AST.SPVD shiftlVar] [shiftlExpr, shiftlRet], [initId]))
590   , (shiftrId, (AST.SubProgBody shiftrSpec [AST.SPVD shiftrVar] [shiftrExpr, shiftrRet], [tailId]))
591   , (nullId, (AST.SubProgBody nullSpec [] [nullExpr], []))
592   , (rotlId, (AST.SubProgBody rotlSpec [AST.SPVD rotlVar] [rotlExpr, rotlRet], [nullId, lastId, initId]))
593   , (rotrId, (AST.SubProgBody rotrSpec [AST.SPVD rotrVar] [rotrExpr, rotrRet], [nullId, tailId, headId]))
594   , (reverseId, (AST.SubProgBody reverseSpec [AST.SPVD reverseVar] [reverseFor, reverseRet], []))
595   ]
596   where 
597     ixPar   = AST.unsafeVHDLBasicId "ix"
598     vecPar  = AST.unsafeVHDLBasicId "vec"
599     vec1Par = AST.unsafeVHDLBasicId "vec1"
600     vec2Par = AST.unsafeVHDLBasicId "vec2"
601     nPar    = AST.unsafeVHDLBasicId "n"
602     iId     = AST.unsafeVHDLBasicId "i"
603     iPar    = iId
604     aPar    = AST.unsafeVHDLBasicId "a"
605     fPar = AST.unsafeVHDLBasicId "f"
606     sPar = AST.unsafeVHDLBasicId "s"
607     resId   = AST.unsafeVHDLBasicId "res"
608     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
609                                AST.IfaceVarDec ixPar  naturalTM] elemTM
610     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
611               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
612                 AST.NSimple ixPar]))
613     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
614                                           , AST.IfaceVarDec iPar   naturalTM
615                                           , AST.IfaceVarDec aPar   elemTM
616                                           ] vectorTM 
617        -- variable res : fsvec_x (0 to vec'length-1);
618     replaceVar =
619          AST.VarDec resId 
620                 (AST.SubtypeIn vectorTM
621                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
622                    [AST.ToRange (AST.PrimLit "0")
623                             (AST.PrimName (AST.NAttribute $ 
624                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
625                                 (AST.PrimLit "1"))   ]))
626                 Nothing
627        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
628     replaceExpr = AST.NSimple resId AST.:=
629            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
630             AST.PrimName (AST.NSimple aPar) AST.:&: 
631              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
632                       ((AST.PrimName (AST.NAttribute $ 
633                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
634                                                               AST.:-: AST.PrimLit "1"))
635     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
636     vecSlice init last =  AST.PrimName (AST.NSlice 
637                                         (AST.SliceName 
638                                               (AST.NSimple vecPar) 
639                                               (AST.ToRange init last)))
640     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
641        -- return vec(0);
642     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
643                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
644     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
645        -- return vec(vec'length-1);
646     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
647                     (AST.NSimple vecPar) 
648                     [AST.PrimName (AST.NAttribute $ 
649                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
650                                                              AST.:-: AST.PrimLit "1"])))
651     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
652        -- variable res : fsvec_x (0 to vec'length-2);
653     initVar = 
654          AST.VarDec resId 
655                 (AST.SubtypeIn vectorTM
656                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
657                    [AST.ToRange (AST.PrimLit "0")
658                             (AST.PrimName (AST.NAttribute $ 
659                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
660                                 (AST.PrimLit "2"))   ]))
661                 Nothing
662        -- resAST.:= vec(0 to vec'length-2)
663     initExpr = AST.NSimple resId AST.:= (vecSlice 
664                                (AST.PrimLit "0") 
665                                (AST.PrimName (AST.NAttribute $ 
666                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
667                                                              AST.:-: AST.PrimLit "2"))
668     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
669     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
670        -- variable res : fsvec_x (0 to vec'length-2); 
671     tailVar = 
672          AST.VarDec resId 
673                 (AST.SubtypeIn vectorTM
674                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
675                    [AST.ToRange (AST.PrimLit "0")
676                             (AST.PrimName (AST.NAttribute $ 
677                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
678                                 (AST.PrimLit "2"))   ]))
679                 Nothing       
680        -- res AST.:= vec(1 to vec'length-1)
681     tailExpr = AST.NSimple resId AST.:= (vecSlice 
682                                (AST.PrimLit "1") 
683                                (AST.PrimName (AST.NAttribute $ 
684                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
685                                                              AST.:-: AST.PrimLit "1"))
686     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
687     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
688                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
689        -- variable res : fsvec_x (0 to n-1);
690     takeVar = 
691          AST.VarDec resId 
692                 (AST.SubtypeIn vectorTM
693                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
694                    [AST.ToRange (AST.PrimLit "0")
695                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
696                                 (AST.PrimLit "1"))   ]))
697                 Nothing
698        -- res AST.:= vec(0 to n-1)
699     takeExpr = AST.NSimple resId AST.:= 
700                     (vecSlice (AST.PrimLit "1") 
701                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
702     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
703     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
704                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
705        -- variable res : fsvec_x (0 to vec'length-n-1);
706     dropVar = 
707          AST.VarDec resId 
708                 (AST.SubtypeIn vectorTM
709                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
710                    [AST.ToRange (AST.PrimLit "0")
711                             (AST.PrimName (AST.NAttribute $ 
712                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
713                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
714                Nothing
715        -- res AST.:= vec(n to vec'length-1)
716     dropExpr = AST.NSimple resId AST.:= (vecSlice 
717                                (AST.PrimName $ AST.NSimple nPar) 
718                                (AST.PrimName (AST.NAttribute $ 
719                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
720                                                              AST.:-: AST.PrimLit "1"))
721     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
722     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
723                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
724     -- variable res : fsvec_x (0 to vec'length);
725     plusgtVar = 
726       AST.VarDec resId 
727              (AST.SubtypeIn vectorTM
728                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
729                 [AST.ToRange (AST.PrimLit "0")
730                         (AST.PrimName (AST.NAttribute $ 
731                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
732              Nothing
733     plusgtExpr = AST.NSimple resId AST.:= 
734                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
735                     (AST.PrimName $ AST.NSimple vecPar))
736     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
737     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
738     emptyVar = 
739           AST.ConstDec resId 
740               (AST.SubtypeIn vectorTM Nothing)
741               (Just $ AST.PrimLit "\"\"")
742     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
743     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
744                                          vectorTM
745     -- variable res : fsvec_x (0 to 0) := (others => a);
746     singletonVar = 
747       AST.VarDec resId 
748              (AST.SubtypeIn vectorTM
749                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
750                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
751              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
752                                           (AST.PrimName $ AST.NSimple aPar)])
753     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
754     copynSpec = AST.Function (mkVHDLExtId copynId) [AST.IfaceVarDec nPar   naturalTM,
755                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
756     -- variable res : fsvec_x (0 to n-1) := (others => a);
757     copynVar = 
758       AST.VarDec resId 
759              (AST.SubtypeIn vectorTM
760                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
761                 [AST.ToRange (AST.PrimLit "0")
762                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
763                              (AST.PrimLit "1"))   ]))
764              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
765                                           (AST.PrimName $ AST.NSimple aPar)])
766     -- return res
767     copynExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
768     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
769                                AST.IfaceVarDec sPar   naturalTM,
770                                AST.IfaceVarDec nPar   naturalTM,
771                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
772     -- variable res : fsvec_x (0 to n-1);
773     selVar = 
774       AST.VarDec resId 
775                 (AST.SubtypeIn vectorTM
776                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
777                     [AST.ToRange (AST.PrimLit "0")
778                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
779                       (AST.PrimLit "1"))   ])
780                 )
781                 Nothing
782     -- for i res'range loop
783     --   res(i) := vec(f+i*s);
784     -- end loop;
785     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [selAssign]
786     -- res(i) := vec(f+i*s);
787     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
788                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
789                                   AST.PrimName (AST.NSimple sPar)) in
790                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
791                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
792     -- return res;
793     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
794     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
795                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
796      -- variable res : fsvec_x (0 to vec'length);
797     ltplusVar = 
798       AST.VarDec resId 
799         (AST.SubtypeIn vectorTM
800           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
801             [AST.ToRange (AST.PrimLit "0")
802               (AST.PrimName (AST.NAttribute $ 
803                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
804         Nothing
805     ltplusExpr = AST.NSimple resId AST.:= 
806                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
807                       (AST.PrimName $ AST.NSimple aPar))
808     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
809     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
810                                              AST.IfaceVarDec vec2Par vectorTM] 
811                                              vectorTM 
812     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
813     plusplusVar = 
814       AST.VarDec resId 
815         (AST.SubtypeIn vectorTM
816           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
817             [AST.ToRange (AST.PrimLit "0")
818               (AST.PrimName (AST.NAttribute $ 
819                 AST.AttribName (AST.NSimple vec1Par) (mkVHDLBasicId lengthId) Nothing) AST.:+:
820                   AST.PrimName (AST.NAttribute $ 
821                 AST.AttribName (AST.NSimple vec2Par) (mkVHDLBasicId lengthId) Nothing) AST.:-:
822                   AST.PrimLit "1")]))
823        Nothing
824     plusplusExpr = AST.NSimple resId AST.:= 
825                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
826                       (AST.PrimName $ AST.NSimple vec2Par))
827     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
828     lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
829     lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $ 
830                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))
831     shiftlSpec = AST.Function (mkVHDLExtId shiftlId) [AST.IfaceVarDec vecPar vectorTM,
832                                    AST.IfaceVarDec aPar   elemTM  ] vectorTM 
833     -- variable res : fsvec_x (0 to vec'length-1);
834     shiftlVar = 
835      AST.VarDec resId 
836             (AST.SubtypeIn vectorTM
837               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
838                [AST.ToRange (AST.PrimLit "0")
839                         (AST.PrimName (AST.NAttribute $ 
840                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
841                            (AST.PrimLit "1")) ]))
842             Nothing
843     -- res := a & init(vec)
844     shiftlExpr = AST.NSimple resId AST.:=
845                     (AST.PrimName (AST.NSimple aPar) AST.:&:
846                      (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
847                        [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
848     shiftlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
849     shiftrSpec = AST.Function (mkVHDLExtId shiftrId) [AST.IfaceVarDec vecPar vectorTM,
850                                        AST.IfaceVarDec aPar   elemTM  ] vectorTM 
851     -- variable res : fsvec_x (0 to vec'length-1);
852     shiftrVar = 
853      AST.VarDec resId 
854             (AST.SubtypeIn vectorTM
855               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
856                [AST.ToRange (AST.PrimLit "0")
857                         (AST.PrimName (AST.NAttribute $ 
858                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
859                            (AST.PrimLit "1")) ]))
860             Nothing
861     -- res := tail(vec) & a
862     shiftrExpr = AST.NSimple resId AST.:=
863                   ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
864                     [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
865                   (AST.PrimName (AST.NSimple aPar)))
866                 
867     shiftrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)      
868     nullSpec = AST.Function (mkVHDLExtId nullId) [AST.IfaceVarDec vecPar vectorTM] booleanTM
869     -- return vec'length = 0
870     nullExpr = AST.ReturnSm (Just $ 
871                 AST.PrimName (AST.NAttribute $ 
872                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:=:
873                     AST.PrimLit "0")
874     rotlSpec = AST.Function (mkVHDLExtId rotlId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
875     -- variable res : fsvec_x (0 to vec'length-1);
876     rotlVar = 
877      AST.VarDec resId 
878             (AST.SubtypeIn vectorTM
879               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
880                [AST.ToRange (AST.PrimLit "0")
881                         (AST.PrimName (AST.NAttribute $ 
882                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
883                            (AST.PrimLit "1")) ]))
884             Nothing
885     -- if null(vec) then res := vec else res := last(vec) & init(vec)
886     rotlExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
887                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
888                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
889                         []
890                         (Just $ AST.Else [rotlExprRet])
891       where rotlExprRet = 
892                 AST.NSimple resId AST.:= 
893                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId lastId))  
894                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
895                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
896                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
897     rotlRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
898     rotrSpec = AST.Function (mkVHDLExtId rotrId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
899     -- variable res : fsvec_x (0 to vec'length-1);
900     rotrVar = 
901      AST.VarDec resId 
902             (AST.SubtypeIn vectorTM
903               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
904                [AST.ToRange (AST.PrimLit "0")
905                         (AST.PrimName (AST.NAttribute $ 
906                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
907                            (AST.PrimLit "1")) ]))
908             Nothing
909     -- if null(vec) then res := vec else res := tail(vec) & head(vec)
910     rotrExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
911                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
912                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
913                         []
914                         (Just $ AST.Else [rotrExprRet])
915       where rotrExprRet = 
916                 AST.NSimple resId AST.:= 
917                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
918                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
919                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId headId))  
920                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
921     rotrRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
922     reverseSpec = AST.Function (mkVHDLExtId reverseId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
923     reverseVar = 
924       AST.VarDec resId 
925              (AST.SubtypeIn vectorTM
926                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
927                 [AST.ToRange (AST.PrimLit "0")
928                          (AST.PrimName (AST.NAttribute $ 
929                            AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
930                             (AST.PrimLit "1")) ]))
931              Nothing
932     -- for i in 0 to res'range loop
933     --   res(vec'length-i-1) := vec(i);
934     -- end loop;
935     reverseFor = 
936        AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [reverseAssign]
937     -- res(vec'length-i-1) := vec(i);
938     reverseAssign = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [destExp]) AST.:=
939       (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) 
940                            [AST.PrimName $ AST.NSimple iId]))
941         where destExp = AST.PrimName (AST.NAttribute $ AST.AttribName (AST.NSimple vecPar) 
942                                    (mkVHDLBasicId lengthId) Nothing) AST.:-: 
943                         AST.PrimName (AST.NSimple iId) AST.:-: 
944                         (AST.PrimLit "1") 
945     -- return res;
946     reverseRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
947     
948 -----------------------------------------------------------------------------
949 -- A table of builtin functions
950 -----------------------------------------------------------------------------
951
952 -- | The builtin functions we support. Maps a name to an argument count and a
953 -- builder function.
954 globalNameTable :: TypeState -> NameTable
955 globalNameTable ty_state = Map.fromList
956   [ (exId             , (2, genFCall ty_state False         ) )
957   , (replaceId        , (3, genFCall ty_state False         ) )
958   , (headId           , (1, genFCall ty_state True          ) )
959   , (lastId           , (1, genFCall ty_state True          ) )
960   , (tailId           , (1, genFCall ty_state False         ) )
961   , (initId           , (1, genFCall ty_state False         ) )
962   , (takeId           , (2, genFCall ty_state False         ) )
963   , (dropId           , (2, genFCall ty_state False         ) )
964   , (selId            , (4, genFCall ty_state False         ) )
965   , (plusgtId         , (2, genFCall ty_state False         ) )
966   , (ltplusId         , (2, genFCall ty_state False         ) )
967   , (plusplusId       , (2, genFCall ty_state False         ) )
968   , (mapId            , (2, genMap                          ) )
969   , (zipWithId        , (3, genZipWith                      ) )
970   , (foldlId          , (3, genFoldl ty_state               ) )
971   , (foldrId          , (3, genFoldr ty_state               ) )
972   , (zipId            , (2, genZip                          ) )
973   , (unzipId          , (1, genUnzip                        ) )
974   , (shiftlId         , (2, genFCall ty_state False         ) )
975   , (shiftrId         , (2, genFCall ty_state False         ) )
976   , (rotlId           , (1, genFCall ty_state False         ) )
977   , (rotrId           , (1, genFCall ty_state False         ) )
978   , (concatId         , (1, genConcat                       ) )
979   , (reverseId        , (1, genFCall ty_state False         ) )
980   , (iteratenId       , (3, genIteraten ty_state            ) )
981   , (iterateId        , (2, genIterate ty_state             ) )
982   , (generatenId      , (3, genGeneraten ty_state           ) )
983   , (generateId       , (2, genGenerate ty_state            ) )
984   , (emptyId          , (0, genFCall ty_state False         ) )
985   , (singletonId      , (1, genFCall ty_state False         ) )
986   , (copynId          , (2, genFCall ty_state False         ) )
987   , (copyId           , (1, genCopy                         ) )
988   , (lengthTId        , (1, genFCall ty_state False         ) )
989   , (nullId           , (1, genFCall ty_state False         ) )
990   , (hwxorId          , (2, genOperator2 ty_state AST.Xor   ) )
991   , (hwandId          , (2, genOperator2 ty_state AST.And   ) )
992   , (hworId           , (2, genOperator2 ty_state AST.Or    ) )
993   , (hwnotId          , (1, genOperator1 ty_state AST.Not   ) )
994   , (plusId           , (2, genOperator2 ty_state (AST.:+:) ) )
995   , (timesId          , (2, genOperator2 ty_state (AST.:*:) ) )
996   , (negateId         , (1, genNegation ty_state            ) )
997   , (minusId          , (2, genOperator2 ty_state (AST.:-:) ) )
998   , (fromSizedWordId  , (1, genFromSizedWord ty_state       ) )
999   , (fromIntegerId    , (1, genFromInteger                  ) )
1000   ]