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