feldspar-compiler 0.6.0.2 → 0.7
raw patch · 68 files changed
+3441/−5461 lines, 68 filesdep +Cabaldep +QuickCheckdep +bytestringdep −MonadCatchIO-mtldep −ansi-terminaldep −haskell-src-extsdep ~basedep ~directorydep ~feldspar-languagePVP ok
version bump matches the API change (PVP)
Dependencies added: Cabal, QuickCheck, bytestring, criterion, data-default, deepseq, ghc-paths, plugins, plugins-multistage, pretty, storable-record, storable-tuple, tasty, tasty-golden, tasty-quickcheck, template-haskell
Dependencies removed: MonadCatchIO-mtl, ansi-terminal, haskell-src-exts, hint
Dependency ranges changed: base, directory, feldspar-language, syntactic
API changes (from Hackage documentation)
- Feldspar.Compiler.Backend.C.CodeGeneration: arrayTypeName :: String
- Feldspar.Compiler.Backend.C.CodeGeneration: class ToC a
- Feldspar.Compiler.Backend.C.CodeGeneration: decrArrayDepth :: Type -> Type
- Feldspar.Compiler.Backend.C.CodeGeneration: defaultMemberName :: String
- Feldspar.Compiler.Backend.C.CodeGeneration: getStructFieldType :: String -> Type -> Type
- Feldspar.Compiler.Backend.C.CodeGeneration: getStructTypeName :: Options -> Place -> Type -> String
- Feldspar.Compiler.Backend.C.CodeGeneration: ind :: (a -> String) -> a -> String
- Feldspar.Compiler.Backend.C.CodeGeneration: instance ToC (Variable ())
- Feldspar.Compiler.Backend.C.CodeGeneration: instance ToC Type
- Feldspar.Compiler.Backend.C.CodeGeneration: ivarTypeName :: String
- Feldspar.Compiler.Backend.C.CodeGeneration: listprint :: (a -> String) -> String -> [a] -> String
- Feldspar.Compiler.Backend.C.CodeGeneration: passByReference :: Type -> Bool
- Feldspar.Compiler.Backend.C.CodeGeneration: showName :: VariableRole -> Place -> Type -> String -> String
- Feldspar.Compiler.Backend.C.CodeGeneration: showType :: Options -> VariableRole -> Place -> Type -> IsRestrict -> String
- Feldspar.Compiler.Backend.C.CodeGeneration: showVariable :: Options -> Place -> VariableRole -> Type -> String -> String
- Feldspar.Compiler.Backend.C.CodeGeneration: structFieldNotFound :: String -> a
- Feldspar.Compiler.Backend.C.CodeGeneration: toC :: ToC a => Options -> Place -> a -> String
- Feldspar.Compiler.Backend.C.Library: Interactive :: CompilationMode
- Feldspar.Compiler.Backend.C.Library: Standalone :: CompilationMode
- Feldspar.Compiler.Backend.C.Library: data CompilationMode
- Feldspar.Compiler.Backend.C.Library: fixFunctionName :: String -> String
- Feldspar.Compiler.Backend.C.Library: instance Eq CompilationMode
- Feldspar.Compiler.Backend.C.Library: instance Show CompilationMode
- Feldspar.Compiler.Backend.C.Library: makeDebugCFileName :: String -> String
- Feldspar.Compiler.Backend.C.Library: makeDebugHFileName :: String -> String
- Feldspar.Compiler.Backend.C.Library: newName :: Monad m => String -> StateT Integer m String
- Feldspar.Compiler.Backend.C.Library: type AllocationInfo = ([Type], [Type], [Type])
- Feldspar.Compiler.Backend.C.Library: withColor :: Color -> IO () -> IO ()
- Feldspar.Compiler.Backend.C.Options: instance Eq Options
- Feldspar.Compiler.Backend.C.Options: instance Eq Platform
- Feldspar.Compiler.Backend.C.Options: instance Show Options
- Feldspar.Compiler.Backend.C.Options: instance Typeable1 Action
- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler: BlockProgramHandler :: BlockProgramHandler
- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler: data BlockProgramHandler
- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler: instance Combine [Declaration ()]
- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler: instance Default [Declaration ()]
- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler: instance Plugin BlockProgramHandler
- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler: instance Transformable BlockProgramHandler Block
- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler: instance Transformable BlockProgramHandler Program
- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler: instance Transformation BlockProgramHandler
- Feldspar.Compiler.Backend.C.Plugin.Locator: GetPrgAssign :: GetPrgAssign
- Feldspar.Compiler.Backend.C.Plugin.Locator: GetPrgBranch :: GetPrgBranch
- Feldspar.Compiler.Backend.C.Plugin.Locator: GetPrgParLoop :: GetPrgParLoop
- Feldspar.Compiler.Backend.C.Plugin.Locator: GetPrgProcCall :: GetPrgProcCall
- Feldspar.Compiler.Backend.C.Plugin.Locator: GetPrgSeqLoop :: GetPrgSeqLoop
- Feldspar.Compiler.Backend.C.Plugin.Locator: contains :: (Ord a, Ord b) => (a, b) -> ((a, b), (a, b)) -> Bool
- Feldspar.Compiler.Backend.C.Plugin.Locator: data GetPrgAssign
- Feldspar.Compiler.Backend.C.Plugin.Locator: data GetPrgBranch
- Feldspar.Compiler.Backend.C.Plugin.Locator: data GetPrgParLoop
- Feldspar.Compiler.Backend.C.Plugin.Locator: data GetPrgProcCall
- Feldspar.Compiler.Backend.C.Plugin.Locator: data GetPrgSeqLoop
- Feldspar.Compiler.Backend.C.Plugin.Locator: getPrgAssign :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)
- Feldspar.Compiler.Backend.C.Plugin.Locator: getPrgBranch :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)
- Feldspar.Compiler.Backend.C.Plugin.Locator: getPrgParLoop :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)
- Feldspar.Compiler.Backend.C.Plugin.Locator: getPrgProcCall :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)
- Feldspar.Compiler.Backend.C.Plugin.Locator: getPrgSeqLoop :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Combine (Program DebugToCSemanticInfo)
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Combine Bool
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Default (Program DebugToCSemanticInfo)
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Default Bool
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Plugin GetPrgAssign
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Plugin GetPrgBranch
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Plugin GetPrgParLoop
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Plugin GetPrgProcCall
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Plugin GetPrgSeqLoop
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformable GetPrgAssign Program
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformable GetPrgBranch Program
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformable GetPrgParLoop Program
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformable GetPrgProcCall Program
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformable GetPrgSeqLoop Program
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformation GetPrgAssign
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformation GetPrgBranch
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformation GetPrgParLoop
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformation GetPrgProcCall
- Feldspar.Compiler.Backend.C.Plugin.Locator: instance Transformation GetPrgSeqLoop
- Feldspar.Compiler.Backend.C.Plugin.Locator: myShow :: Program DebugToCSemanticInfo -> String
- Feldspar.Compiler.Backend.C.Plugin.Locator: myShowB :: Block DebugToCSemanticInfo -> String
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: DebugToC :: DebugToC
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: addIndent :: Int -> Int
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: code :: MonadState ([Char], Int, Int) m => [Char] -> m ()
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: compToC :: ((Options, Place), Int) -> Module () -> (String, (Int, Int))
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: compToCWithInfos :: ((Options, Place), Int) -> Module () -> (Module DebugToCSemanticInfo, (String, (Int, Int)))
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: complexTransform :: (MonadState (t, t2, t3) m, Transformable t1 s, ~ * (State t1) (t2, t3)) => t1 -> Down t1 -> s (From t1) -> m (Result t1 s)
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: data DebugToC
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: data DebugToCSemanticInfo
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: defaultState :: Int -> Int -> (String, Int, Int)
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: displayComment :: Int -> [String] -> String
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: displayMemInfo :: String -> [Type] -> String
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: displayType :: Type -> String
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: indenter :: MonadState ([Char], t, t1) m => Int -> m ()
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo ActualParameter
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo ArrayConst
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo ArrayElem
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Assign
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Block
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo BoolConst
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Branch
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Cast
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Comment
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo ComplexConst
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Constant
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Declaration
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Empty
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Entity
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Expression
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo FloatConst
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo FunctionCall
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo IntConst
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Module
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo ParLoop
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo ProcDecl
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo ProcDef
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo ProcedureCall
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Program
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Run
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo SeqLoop
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Sequence
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo SizeOf
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Spawn
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Struct
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo StructField
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo StructMember
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Annotation DebugToCSemanticInfo Variable
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Plugin DebugToC
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC ActualParameter
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC Block
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC Constant
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC Declaration
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC Entity
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC Expression
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC Module
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC Program
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC StructMember
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable DebugToC Variable
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable1 DebugToC [] ActualParameter
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable1 DebugToC [] Constant
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable1 DebugToC [] Declaration
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable1 DebugToC [] Entity
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable1 DebugToC [] Expression
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable1 DebugToC [] Program
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable1 DebugToC [] StructMember
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformable1 DebugToC [] Variable
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: instance Transformation DebugToC
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: monadicListTransform' :: (MonadState ([Char], Int, Int) m, Transformable1 t s a, ~ * (Up t) [Char], ~ * (State t) (Int, Int)) => t -> Down t -> s (a (From t)) -> m (Result1 t s a)
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: monadicTransform' :: (MonadState ([Char], Int, Int) m, Transformable t s, ~ * (Up t) [Char], ~ * (State t) (Int, Int)) => t -> Down t -> s (From t) -> m (Result t s)
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: putIndent :: Int -> String
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: transform1' :: (Num t1, Transformable1 t5 [] s, Transformable t5 s, ~ * (Up t5) [Char], ~ * (Up t) [Char], ~ * (Down t5) (t2, t3, t4), ~ * (State t5) (t1, Int), ~ * (State t) (t1, Int), ~ * (To t) (To t5)) => t5 -> (t1, Int) -> (t2, t3, t4) -> [s (From t5)] -> [Char] -> t1 -> Result1 t [] s
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: transformActParam :: (Transformable t4 Expression, ~ * (Label (To t4) ActualParameter) ((Int, Int), (Int, Int)), ~ * (Up t4) [Char], ~ * (Up t1) [Char], ~ * (Down t4) (Options, t2, t3), ~ * (State t4) (Int, Int), ~ * (State t1) (Int, Int), ~ * (To t1) (To t4)) => t4 -> (Int, Int) -> (Options, t, t3) -> ActualParameter (From t4) -> t2 -> Result t1 ActualParameter
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: transformConst :: (~ * (Label (To t3) Constant) ((Int, Int), (Int, Int)), ~ * (Label (To t3) IntConst) ((Int, Int), (Int, Int)), ~ * (Label (To t3) FloatConst) ((Int, Int), (Int, Int)), ~ * (Label (To t3) BoolConst) ((Int, Int), (Int, Int)), ~ * (Up t3) [Char], ~ * (State t3) (Int, Int)) => t -> (Int, Int) -> (Options, t1, t2) -> Constant () -> String -> Result t3 Constant
- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint: transformFuncCall :: (Transformable t4 Expression, ~ * (Label (To t4) Expression) ((Int, Int), (Int, Int)), ~ * (Label (To t4) FunctionCall) ((Int, Int), (Int, Int)), ~ * (Up t4) [Char], ~ * (Up t3) [Char], ~ * (Down t4) (t, t1, t2), ~ * (State t4) (Int, Int), ~ * (State t3) (Int, Int), ~ * (To t3) (To t4)) => t4 -> (Int, Int) -> (t, t1, t2) -> Expression (From t4) -> [Char] -> [Char] -> [Char] -> Result t3 Expression
- Feldspar.Compiler.Backend.C.Plugin.Rule: instance (DefaultTransformable RulePlugin t, Typeable1 t) => Transformable RulePlugin t
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: GlobalCollector :: GlobalCollector
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: TypeCheck :: TypeCheck
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: TypeCheckDown :: TypeCatalog -> Bool -> TypeCheckDown
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: TypeCorrector :: TypeCorrector
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: data GlobalCollector
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: data TypeCheck
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: data TypeCheckDown
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: data TypeCorrector
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: globals :: TypeCheckDown -> TypeCatalog
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: inDecl :: TypeCheckDown -> Bool -> TypeCheckDown
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: inDeclaration :: TypeCheckDown -> Bool
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Combine [String]
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Default TypeCatalog
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Default [String]
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Plugin TypeCorrector
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable GlobalCollector Entity
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable GlobalCollector Variable
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable TypeCheck Block
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable TypeCheck Declaration
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable TypeCheck Entity
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable TypeCheck Program
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable TypeCheck Variable
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable TypeCorrector Entity
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformable TypeCorrector Variable
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformation GlobalCollector
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformation TypeCheck
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: instance Transformation TypeCorrector
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: select :: Type -> Type -> Type
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: type TypeCatalog = Map String Type
- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector: typeCorrectorError :: String -> a
- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator: TypeDefinitionGenerator :: TypeDefinitionGenerator
- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator: data TypeDefinitionGenerator
- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator: getTypes :: Options -> Type -> [Entity ()]
- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator: instance Plugin TypeDefinitionGenerator
- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator: instance Transformable TypeDefinitionGenerator Module
- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator: instance Transformable TypeDefinitionGenerator Variable
- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator: instance Transformation TypeDefinitionGenerator
- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator: typeDefGenError :: ErrorClass -> String -> a
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: Parameters :: [String] -> [String] -> Parameters
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: VariableRoleAssigner :: VariableRoleAssigner
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: data Parameters
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: data VariableRoleAssigner
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: inParametersVRA :: Parameters -> [String]
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: instance Plugin VariableRoleAssigner
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: instance Transformable VariableRoleAssigner Entity
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: instance Transformable VariableRoleAssigner Variable
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: instance Transformation VariableRoleAssigner
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: isComposite :: Variable () -> Bool
- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner: outParametersVRA :: Parameters -> [String]
- Feldspar.Compiler.Compiler: IncludesNeeded :: IncludesNeeded
- Feldspar.Compiler.Compiler: NoIncludesNeeded :: Int -> IncludesNeeded
- Feldspar.Compiler.Compiler: SomeCompilable :: a -> SomeCompilable
- Feldspar.Compiler.Compiler: data IncludesNeeded
- Feldspar.Compiler.Compiler: data SomeCompilable
- Feldspar.Compiler.Compiler: endPosition :: CompToCCoreResult -> Position
- Feldspar.Compiler.Compiler: executePluginChain' :: Compilable c internal => CompilationMode -> c -> OriginalFunctionSignature -> Options -> Module ()
- Feldspar.Compiler.Compiler: genIncludeLinesCore :: [String] -> (String, Int)
- Feldspar.Compiler.Compiler: incneedLineNum :: IncludesNeeded -> Int
- Feldspar.Compiler.Compiler: instance Typeable SomeCompilable
- Feldspar.Compiler.Compiler: precompilationExternalInfo :: ExternalInfoCollection -> ExternalInfo Precompilation
- Feldspar.Compiler.Compiler: separateAndCompileToCCore :: Compilable t internal => (Module () -> [Module ()]) -> CompilationMode -> t -> IncludesNeeded -> OriginalFunctionSignature -> Options -> [(CompToCCoreResult, Module ())]
- Feldspar.Compiler.Compiler: type Position = (Int, Int)
- Feldspar.Compiler.Compiler: typeCorrectorExternalInfo :: ExternalInfoCollection -> ExternalInfo TypeCorrector
- Feldspar.Compiler.Compiler: typeDefinitionGeneratorExternalInfo :: ExternalInfoCollection -> ExternalInfo TypeDefinitionGenerator
- Feldspar.Compiler.Compiler: unrollExternalInfo :: ExternalInfoCollection -> ExternalInfo UnrollPlugin
- Feldspar.Compiler.Compiler: variableRoleAssignerExternalInfo :: ExternalInfoCollection -> ExternalInfo VariableRoleAssigner
- Feldspar.Compiler.Frontend.Interactive.Interface: AssignType :: PrgType
- Feldspar.Compiler.Frontend.Interactive.Interface: ForType :: PrgType
- Feldspar.Compiler.Frontend.Interactive.Interface: IfType :: PrgType
- Feldspar.Compiler.Frontend.Interactive.Interface: assignPrg :: PrgType
- Feldspar.Compiler.Frontend.Interactive.Interface: data PrgType
- Feldspar.Compiler.Frontend.Interactive.Interface: forPrg :: PrgType
- Feldspar.Compiler.Frontend.Interactive.Interface: getProgram :: (Int, Int) -> PrgType -> Module DebugToCSemanticInfo -> IO ()
- Feldspar.Compiler.Frontend.Interactive.Interface: icompileWithInfos :: Compilable t internal => t -> String -> Options -> SplitCompToCCoreResult
- Feldspar.Compiler.Frontend.Interactive.Interface: ifPrg :: PrgType
- Feldspar.Compiler.Imperative.FromCore: buildInParamDescriptor :: SyntacticFeld a => a -> [Int]
- Feldspar.Compiler.Imperative.FromCore: class SyntacticFeld a => Compilable a internal | a -> internal
- Feldspar.Compiler.Imperative.FromCore: instance (SyntacticFeld a) => Compilable a ()
- Feldspar.Compiler.Imperative.FromCore: instance Compile Empty FeldDomain
- Feldspar.Compiler.Imperative.FromCore: instance Compile FeldDomain FeldDomain
- Feldspar.Compiler.Imperative.FromCore: numArgs :: SyntacticFeld a => a -> Int
- Feldspar.Compiler.Imperative.FromCore.Array: instance (Compile dom dom, Project (CLambda Type) dom, Project (Literal :|| Type) dom, Project (Variable :|| Type) dom) => Compile (Array :|| Type) dom
- Feldspar.Compiler.Imperative.FromCore.Binding: instance (Compile dom dom, Project (CLambda Type) dom) => Compile (Let :|| Type) dom
- Feldspar.Compiler.Imperative.FromCore.Interpretation: mkVarName :: VarId -> String
- Feldspar.Compiler.Imperative.FromCore.Interpretation: tellDecl :: [Def] -> CodeWriter ()
- Feldspar.Compiler.Imperative.FromCore.Interpretation: type Task = [Prog]
- Feldspar.Compiler.Imperative.FromCore.Literal: literalLoc :: Location -> TypeRep a -> Size a -> a -> CodeWriter ()
- Feldspar.Compiler.Imperative.FromCore.Loop: instance (Compile dom dom, Project (CLambda Type) dom, Project (Literal :|| Type) dom, Project (Variable :|| Type) dom) => Compile (Loop :|| Type) dom
- Feldspar.Compiler.Imperative.FromCore.MutableToPure: instance (Compile dom dom, Project (CLambda Type) dom, Project (Variable :|| Type) dom) => Compile MutableToPure dom
- Feldspar.Compiler.Imperative.Frontend: (:!:) :: Expr -> Expr -> Expr
- Feldspar.Compiler.Imperative.Frontend: (:.:) :: Expr -> String -> Expr
- Feldspar.Compiler.Imperative.Frontend: (:=) :: Expr -> Expr -> Prog
- Feldspar.Compiler.Imperative.Frontend: Array :: Type -> Type
- Feldspar.Compiler.Imperative.Frontend: BComment :: String -> Prog
- Feldspar.Compiler.Imperative.Frontend: Binop :: Type -> String -> [Expr] -> Expr
- Feldspar.Compiler.Imperative.Frontend: Bit :: Type
- Feldspar.Compiler.Imperative.Frontend: Bl :: [Def] -> Prog -> Block
- Feldspar.Compiler.Imperative.Frontend: Block :: [Def] -> Prog -> Prog
- Feldspar.Compiler.Imperative.Frontend: Boolean :: Type
- Feldspar.Compiler.Imperative.Frontend: Call :: String -> [Param] -> Prog
- Feldspar.Compiler.Imperative.Frontend: Cast :: Type -> Expr -> Expr
- Feldspar.Compiler.Imperative.Frontend: Comment :: String -> Prog
- Feldspar.Compiler.Imperative.Frontend: Complex :: Type -> Type
- Feldspar.Compiler.Imperative.Frontend: Def :: Type -> String -> Def
- Feldspar.Compiler.Imperative.Frontend: Fl :: Expr
- Feldspar.Compiler.Imperative.Frontend: Floating :: Type
- Feldspar.Compiler.Imperative.Frontend: Fn :: String -> Param
- Feldspar.Compiler.Imperative.Frontend: FnAddr :: String -> Param
- Feldspar.Compiler.Imperative.Frontend: For :: String -> Expr -> Int -> Prog -> Prog
- Feldspar.Compiler.Imperative.Frontend: Fun :: Type -> String -> [Expr] -> Expr
- Feldspar.Compiler.Imperative.Frontend: I16 :: Type
- Feldspar.Compiler.Imperative.Frontend: I32 :: Type
- Feldspar.Compiler.Imperative.Frontend: I40 :: Type
- Feldspar.Compiler.Imperative.Frontend: I64 :: Type
- Feldspar.Compiler.Imperative.Frontend: I8 :: Type
- Feldspar.Compiler.Imperative.Frontend: IVar :: Type -> Type
- Feldspar.Compiler.Imperative.Frontend: If :: Expr -> Prog -> Prog -> Prog
- Feldspar.Compiler.Imperative.Frontend: In :: Expr -> Param
- Feldspar.Compiler.Imperative.Frontend: Init :: Type -> String -> Expr -> Def
- Feldspar.Compiler.Imperative.Frontend: LitC :: Expr -> Expr -> Expr
- Feldspar.Compiler.Imperative.Frontend: LitF :: Double -> Expr
- Feldspar.Compiler.Imperative.Frontend: LitI :: Type -> Integer -> Expr
- Feldspar.Compiler.Imperative.Frontend: Mod :: [Ent] -> Mod
- Feldspar.Compiler.Imperative.Frontend: Out :: Expr -> Param
- Feldspar.Compiler.Imperative.Frontend: Pointer :: Type -> String -> Var
- Feldspar.Compiler.Imperative.Frontend: ProcDcl :: String -> [Var] -> [Var] -> Ent
- Feldspar.Compiler.Imperative.Frontend: ProcDf :: String -> [Var] -> [Var] -> Prog -> Ent
- Feldspar.Compiler.Imperative.Frontend: Ptr :: Type -> String -> Expr
- Feldspar.Compiler.Imperative.Frontend: Seq :: [Prog] -> Prog
- Feldspar.Compiler.Imperative.Frontend: SizedArray :: Int -> Type -> Type
- Feldspar.Compiler.Imperative.Frontend: SizeofE :: Expr -> Expr
- Feldspar.Compiler.Imperative.Frontend: SizeofT :: Type -> Expr
- Feldspar.Compiler.Imperative.Frontend: Skip :: Prog
- Feldspar.Compiler.Imperative.Frontend: Struct :: [(String, Type)] -> Type
- Feldspar.Compiler.Imperative.Frontend: StructD :: String -> [(String, Type)] -> Ent
- Feldspar.Compiler.Imperative.Frontend: Tr :: Expr
- Feldspar.Compiler.Imperative.Frontend: TypAuto :: Type -> Param
- Feldspar.Compiler.Imperative.Frontend: TypScalar :: Type -> Param
- Feldspar.Compiler.Imperative.Frontend: U16 :: Type
- Feldspar.Compiler.Imperative.Frontend: U32 :: Type
- Feldspar.Compiler.Imperative.Frontend: U40 :: Type
- Feldspar.Compiler.Imperative.Frontend: U64 :: Type
- Feldspar.Compiler.Imperative.Frontend: U8 :: Type
- Feldspar.Compiler.Imperative.Frontend: UserType :: String -> Type
- Feldspar.Compiler.Imperative.Frontend: Var :: Type -> String -> Expr
- Feldspar.Compiler.Imperative.Frontend: Variable :: Type -> String -> Var
- Feldspar.Compiler.Imperative.Frontend: Void :: Type
- Feldspar.Compiler.Imperative.Frontend: While :: Prog -> Expr -> Prog -> Prog
- Feldspar.Compiler.Imperative.Frontend: assignProg :: Expr -> Expr -> Prog
- Feldspar.Compiler.Imperative.Frontend: boolToExpr :: Bool -> Expr
- Feldspar.Compiler.Imperative.Frontend: class Interface t where type family Repr t
- Feldspar.Compiler.Imperative.Frontend: class Named a
- Feldspar.Compiler.Imperative.Frontend: copyProgLen :: Expr -> Expr -> Expr -> Prog
- Feldspar.Compiler.Imperative.Frontend: copyProgPos :: Expr -> Expr -> Expr -> Prog
- Feldspar.Compiler.Imperative.Frontend: data Block
- Feldspar.Compiler.Imperative.Frontend: data Def
- Feldspar.Compiler.Imperative.Frontend: data Ent
- Feldspar.Compiler.Imperative.Frontend: data Expr
- Feldspar.Compiler.Imperative.Frontend: data Mod
- Feldspar.Compiler.Imperative.Frontend: data Param
- Feldspar.Compiler.Imperative.Frontend: data Prog
- Feldspar.Compiler.Imperative.Frontend: data Type
- Feldspar.Compiler.Imperative.Frontend: data Var
- Feldspar.Compiler.Imperative.Frontend: fromInterface :: Interface t => t -> Repr t
- Feldspar.Compiler.Imperative.Frontend: getName :: Named a => a -> String
- Feldspar.Compiler.Imperative.Frontend: instance Eq Block
- Feldspar.Compiler.Imperative.Frontend: instance Eq Def
- Feldspar.Compiler.Imperative.Frontend: instance Eq Ent
- Feldspar.Compiler.Imperative.Frontend: instance Eq Expr
- Feldspar.Compiler.Imperative.Frontend: instance Eq Param
- Feldspar.Compiler.Imperative.Frontend: instance Eq Prog
- Feldspar.Compiler.Imperative.Frontend: instance Eq Type
- Feldspar.Compiler.Imperative.Frontend: instance Eq Var
- Feldspar.Compiler.Imperative.Frontend: instance HasType Expr
- Feldspar.Compiler.Imperative.Frontend: instance HasType Var
- Feldspar.Compiler.Imperative.Frontend: instance Interface Block
- Feldspar.Compiler.Imperative.Frontend: instance Interface Def
- Feldspar.Compiler.Imperative.Frontend: instance Interface Ent
- Feldspar.Compiler.Imperative.Frontend: instance Interface Expr
- Feldspar.Compiler.Imperative.Frontend: instance Interface Mod
- Feldspar.Compiler.Imperative.Frontend: instance Interface Param
- Feldspar.Compiler.Imperative.Frontend: instance Interface Prog
- Feldspar.Compiler.Imperative.Frontend: instance Interface Type
- Feldspar.Compiler.Imperative.Frontend: instance Interface Var
- Feldspar.Compiler.Imperative.Frontend: instance Monoid Block
- Feldspar.Compiler.Imperative.Frontend: instance Monoid Prog
- Feldspar.Compiler.Imperative.Frontend: instance Named Def
- Feldspar.Compiler.Imperative.Frontend: instance Named Var
- Feldspar.Compiler.Imperative.Frontend: instance Show Block
- Feldspar.Compiler.Imperative.Frontend: instance Show Def
- Feldspar.Compiler.Imperative.Frontend: instance Show Ent
- Feldspar.Compiler.Imperative.Frontend: instance Show Expr
- Feldspar.Compiler.Imperative.Frontend: instance Show Mod
- Feldspar.Compiler.Imperative.Frontend: instance Show Param
- Feldspar.Compiler.Imperative.Frontend: instance Show Prog
- Feldspar.Compiler.Imperative.Frontend: instance Show Type
- Feldspar.Compiler.Imperative.Frontend: instance Show Var
- Feldspar.Compiler.Imperative.Frontend: toInterface :: Interface t => Repr t -> t
- Feldspar.Compiler.Imperative.Frontend: vType :: Var -> Type
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: Collect :: Collect
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: data Collect
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: instance [overlap ok] Combine Collection
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: instance [overlap ok] Default Collection
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: instance [overlap ok] Plugin Collect
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: instance [overlap ok] Transformable Collect Block
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: instance [overlap ok] Transformable Collect Program
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: instance [overlap ok] Transformable Collect Variable
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: instance [overlap ok] Transformation Collect
- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars: type Collection = Map String Var
- Feldspar.Compiler.Imperative.Plugin.ConstantFolding: ConstantFolding :: ConstantFolding
- Feldspar.Compiler.Imperative.Plugin.ConstantFolding: data ConstantFolding
- Feldspar.Compiler.Imperative.Plugin.ConstantFolding: instance Plugin ConstantFolding
- Feldspar.Compiler.Imperative.Plugin.ConstantFolding: instance Transformable ConstantFolding Expression
- Feldspar.Compiler.Imperative.Plugin.ConstantFolding: instance Transformation ConstantFolding
- Feldspar.Compiler.Imperative.Plugin.Free: Free :: Free
- Feldspar.Compiler.Imperative.Plugin.Free: data Free
- Feldspar.Compiler.Imperative.Plugin.Free: instance [overlap ok] Plugin Free
- Feldspar.Compiler.Imperative.Plugin.Free: instance [overlap ok] Transformable Free Block
- Feldspar.Compiler.Imperative.Plugin.Free: instance [overlap ok] Transformation Free
- Feldspar.Compiler.Imperative.Plugin.IVars: instance [overlap ok] Transformable IVarPlugin Block
- Feldspar.Compiler.Imperative.Plugin.Naming: Precompilation :: Precompilation
- Feldspar.Compiler.Imperative.Plugin.Naming: PrecompilationExternalInfo :: OriginalFunctionSignature -> [Int] -> Int -> CompilationMode -> PrecompilationExternalInfo
- Feldspar.Compiler.Imperative.Plugin.Naming: SignatureInformation :: String -> [String] -> Maybe [Maybe String] -> SignatureInformation
- Feldspar.Compiler.Imperative.Plugin.Naming: addPostfixNumberToMaybeString :: (Maybe String, Int) -> Maybe String
- Feldspar.Compiler.Imperative.Plugin.Naming: compilationMode :: PrecompilationExternalInfo -> CompilationMode
- Feldspar.Compiler.Imperative.Plugin.Naming: data Precompilation
- Feldspar.Compiler.Imperative.Plugin.Naming: data PrecompilationExternalInfo
- Feldspar.Compiler.Imperative.Plugin.Naming: data SignatureInformation
- Feldspar.Compiler.Imperative.Plugin.Naming: generatedImperativeParameterNames :: SignatureInformation -> [String]
- Feldspar.Compiler.Imperative.Plugin.Naming: getVariableName :: SignatureInformation -> String -> Maybe String
- Feldspar.Compiler.Imperative.Plugin.Naming: inflate :: Int -> [Maybe String] -> [Maybe String]
- Feldspar.Compiler.Imperative.Plugin.Naming: inputParametersDescriptor :: PrecompilationExternalInfo -> [Int]
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Default SignatureInformation
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Eq SignatureInformation
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Plugin Precompilation
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Show SignatureInformation
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Transformable Precompilation ActualParameter
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Transformable Precompilation Entity
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Transformable Precompilation Program
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Transformable Precompilation Variable
- Feldspar.Compiler.Imperative.Plugin.Naming: instance Transformation Precompilation
- Feldspar.Compiler.Imperative.Plugin.Naming: maybeStr2Str :: Maybe String -> String
- Feldspar.Compiler.Imperative.Plugin.Naming: numberOfFunctionArguments :: PrecompilationExternalInfo -> Int
- Feldspar.Compiler.Imperative.Plugin.Naming: originalFunctionName :: SignatureInformation -> String
- Feldspar.Compiler.Imperative.Plugin.Naming: originalFunctionSignature :: PrecompilationExternalInfo -> OriginalFunctionSignature
- Feldspar.Compiler.Imperative.Plugin.Naming: originalParameterNames :: SignatureInformation -> Maybe [Maybe String]
- Feldspar.Compiler.Imperative.Plugin.Naming: parameterNameListConsolidator :: PrecompilationExternalInfo -> [Maybe String]
- Feldspar.Compiler.Imperative.Plugin.Naming: precompilationError :: ErrorClass -> String -> a
- Feldspar.Compiler.Imperative.Plugin.Naming: prefix :: SignatureInformation -> String -> String
- Feldspar.Compiler.Imperative.Plugin.Naming: proceduresToPrefix :: [String]
- Feldspar.Compiler.Imperative.Plugin.Unroll: SemInfPrg :: Int -> [String] -> String -> SemInfPrg
- Feldspar.Compiler.Imperative.Plugin.Unroll: Unroll1 :: Unroll1
- Feldspar.Compiler.Imperative.Plugin.Unroll: Unroll2 :: Unroll2
- Feldspar.Compiler.Imperative.Plugin.Unroll: UnrollPlugin :: UnrollPlugin
- Feldspar.Compiler.Imperative.Plugin.Unroll: data SemInfPrg
- Feldspar.Compiler.Imperative.Plugin.Unroll: data Unroll1
- Feldspar.Compiler.Imperative.Plugin.Unroll: data Unroll2
- Feldspar.Compiler.Imperative.Plugin.Unroll: data UnrollPlugin
- Feldspar.Compiler.Imperative.Plugin.Unroll: data UnrollSemInf
- Feldspar.Compiler.Imperative.Plugin.Unroll: getVarNameDecl :: Declaration t -> String
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf ActualParameter
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf ArrayConst
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf ArrayElem
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Assign
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Block
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf BoolConst
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Branch
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Cast
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Comment
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf ComplexConst
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Constant
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Declaration
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Empty
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Entity
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Expression
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf FloatConst
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf FunctionCall
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf IntConst
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Module
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf ParLoop
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf ProcDecl
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf ProcDef
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf ProcedureCall
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Program
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Run
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf SeqLoop
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Sequence
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf SizeOf
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Spawn
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Struct
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf StructField
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf StructMember
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Annotation UnrollSemInf Variable
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Combine Bool
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Default (Maybe SemInfPrg)
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Default Bool
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Eq SemInfPrg
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Plugin UnrollPlugin
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Show SemInfPrg
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Transformable Unroll1 Program
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Transformable Unroll2 Expression
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Transformable Unroll2 Program
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Transformable Unroll2 Variable
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Transformation Unroll1
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Transformation Unroll2
- Feldspar.Compiler.Imperative.Plugin.Unroll: instance Transformation UnrollPlugin
- Feldspar.Compiler.Imperative.Plugin.Unroll: isJust :: Maybe t -> Bool
- Feldspar.Compiler.Imperative.Plugin.Unroll: loopVar :: SemInfPrg -> String
- Feldspar.Compiler.Imperative.Plugin.Unroll: position :: SemInfPrg -> Int
- Feldspar.Compiler.Imperative.Plugin.Unroll: renameDeclaration :: Declaration t -> String -> Declaration t
- Feldspar.Compiler.Imperative.Plugin.Unroll: renameVariable :: Variable t -> String -> Variable t
- Feldspar.Compiler.Imperative.Plugin.Unroll: varNames :: SemInfPrg -> [String]
- Feldspar.Compiler.Imperative.Representation: AddressNeed_pl :: Place
- Feldspar.Compiler.Imperative.Representation: Auto :: TypeParameterMode
- Feldspar.Compiler.Imperative.Representation: Branch :: Expression t -> Block t -> Block t -> Label t Branch -> Label t Program -> Program t
- Feldspar.Compiler.Imperative.Representation: Declaration_pl :: Place
- Feldspar.Compiler.Imperative.Representation: FunctionCallIn_pl :: Place
- Feldspar.Compiler.Imperative.Representation: In :: Expression t -> Label t ActualParameter -> ActualParameter t
- Feldspar.Compiler.Imperative.Representation: LiteralLen :: Int -> Length
- Feldspar.Compiler.Imperative.Representation: MainParameter_pl :: Place
- Feldspar.Compiler.Imperative.Representation: Out :: Expression t -> Label t ActualParameter -> ActualParameter t
- Feldspar.Compiler.Imperative.Representation: ProcDecl :: String -> [Variable t] -> [Variable t] -> Label t ProcDecl -> Label t Entity -> Entity t
- Feldspar.Compiler.Imperative.Representation: ProcDef :: String -> [Variable t] -> [Variable t] -> Block t -> Label t ProcDef -> Label t Entity -> Entity t
- Feldspar.Compiler.Imperative.Representation: Scalar :: TypeParameterMode
- Feldspar.Compiler.Imperative.Representation: UndefinedLen :: Length
- Feldspar.Compiler.Imperative.Representation: Value :: VariableRole
- Feldspar.Compiler.Imperative.Representation: ValueNeed_pl :: Place
- Feldspar.Compiler.Imperative.Representation: actParamLabel :: ActualParameter t -> Label t ActualParameter
- Feldspar.Compiler.Imperative.Representation: addressNeeded :: ActualParameter t -> Bool
- Feldspar.Compiler.Imperative.Representation: arrayLabel :: Expression t -> Label t ArrayElem
- Feldspar.Compiler.Imperative.Representation: assignLabel :: Program t -> Label t Assign
- Feldspar.Compiler.Imperative.Representation: blockLabel :: Block t -> Label t Block
- Feldspar.Compiler.Imperative.Representation: boolConstLabel :: Constant t -> Label t BoolConst
- Feldspar.Compiler.Imperative.Representation: branchCond :: Program t -> Expression t
- Feldspar.Compiler.Imperative.Representation: branchLabel :: Program t -> Label t Branch
- Feldspar.Compiler.Imperative.Representation: castLabel :: Expression t -> Label t Cast
- Feldspar.Compiler.Imperative.Representation: class Annotation t (s :: * -> *) where type family Label t s
- Feldspar.Compiler.Imperative.Representation: class (Eq (Label t Module), Eq (Label t Entity), Eq (Label t Struct), Eq (Label t ProcDef), Eq (Label t ProcDecl), Eq (Label t StructMember), Eq (Label t Block), Eq (Label t Program), Eq (Label t Empty), Eq (Label t Comment), Eq (Label t Assign), Eq (Label t ProcedureCall), Eq (Label t Spawn), Eq (Label t Run), Eq (Label t Sequence), Eq (Label t Branch), Eq (Label t SeqLoop), Eq (Label t ParLoop), Eq (Label t ActualParameter), Eq (Label t Declaration), Eq (Label t Expression), Eq (Label t FunctionCall), Eq (Label t Cast), Eq (Label t SizeOf), Eq (Label t StructField), Eq (Label t ArrayElem), Eq (Label t Constant), Eq (Label t IntConst), Eq (Label t FloatConst), Eq (Label t BoolConst), Eq (Label t ArrayConst), Eq (Label t ComplexConst), Eq (Label t Variable)) => EqLabel t
- Feldspar.Compiler.Imperative.Representation: class Labeled c
- Feldspar.Compiler.Imperative.Representation: class (Show (Label t Module), Show (Label t Entity), Show (Label t Struct), Show (Label t ProcDef), Show (Label t ProcDecl), Show (Label t StructMember), Show (Label t Block), Show (Label t Program), Show (Label t Empty), Show (Label t Comment), Show (Label t Assign), Show (Label t ProcedureCall), Show (Label t Spawn), Show (Label t Run), Show (Label t Sequence), Show (Label t Branch), Show (Label t SeqLoop), Show (Label t ParLoop), Show (Label t ActualParameter), Show (Label t Declaration), Show (Label t Expression), Show (Label t FunctionCall), Show (Label t Cast), Show (Label t SizeOf), Show (Label t ArrayElem), Show (Label t StructField), Show (Label t Constant), Show (Label t IntConst), Show (Label t FloatConst), Show (Label t BoolConst), Show (Label t ArrayConst), Show (Label t ComplexConst), Show (Label t Variable)) => ShowLabel t
- Feldspar.Compiler.Imperative.Representation: commentLabel :: Program t -> Label t Comment
- Feldspar.Compiler.Imperative.Representation: complexConstLabel :: Constant t -> Label t ComplexConst
- Feldspar.Compiler.Imperative.Representation: constLabel :: Constant t -> Label t Constant
- Feldspar.Compiler.Imperative.Representation: data ArrayConst t
- Feldspar.Compiler.Imperative.Representation: data ArrayElem t
- Feldspar.Compiler.Imperative.Representation: data Assign t
- Feldspar.Compiler.Imperative.Representation: data BoolConst t
- Feldspar.Compiler.Imperative.Representation: data Branch t
- Feldspar.Compiler.Imperative.Representation: data Cast t
- Feldspar.Compiler.Imperative.Representation: data Comment t
- Feldspar.Compiler.Imperative.Representation: data ComplexConst t
- Feldspar.Compiler.Imperative.Representation: data Empty t
- Feldspar.Compiler.Imperative.Representation: data FloatConst t
- Feldspar.Compiler.Imperative.Representation: data FunctionCall t
- Feldspar.Compiler.Imperative.Representation: data IntConst t
- Feldspar.Compiler.Imperative.Representation: data LeftFunCall t
- Feldspar.Compiler.Imperative.Representation: data Length
- Feldspar.Compiler.Imperative.Representation: data ParLoop t
- Feldspar.Compiler.Imperative.Representation: data Place
- Feldspar.Compiler.Imperative.Representation: data ProcDecl t
- Feldspar.Compiler.Imperative.Representation: data ProcDef t
- Feldspar.Compiler.Imperative.Representation: data ProcedureCall t
- Feldspar.Compiler.Imperative.Representation: data Run t
- Feldspar.Compiler.Imperative.Representation: data SeqLoop t
- Feldspar.Compiler.Imperative.Representation: data Sequence t
- Feldspar.Compiler.Imperative.Representation: data SizeOf t
- Feldspar.Compiler.Imperative.Representation: data Spawn t
- Feldspar.Compiler.Imperative.Representation: data Struct t
- Feldspar.Compiler.Imperative.Representation: data StructField t
- Feldspar.Compiler.Imperative.Representation: data TypeParameterMode
- Feldspar.Compiler.Imperative.Representation: data VariableRole
- Feldspar.Compiler.Imperative.Representation: declLabel :: Declaration t -> Label t Declaration
- Feldspar.Compiler.Imperative.Representation: definitionLabel :: Entity t -> Label t Entity
- Feldspar.Compiler.Imperative.Representation: elseBlock :: Program t -> Block t
- Feldspar.Compiler.Imperative.Representation: emptyLabel :: Program t -> Label t Empty
- Feldspar.Compiler.Imperative.Representation: exprLabel :: Expression t -> Label t Expression
- Feldspar.Compiler.Imperative.Representation: floatConstLabel :: Constant t -> Label t FloatConst
- Feldspar.Compiler.Imperative.Representation: funCallLabel :: Expression t -> Label t FunctionCall
- Feldspar.Compiler.Imperative.Representation: inParam :: ActualParameter t -> Expression t
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] (Eq (Label t Module), Eq (Label t Entity), Eq (Label t Struct), Eq (Label t ProcDef), Eq (Label t ProcDecl), Eq (Label t StructMember), Eq (Label t Block), Eq (Label t Program), Eq (Label t Empty), Eq (Label t Comment), Eq (Label t Assign), Eq (Label t ProcedureCall), Eq (Label t Spawn), Eq (Label t Run), Eq (Label t Sequence), Eq (Label t Branch), Eq (Label t SeqLoop), Eq (Label t ParLoop), Eq (Label t ActualParameter), Eq (Label t Declaration), Eq (Label t Expression), Eq (Label t FunctionCall), Eq (Label t Cast), Eq (Label t SizeOf), Eq (Label t StructField), Eq (Label t ArrayElem), Eq (Label t Constant), Eq (Label t IntConst), Eq (Label t FloatConst), Eq (Label t BoolConst), Eq (Label t ArrayConst), Eq (Label t ComplexConst), Eq (Label t Variable)) => EqLabel t
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] (Show (Label t Module), Show (Label t Entity), Show (Label t Struct), Show (Label t ProcDef), Show (Label t ProcDecl), Show (Label t StructMember), Show (Label t Block), Show (Label t Program), Show (Label t Empty), Show (Label t Comment), Show (Label t Assign), Show (Label t ProcedureCall), Show (Label t Spawn), Show (Label t Run), Show (Label t Sequence), Show (Label t Branch), Show (Label t SeqLoop), Show (Label t ParLoop), Show (Label t ActualParameter), Show (Label t Declaration), Show (Label t Expression), Show (Label t FunctionCall), Show (Label t Cast), Show (Label t SizeOf), Show (Label t ArrayElem), Show (Label t StructField), Show (Label t Constant), Show (Label t IntConst), Show (Label t FloatConst), Show (Label t BoolConst), Show (Label t ArrayConst), Show (Label t ComplexConst), Show (Label t Variable)) => ShowLabel t
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Annotation () s
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq Length
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq Place
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq TypeParameterMode
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq VariableRole
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (ActualParameter t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (Block t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (Constant t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (Declaration t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (Entity t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (Expression t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (Module t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (Program t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (StructMember t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] EqLabel t => Eq (Variable t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled ActualParameter
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled Block
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled Constant
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled Declaration
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled Entity
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled Expression
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled Module
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled Program
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled StructMember
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Labeled Variable
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show Length
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show Place
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show TypeParameterMode
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show VariableRole
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => HasType (ActualParameter t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => HasType (Constant t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => HasType (Expression t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (ActualParameter t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (Block t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (Constant t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (Declaration t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (Entity t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (Expression t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (Module t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (Program t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (StructMember t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] ShowLabel t => Show (Variable t)
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 ActualParameter
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 Block
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 Constant
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 Declaration
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 Entity
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 Expression
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 Module
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 Program
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 StructMember
- Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable1 Variable
- Feldspar.Compiler.Imperative.Representation: intConstLabel :: Constant t -> Label t IntConst
- Feldspar.Compiler.Imperative.Representation: label :: Labeled c => c t -> Label t c
- Feldspar.Compiler.Imperative.Representation: moduleLabel :: Module t -> Label t Module
- Feldspar.Compiler.Imperative.Representation: outParam :: ActualParameter t -> Expression t
- Feldspar.Compiler.Imperative.Representation: pLoopLabel :: Program t -> Label t ParLoop
- Feldspar.Compiler.Imperative.Representation: procCallLabel :: Program t -> Label t ProcedureCall
- Feldspar.Compiler.Imperative.Representation: procDeclLabel :: Entity t -> Label t ProcDecl
- Feldspar.Compiler.Imperative.Representation: procDefLabel :: Entity t -> Label t ProcDef
- Feldspar.Compiler.Imperative.Representation: programLabel :: Program t -> Label t Program
- Feldspar.Compiler.Imperative.Representation: sLoopLabel :: Program t -> Label t SeqLoop
- Feldspar.Compiler.Imperative.Representation: sequenceLabel :: Program t -> Label t Sequence
- Feldspar.Compiler.Imperative.Representation: setLabel :: Labeled c => c t -> Label t c -> c t
- Feldspar.Compiler.Imperative.Representation: sizeOfLabel :: Expression t -> Label t SizeOf
- Feldspar.Compiler.Imperative.Representation: structFieldLabel :: Expression t -> Label t StructField
- Feldspar.Compiler.Imperative.Representation: structLabel :: Entity t -> Label t Struct
- Feldspar.Compiler.Imperative.Representation: structMemberLabel :: StructMember t -> Label t StructMember
- Feldspar.Compiler.Imperative.Representation: thenBlock :: Program t -> Block t
- Feldspar.Compiler.Imperative.Representation: typeParamMode :: ActualParameter t -> TypeParameterMode
- Feldspar.Compiler.Imperative.Representation: var :: Expression t -> Variable t
- Feldspar.Compiler.Imperative.Representation: varLabel :: Variable t -> Label t Variable
- Feldspar.Compiler.Imperative.Representation: varRole :: Variable t -> VariableRole
- Feldspar.Compiler.Imperative.TransformationInstance: class (Transformation t, Convert (Label (From t) s) (Label (To t) s), Default (Label (To t) s)) => Conversion t s
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Conversion t StructMember, Default (Up t)) => DefaultTransformable t StructMember
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Conversion t Variable, Default (Up t)) => DefaultTransformable t Variable
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Constant, Transformable1 t [] Constant, Conversion t Constant, Conversion t IntConst, Conversion t FloatConst, Conversion t BoolConst, Conversion t ArrayConst, Conversion t ComplexConst, Default (Up t)) => DefaultTransformable t Constant
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Expression, Conversion t ActualParameter) => DefaultTransformable t ActualParameter
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Expression, Transformable t Variable, Transformable t Constant, Transformable1 t [] Expression, Conversion t Expression, Conversion t FunctionCall, Conversion t ArrayElem, Conversion t StructField, Conversion t SizeOf, Conversion t Cast, Default (Up t)) => DefaultTransformable t Expression
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Variable, Transformable1 t Maybe Expression, Conversion t Declaration) => DefaultTransformable t Declaration
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable1 t [] Declaration, Transformable t Program, Conversion t Block) => DefaultTransformable t Block
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable1 t [] Entity, Conversion t Module) => DefaultTransformable t Module
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable1 t [] Program, Transformable t Expression, Transformable1 t [] ActualParameter, Transformable t Block, Transformable t Variable, Conversion t Program, Conversion t Empty, Conversion t Comment, Conversion t Assign, Conversion t ProcedureCall, Conversion t Spawn, Conversion t Run, Conversion t Sequence, Conversion t Branch, Conversion t SeqLoop, Conversion t ParLoop, Default (Up t)) => DefaultTransformable t Program
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable1 t [] StructMember, Transformable1 t [] Variable, Transformable t Block, Transformable t Declaration, Conversion t Entity, Conversion t Struct, Conversion t ProcDef, Conversion t ProcDecl) => DefaultTransformable t Entity
- Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformation t, Convert (Label (From t) s) (Label (To t) s), Default (Label (To t) s)) => Conversion t s
- Feldspar.NameExtractor: OriginalFunctionSignature :: String -> [Maybe String] -> OriginalFunctionSignature
- Feldspar.NameExtractor: customizedParse :: FilePath -> FilePath -> ParseResult Module
- Feldspar.NameExtractor: data OriginalFunctionSignature
- Feldspar.NameExtractor: functionNameNeeded :: String -> Bool
- Feldspar.NameExtractor: getDeclarationList :: FilePath -> String -> [String]
- Feldspar.NameExtractor: getExtendedDeclarationList :: FilePath -> String -> [OriginalFunctionSignature]
- Feldspar.NameExtractor: getFullDeclarationListWithParameterList :: FilePath -> String -> [OriginalFunctionSignature]
- Feldspar.NameExtractor: getModuleName :: FilePath -> String -> String
- Feldspar.NameExtractor: getParameterList :: FilePath -> String -> IO [Maybe String]
- Feldspar.NameExtractor: getParameterListOld :: FilePath -> String -> String -> [Maybe String]
- Feldspar.NameExtractor: getParseOutput :: FilePath -> IO (ParseResult Module)
- Feldspar.NameExtractor: ignore :: OriginalFunctionSignature
- Feldspar.NameExtractor: instance Eq OriginalFunctionSignature
- Feldspar.NameExtractor: instance Show OriginalFunctionSignature
- Feldspar.NameExtractor: nameExtractorError :: ErrorClass -> String -> a
- Feldspar.NameExtractor: neutralName :: String
- Feldspar.NameExtractor: originalFunctionName :: OriginalFunctionSignature -> String
- Feldspar.NameExtractor: originalParameterNames :: OriginalFunctionSignature -> [Maybe String]
- Feldspar.NameExtractor: printDeclarationList :: FilePath -> IO (String -> [String])
- Feldspar.NameExtractor: printDeclarationListWithParameterList :: FilePath -> IO ()
- Feldspar.NameExtractor: printParameterListOfFunction :: FilePath -> String -> IO [Maybe String]
- Feldspar.NameExtractor: stripFunBind :: Decl -> OriginalFunctionSignature
- Feldspar.NameExtractor: stripModule :: Module -> [Decl]
- Feldspar.NameExtractor: stripModule2 :: Module -> ModuleName
- Feldspar.NameExtractor: stripModuleName :: ModuleName -> String
- Feldspar.NameExtractor: stripName :: Name -> String
- Feldspar.NameExtractor: stripPattern :: Pat -> Maybe String
- Feldspar.NameExtractor: stripUnnecessary :: [String] -> [String]
- Feldspar.NameExtractor: usedExtensions :: [Extension]
- Feldspar.NameExtractor: warning :: String -> a -> a
- Feldspar.Transformation.Framework: class Convert a b
- Feldspar.Transformation.Framework: convert :: Convert a b => a -> b
- Feldspar.Transformation.Framework: instance [overlap ok] Default b => Convert a b
+ Feldspar.Compiler: FeldOpts :: [Target] -> FeldOpts
+ Feldspar.Compiler: Options :: Platform -> UnrollStrategy -> DebugOption -> Bool -> Bool -> [Rule] -> FeldOpts -> Int -> Options
+ Feldspar.Compiler: RegionInf :: Target
+ Feldspar.Compiler: SICS :: Target
+ Feldspar.Compiler: c99OpenMpPlatformOptions :: Options
+ Feldspar.Compiler: compile :: SyntacticFeld t => t -> FilePath -> String -> Options -> IO ()
+ Feldspar.Compiler: data FeldOpts :: *
+ Feldspar.Compiler: data Options
+ Feldspar.Compiler: data Target :: *
+ Feldspar.Compiler: debug :: Options -> DebugOption
+ Feldspar.Compiler: frontendOpts :: Options -> FeldOpts
+ Feldspar.Compiler: getCore :: SyntacticFeld t => t -> Module ()
+ Feldspar.Compiler: icompile :: SyntacticFeld t => t -> IO ()
+ Feldspar.Compiler: icompile' :: SyntacticFeld t => Options -> String -> t -> IO ()
+ Feldspar.Compiler: icompileWith :: SyntacticFeld t => Options -> t -> IO ()
+ Feldspar.Compiler: memoryInfoVisible :: Options -> Bool
+ Feldspar.Compiler: nativeArrayRules :: [Rule]
+ Feldspar.Compiler: nestSize :: Options -> Int
+ Feldspar.Compiler: platform :: Options -> Platform
+ Feldspar.Compiler: printCore :: SyntacticFeld t => t -> IO ()
+ Feldspar.Compiler: printHeader :: Options -> Bool
+ Feldspar.Compiler: rules :: Options -> [Rule]
+ Feldspar.Compiler: targets :: FeldOpts -> [Target]
+ Feldspar.Compiler: unroll :: Options -> UnrollStrategy
+ Feldspar.Compiler.Backend.C.CodeGeneration: PEnv :: Options -> PrintEnv
+ Feldspar.Compiler.Backend.C.CodeGeneration: block :: PrintEnv -> Doc -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: blockComment :: [Doc] -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: call :: Doc -> [Doc] -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: cgen :: CodeGen a => PrintEnv -> a -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: cgenList :: CodeGen a => PrintEnv -> [a] -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: class CodeGen a
+ Feldspar.Compiler.Backend.C.CodeGeneration: compToCWithInfos :: Options -> Module () -> String
+ Feldspar.Compiler.Backend.C.CodeGeneration: data PrintEnv
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (ActualParameter ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Block ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Constant ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Declaration ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Entity ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Expression ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Module ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Pattern ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Program ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (StructMember ())
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen (Variable t)
+ Feldspar.Compiler.Backend.C.CodeGeneration: instance CodeGen Type
+ Feldspar.Compiler.Backend.C.CodeGeneration: options :: PrintEnv -> Options
+ Feldspar.Compiler.Backend.C.CodeGeneration: pvar :: PrintEnv -> Variable t -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: pvars :: PrintEnv -> [Variable t] -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: sizeInBrackets :: Type -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: stmt :: Doc -> Doc
+ Feldspar.Compiler.Backend.C.CodeGeneration: transformConst :: PrintEnv -> Constant () -> Maybe String
+ Feldspar.Compiler.Backend.C.Library: encodeFunctionName :: String -> String
+ Feldspar.Compiler.Backend.C.Library: makeDebugFileName :: String -> String
+ Feldspar.Compiler.Backend.C.Options: frontendOpts :: Options -> FeldOpts
+ Feldspar.Compiler.Backend.C.Options: instance Typeable Action
+ Feldspar.Compiler.Backend.C.Options: nestSize :: Options -> Int
+ Feldspar.Compiler.Backend.C.Options: printHeader :: Options -> Bool
+ Feldspar.Compiler.Backend.C.Options: varFloating :: Platform -> Bool
+ Feldspar.Compiler.Backend.C.Platforms: c99OpenMp :: Platform
+ Feldspar.Compiler.Backend.C.Platforms: nativeArrayRules :: [Rule]
+ Feldspar.Compiler.Backend.C.Plugin.Rule: instance (DefaultTransformable RulePlugin t, Typeable t) => Transformable RulePlugin t
+ Feldspar.Compiler.CallConv: buildCType :: Type -> Q Type
+ Feldspar.Compiler.CallConv: buildHaskellType :: Type -> Q Type
+ Feldspar.Compiler.CallConv: rewriteType :: Type -> Q Type
+ Feldspar.Compiler.Compiler: c99OpenMpPlatformOptions :: Options
+ Feldspar.Compiler.Frontend.Interactive.Interface: getCore :: SyntacticFeld t => t -> Module ()
+ Feldspar.Compiler.Frontend.Interactive.Interface: icompileWith :: SyntacticFeld t => Options -> t -> IO ()
+ Feldspar.Compiler.Frontend.Interactive.Interface: printCore :: SyntacticFeld t => t -> IO ()
+ Feldspar.Compiler.Imperative.FromCore: getCore' :: SyntacticFeld a => Options -> a -> Module ()
+ Feldspar.Compiler.Imperative.FromCore: instance Compile Empty dom
+ Feldspar.Compiler.Imperative.FromCore: instance Compile FeldDom FeldDom
+ Feldspar.Compiler.Imperative.FromCore.Array: instance (Compile dom dom, Project (CLambda Type) dom, Project (Literal :|| Type) dom, Project (Variable :|| Type) dom, Project Let dom, Project (Array :|| Type) dom, Project (Tuple :|| Type) dom, ConstrainedBy dom Typeable, AlphaEq dom dom (Decor Info dom) [(VarId, VarId)]) => Compile (Array :|| Type) dom
+ Feldspar.Compiler.Imperative.FromCore.Binding: compileBind :: Compile dom dom => (VarId, ASTB (Decor Info dom) Type) -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Binding: instance (Compile dom dom, Project (CLambda Type) dom) => Compile Let dom
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: backendOpts :: Readers -> Options
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: compileDecor :: Info a -> CodeWriter b -> CodeWriter b
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: confiscateBigBlock :: CodeWriter a -> CodeWriter ((a, Writers), Block ())
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: decl :: Writers -> [Declaration ()]
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: declareAlias :: Expression () -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: encodeType :: Type -> String
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: epilogue :: Writers -> [Program ()]
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: freshAlias :: Expression () -> CodeWriter (Expression ())
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: freshAliasInit :: Expression () -> CodeWriter (Expression ())
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: getTypes :: Options -> [Declaration ()] -> [Entity ()]
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: initialize :: Expression () -> Expression () -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: isComposite :: Type -> Bool
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkBranch :: Compile dom dom => Location -> ASTF (Decor Info dom) Bool -> ASTF (Decor Info dom) a -> Maybe (ASTF (Decor Info dom) a) -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkDoubleBufferState :: Expression () -> VarId -> CodeWriter (Expression (), Expression ())
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkNamedRef :: String -> Type -> VarId -> Variable ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkNamedVar :: String -> Type -> VarId -> Variable ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkPointer :: Type -> VarId -> Variable ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkRef :: Type -> VarId -> Expression ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkStructType :: [(String, Type)] -> Type
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: params :: Writers -> [Variable ()]
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: shallowAssign :: Location -> Expression () -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: shallowCopyReferences :: Expression () -> Expression () -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: shallowCopyWithRefSwap :: Expression () -> Expression () -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: tellDeclWith :: Bool -> [Declaration ()] -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Loop: instance (Compile dom dom, Project (CLambda Type) dom, Project (Literal :|| Type) dom, Project (Variable :|| Type) dom, Project Let dom, ConstrainedBy dom Typeable) => Compile (Loop :|| Type) dom
+ Feldspar.Compiler.Imperative.FromCore.MutableToPure: chaseBind :: (Project (MONAD Mut) dom, Project (CLambda Type) dom) => AST dom a -> AST dom a
+ Feldspar.Compiler.Imperative.FromCore.MutableToPure: instance (Compile dom dom, Project (CLambda Type) dom, Project (Variable :|| Type) dom, Project (MONAD Mut) dom, Project MutableArray dom) => Compile MutableToPure dom
+ Feldspar.Compiler.Imperative.FromCore.Primitive: instance Compile dom dom => Compile (REALFLOAT :|| Type) dom
+ Feldspar.Compiler.Imperative.FromCore.Switch: chaseTree :: (Compile dom dom, Project (Condition :|| Type) dom, Project (EQ :|| Type) dom) => Location -> ASTF (Decor Info dom) a -> ASTF (Decor Info dom) b -> CodeWriter [(Pattern (), Block ())]
+ Feldspar.Compiler.Imperative.FromCore.Switch: instance (Compile dom dom, Project (EQ :|| Type) dom, Project (Condition :|| Type) dom) => Compile (Switch :|| Type) dom
+ Feldspar.Compiler.Imperative.Frontend: binop :: Type -> String -> Expression () -> Expression () -> Expression ()
+ Feldspar.Compiler.Imperative.Frontend: call :: String -> [ActualParameter ()] -> Program ()
+ Feldspar.Compiler.Imperative.Frontend: chaseArray :: Expression t -> Maybe (Range Length)
+ Feldspar.Compiler.Imperative.Frontend: containsNativeArray :: Type -> Bool
+ Feldspar.Compiler.Imperative.Frontend: dVar :: Declaration () -> Variable ()
+ Feldspar.Compiler.Imperative.Frontend: flattenStructs :: Type -> [(Expression () -> Expression (), Type)]
+ Feldspar.Compiler.Imperative.Frontend: for :: Bool -> String -> Expression () -> Expression () -> Block () -> Program ()
+ Feldspar.Compiler.Imperative.Frontend: freeArrays :: [Declaration ()] -> [Program ()]
+ Feldspar.Compiler.Imperative.Frontend: freeIVars :: [Declaration ()] -> [Program ()]
+ Feldspar.Compiler.Imperative.Frontend: fun :: Type -> String -> [Expression ()] -> Expression ()
+ Feldspar.Compiler.Imperative.Frontend: fun' :: FunctionMode -> Type -> String -> [Expression ()] -> Expression ()
+ Feldspar.Compiler.Imperative.Frontend: hasReference :: Type -> Bool
+ Feldspar.Compiler.Imperative.Frontend: iVarDestroy :: Variable () -> Program ()
+ Feldspar.Compiler.Imperative.Frontend: isIVar :: Type -> Bool
+ Feldspar.Compiler.Imperative.Frontend: isNativeArray :: Type -> Bool
+ Feldspar.Compiler.Imperative.Frontend: isPointer :: Type -> Bool
+ Feldspar.Compiler.Imperative.Frontend: isVarExpr :: Expression () -> Bool
+ Feldspar.Compiler.Imperative.Frontend: litC :: Constant () -> Constant () -> Expression ()
+ Feldspar.Compiler.Imperative.Frontend: litD :: Double -> Expression t
+ Feldspar.Compiler.Imperative.Frontend: litF :: Float -> Expression t
+ Feldspar.Compiler.Imperative.Frontend: litI :: Type -> Integer -> Expression ()
+ Feldspar.Compiler.Imperative.Frontend: litI32 :: Integer -> Expression ()
+ Feldspar.Compiler.Imperative.Frontend: mkInitialize :: String -> Maybe (Expression ()) -> Expression () -> Program ()
+ Feldspar.Compiler.Imperative.Frontend: while :: Block () -> Expression () -> Block () -> Program ()
+ Feldspar.Compiler.Imperative.Representation: AddrOf :: Expression t -> Expression t
+ Feldspar.Compiler.Imperative.Representation: ArrayConst :: [Constant t] -> Constant t
+ Feldspar.Compiler.Imperative.Representation: DoubleConst :: Double -> Constant t
+ Feldspar.Compiler.Imperative.Representation: DoubleType :: Type
+ Feldspar.Compiler.Imperative.Representation: NativeArray :: (Maybe Length) -> Type -> Type
+ Feldspar.Compiler.Imperative.Representation: Pat :: (Expression t) -> Pattern t
+ Feldspar.Compiler.Imperative.Representation: PatDefault :: Pattern t
+ Feldspar.Compiler.Imperative.Representation: Proc :: String -> [Variable t] -> [Variable t] -> Maybe (Block t) -> Entity t
+ Feldspar.Compiler.Imperative.Representation: Switch :: Expression t -> [(Pattern t, Block t)] -> Program t
+ Feldspar.Compiler.Imperative.Representation: ValueDef :: Variable t -> Constant t -> Entity t
+ Feldspar.Compiler.Imperative.Representation: ValueParameter :: Expression t -> ActualParameter t
+ Feldspar.Compiler.Imperative.Representation: addrExpr :: Expression t -> Expression t
+ Feldspar.Compiler.Imperative.Representation: alts :: Program t -> [(Pattern t, Block t)]
+ Feldspar.Compiler.Imperative.Representation: arrayValues :: Constant t -> [Constant t]
+ Feldspar.Compiler.Imperative.Representation: data Pattern t
+ Feldspar.Compiler.Imperative.Representation: doubleValue :: Constant t -> Double
+ Feldspar.Compiler.Imperative.Representation: fv :: Expression t -> [Variable t]
+ Feldspar.Compiler.Imperative.Representation: fv' :: Expression t -> [Variable t]
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (ActualParameter t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Block t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Constant t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Declaration t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Entity t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Expression t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Module t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Pattern t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Program t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (StructMember t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Eq (Variable t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] HasType (ActualParameter t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] HasType (Constant t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] HasType (Expression t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Monoid (Block t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Monoid (Program t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (ActualParameter t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Block t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Constant t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Declaration t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Entity t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Expression t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Module t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Pattern t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Program t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (StructMember t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Show (Variable t)
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable ActualParameter
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Block
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Constant
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Declaration
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Entity
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Expression
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Function
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Module
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Pattern
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Program
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable StructMember
+ Feldspar.Compiler.Imperative.Representation: instance [overlap ok] Typeable Variable
+ Feldspar.Compiler.Imperative.Representation: pParallel :: Program t -> Bool
+ Feldspar.Compiler.Imperative.Representation: scrutinee :: Program t -> Expression t
+ Feldspar.Compiler.Imperative.Representation: valValue :: Entity t -> Constant t
+ Feldspar.Compiler.Imperative.Representation: valVar :: Entity t -> Variable t
+ Feldspar.Compiler.Imperative.Representation: valueParam :: ActualParameter t -> Expression t
+ Feldspar.Compiler.Imperative.Representation: varExpr :: Expression t -> Variable t
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Constant, Transformable t Expression, Transformable1 t [] ActualParameter, Transformable t Block, Transformable t Variable, Combine (Up t), Default (Up t)) => DefaultTransformable t Pattern
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Constant, Transformable1 t [] Constant, Combine (Up t), Default (Up t)) => DefaultTransformable t Constant
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Expression, Default (Up t)) => DefaultTransformable t ActualParameter
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Expression, Transformable t Variable, Transformable t Constant, Transformable1 t [] Expression, Combine (Up t), Default (Up t)) => DefaultTransformable t Expression
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable t Variable, Transformable1 t Maybe Expression, Combine (Up t)) => DefaultTransformable t Declaration
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable1 t [] Declaration, Transformable t Program, Combine (Up t)) => DefaultTransformable t Block
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable1 t [] Program, Transformable t Expression, Transformable1 t [] ActualParameter, Transformable t Block, Transformable t Variable, Combine (Up t), Default (Up t), Transformation t) => DefaultTransformable t Program
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] (Transformable1 t [] StructMember, Transformable1 t [] Variable, Transformable t Block, Transformable t Declaration, Transformable t Constant, Combine (Up t), Default (Up t), Transformation t) => DefaultTransformable t Entity
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] Default (Up t) => DefaultTransformable t StructMember
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] Default (Up t) => DefaultTransformable t Variable
+ Feldspar.Compiler.Imperative.TransformationInstance: instance [overlap ok] Transformable1 t [] Entity => DefaultTransformable t Module
+ Feldspar.Compiler.Internal: c99OpenMpPlatformOptions :: Options
+ Feldspar.Compiler.Internal: c99PlatformOptions :: Options
+ Feldspar.Compiler.Internal: defaultOptions :: Options
+ Feldspar.Compiler.Internal: nativeArrayRules :: [Rule]
+ Feldspar.Compiler.Internal: noMemoryInformation :: Options
+ Feldspar.Compiler.Internal: noPrimitiveInstructionHandling :: Options
+ Feldspar.Compiler.Internal: tic64xPlatformOptions :: Options
+ Feldspar.Compiler.Internal: unrollOptions :: Options
+ Feldspar.Compiler.Marshal: SA :: Ptr a -> Int32 -> Int32 -> Word32 -> SA a
+ Feldspar.Compiler.Marshal: buf :: SA a -> Ptr a
+ Feldspar.Compiler.Marshal: bytes :: SA a -> Word32
+ Feldspar.Compiler.Marshal: data SA a
+ Feldspar.Compiler.Marshal: elems :: SA a -> Int32
+ Feldspar.Compiler.Marshal: esize :: SA a -> Int32
+ Feldspar.Compiler.Marshal: instance (Marshal a, Marshal b) => Marshal (a, b)
+ Feldspar.Compiler.Marshal: instance (Marshal a, Marshal b, Marshal c) => Marshal (a, b, c)
+ Feldspar.Compiler.Marshal: instance (Marshal a, Marshal b, Marshal c, Marshal d) => Marshal (a, b, c, d)
+ Feldspar.Compiler.Marshal: instance (Marshal a, Marshal b, Marshal c, Marshal d, Marshal e) => Marshal (a, b, c, d, e)
+ Feldspar.Compiler.Marshal: instance (Marshal a, Marshal b, Marshal c, Marshal d, Marshal e, Marshal f) => Marshal (a, b, c, d, e, f)
+ Feldspar.Compiler.Marshal: instance (Marshal a, Marshal b, Marshal c, Marshal d, Marshal e, Marshal f, Marshal g) => Marshal (a, b, c, d, e, f, g)
+ Feldspar.Compiler.Marshal: instance (RealFloat a, Storable a) => Storable (Complex a)
+ Feldspar.Compiler.Marshal: instance (Storable (Rep a), Marshal a) => Marshal [a]
+ Feldspar.Compiler.Marshal: instance Default (Ptr a)
+ Feldspar.Compiler.Marshal: instance Default (SA a)
+ Feldspar.Compiler.Marshal: instance Eq (SA a)
+ Feldspar.Compiler.Marshal: instance Marshal (Complex a)
+ Feldspar.Compiler.Marshal: instance Marshal IntN
+ Feldspar.Compiler.Marshal: instance Marshal WordN
+ Feldspar.Compiler.Marshal: instance Reference (Complex a)
+ Feldspar.Compiler.Marshal: instance Reference (Ptr a)
+ Feldspar.Compiler.Marshal: instance Reference IntN
+ Feldspar.Compiler.Marshal: instance Reference WordN
+ Feldspar.Compiler.Marshal: instance Show (SA a)
+ Feldspar.Compiler.Marshal: instance Storable (a, b) => Reference (a, b)
+ Feldspar.Compiler.Marshal: instance Storable (a, b, c) => Reference (a, b, c)
+ Feldspar.Compiler.Marshal: instance Storable (a, b, c, d) => Reference (a, b, c, d)
+ Feldspar.Compiler.Marshal: instance Storable (a, b, c, d, e) => Reference (a, b, c, d, e)
+ Feldspar.Compiler.Marshal: instance Storable (a, b, c, d, e, f) => Reference (a, b, c, d, e, f)
+ Feldspar.Compiler.Marshal: instance Storable (a, b, c, d, e, f, g) => Reference (a, b, c, d, e, f, g)
+ Feldspar.Compiler.Marshal: instance Storable a => Reference (SA a)
+ Feldspar.Compiler.Marshal: instance Storable a => Storable (SA a)
+ Feldspar.Compiler.Plugin: defaultConfig :: Config
+ Feldspar.Compiler.Plugin: loadFun :: [Name] -> Q [Dec]
+ Feldspar.Compiler.Plugin: loadFunOpts :: [String] -> [Name] -> Q [Dec]
+ Feldspar.Compiler.Plugin: loadFunWithConfig :: Config -> [Name] -> Q [Dec]
+ Feldspar.Compiler.Plugin: pack :: (Reference (Rep a), Marshal a) => a -> IO (Ref (Rep a))
+ Feldspar.Compiler.Plugin: unpack :: (Reference (Rep a), Marshal a) => Ref (Rep a) -> IO a
+ Feldspar.Runtime: feldspar_compiler_hook :: Int
- Feldspar.Compiler.Backend.C.Options: Options :: Platform -> UnrollStrategy -> DebugOption -> Bool -> [Rule] -> Options
+ Feldspar.Compiler.Backend.C.Options: Options :: Platform -> UnrollStrategy -> DebugOption -> Bool -> Bool -> [Rule] -> FeldOpts -> Int -> Options
- Feldspar.Compiler.Backend.C.Options: Platform :: String -> [(Type, String, String)] -> [(Type, ShowValue)] -> [String] -> [Rule] -> IsRestrict -> Platform
+ Feldspar.Compiler.Backend.C.Options: Platform :: String -> [(Type, String)] -> [(Type, ShowValue)] -> [String] -> [Rule] -> Bool -> IsRestrict -> Platform
- Feldspar.Compiler.Backend.C.Options: propagate :: (Interface t, Typeable (Repr t)) => (t -> [Action (Repr t)]) -> Action t'
+ Feldspar.Compiler.Backend.C.Options: propagate :: Typeable t => (t -> [Action t]) -> Action t'
- Feldspar.Compiler.Backend.C.Options: replaceWith :: Interface t => t -> Action (Repr t)
+ Feldspar.Compiler.Backend.C.Options: replaceWith :: t -> Action t
- Feldspar.Compiler.Backend.C.Options: rule :: (Interface t, Typeable (Repr t)) => (t -> [Action (Repr t)]) -> Rule
+ Feldspar.Compiler.Backend.C.Options: rule :: Typeable t => (t -> [Action t]) -> Rule
- Feldspar.Compiler.Backend.C.Options: types :: Platform -> [(Type, String, String)]
+ Feldspar.Compiler.Backend.C.Options: types :: Platform -> [(Type, String)]
- Feldspar.Compiler.Compiler: CompToCCoreResult :: String -> Position -> Module DebugToCSemanticInfo -> CompToCCoreResult
+ Feldspar.Compiler.Compiler: CompToCCoreResult :: String -> Module t -> CompToCCoreResult t
- Feldspar.Compiler.Compiler: ExternalInfoCollection :: ExternalInfo Precompilation -> ExternalInfo UnrollPlugin -> ExternalInfo RulePlugin -> ExternalInfo RulePlugin -> ExternalInfo TypeDefinitionGenerator -> ExternalInfo VariableRoleAssigner -> ExternalInfo TypeCorrector -> ExternalInfoCollection
+ Feldspar.Compiler.Compiler: ExternalInfoCollection :: ExternalInfo RulePlugin -> ExternalInfo RulePlugin -> ExternalInfoCollection
- Feldspar.Compiler.Compiler: SplitCompToCCoreResult :: CompToCCoreResult -> CompToCCoreResult -> SplitCompToCCoreResult
+ Feldspar.Compiler.Compiler: SplitCompToCCoreResult :: CompToCCoreResult () -> CompToCCoreResult () -> SplitCompToCCoreResult
- Feldspar.Compiler.Compiler: compileToCCore :: Compilable t internal => CompilationMode -> t -> Maybe String -> IncludesNeeded -> OriginalFunctionSignature -> Options -> SplitCompToCCoreResult
+ Feldspar.Compiler.Compiler: compileToCCore :: SyntacticFeld c => String -> Options -> c -> SplitCompToCCoreResult
- Feldspar.Compiler.Compiler: data CompToCCoreResult
+ Feldspar.Compiler.Compiler: data CompToCCoreResult t
- Feldspar.Compiler.Compiler: debugModule :: CompToCCoreResult -> Module DebugToCSemanticInfo
+ Feldspar.Compiler.Compiler: debugModule :: CompToCCoreResult t -> Module t
- Feldspar.Compiler.Compiler: executePluginChain :: Compilable c internal => CompilationMode -> c -> OriginalFunctionSignature -> Options -> SplitModuleDescriptor
+ Feldspar.Compiler.Compiler: executePluginChain :: SyntacticFeld c => String -> Options -> c -> Module ()
- Feldspar.Compiler.Compiler: genIncludeLines :: Options -> Maybe String -> (String, Int)
+ Feldspar.Compiler.Compiler: genIncludeLines :: Options -> Maybe String -> String
- Feldspar.Compiler.Compiler: moduleToCCore :: IncludesNeeded -> Options -> Module () -> CompToCCoreResult
+ Feldspar.Compiler.Compiler: moduleToCCore :: Options -> Module () -> CompToCCoreResult ()
- Feldspar.Compiler.Compiler: sctccrHeader :: SplitCompToCCoreResult -> CompToCCoreResult
+ Feldspar.Compiler.Compiler: sctccrHeader :: SplitCompToCCoreResult -> CompToCCoreResult ()
- Feldspar.Compiler.Compiler: sctccrSource :: SplitCompToCCoreResult -> CompToCCoreResult
+ Feldspar.Compiler.Compiler: sctccrSource :: SplitCompToCCoreResult -> CompToCCoreResult ()
- Feldspar.Compiler.Compiler: sourceCode :: CompToCCoreResult -> String
+ Feldspar.Compiler.Compiler: sourceCode :: CompToCCoreResult t -> String
- Feldspar.Compiler.Frontend.Interactive.Interface: compile :: Compilable t internal => t -> FilePath -> String -> Options -> IO ()
+ Feldspar.Compiler.Frontend.Interactive.Interface: compile :: SyntacticFeld t => t -> FilePath -> String -> Options -> IO ()
- Feldspar.Compiler.Frontend.Interactive.Interface: icompile :: Compilable t internal => t -> IO ()
+ Feldspar.Compiler.Frontend.Interactive.Interface: icompile :: SyntacticFeld t => t -> IO ()
- Feldspar.Compiler.Frontend.Interactive.Interface: icompile' :: Compilable t internal => t -> String -> Options -> IO ()
+ Feldspar.Compiler.Frontend.Interactive.Interface: icompile' :: SyntacticFeld t => Options -> String -> t -> IO ()
- Feldspar.Compiler.Imperative.FromCore: compileProgTop :: (Compile dom dom, Project (CLambda Type) dom) => String -> [Var] -> ASTF (Decor Info dom) a -> Mod
+ Feldspar.Compiler.Imperative.FromCore: compileProgTop :: (Compile dom dom, Project (CLambda Type) dom, Project Let dom, Project (Literal :|| Type) dom, ConstrainedBy dom Typeable) => Options -> String -> [(VarId, ASTB (Decor Info dom) Type)] -> ASTF (Decor Info dom) a -> CodeWriter (Variable ())
- Feldspar.Compiler.Imperative.FromCore: fromCore :: SyntacticFeld a => String -> a -> Module ()
+ Feldspar.Compiler.Imperative.FromCore: fromCore :: SyntacticFeld a => Options -> String -> a -> Module ()
- Feldspar.Compiler.Imperative.FromCore.Binding: compileLet :: Compile dom dom => ASTF (Decor Info dom) a -> Info (a -> b) -> VarId -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Binding: compileLet :: Compile dom dom => ASTF (Decor Info dom) a -> Info (a -> b) -> VarId -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: Readers :: [(VarId, Expr)] -> SourceInfo -> Readers
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: Readers :: [(VarId, Expression ())] -> SourceInfo -> Options -> Readers
- Feldspar.Compiler.Imperative.FromCore.Interpretation: States :: Integer -> States
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: States :: VarId -> States
- Feldspar.Compiler.Imperative.FromCore.Interpretation: Writers :: Block -> [Ent] -> Writers
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: Writers :: Block () -> [Entity ()] -> [Declaration ()] -> [Variable ()] -> [Program ()] -> Writers
- Feldspar.Compiler.Imperative.FromCore.Interpretation: alias :: Readers -> [(VarId, Expr)]
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: alias :: Readers -> [(VarId, Expression ())]
- Feldspar.Compiler.Imperative.FromCore.Interpretation: assign :: Location -> Expr -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: assign :: Location -> Expression () -> CodeWriter ()
- Feldspar.Compiler.Imperative.FromCore.Interpretation: block :: Writers -> Block
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: block :: Writers -> Block ()
- Feldspar.Compiler.Imperative.FromCore.Interpretation: compileExpr :: Compile dom dom => ASTF (Decor Info dom) a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: compileExpr :: Compile dom dom => ASTF (Decor Info dom) a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: compileExprDecor :: Compile dom dom => Decor Info dom a -> Args (AST (Decor Info dom)) a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: compileExprDecor :: Compile dom dom => Decor Info dom a -> Args (AST (Decor Info dom)) a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: compileExprSym :: Compile sub dom => sub a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: compileExprSym :: Compile sub dom => sub a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: compileExprVar :: Compile dom dom => ASTF (Decor Info dom) a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: compileExprVar :: Compile dom dom => ASTF (Decor Info dom) a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: compileProgFresh :: Compile sub dom => sub a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: compileProgFresh :: Compile sub dom => sub a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: confiscateBlock :: CodeWriter a -> CodeWriter (a, Block)
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: confiscateBlock :: CodeWriter a -> CodeWriter (a, Block ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: declare :: Expr -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: declare :: Expression () -> CodeWriter ()
- Feldspar.Compiler.Imperative.FromCore.Interpretation: def :: Writers -> [Ent]
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: def :: Writers -> [Entity ()]
- Feldspar.Compiler.Imperative.FromCore.Interpretation: fresh :: States -> Integer
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: fresh :: States -> VarId
- Feldspar.Compiler.Imperative.FromCore.Interpretation: freshId :: CodeWriter Integer
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: freshId :: CodeWriter VarId
- Feldspar.Compiler.Imperative.FromCore.Interpretation: freshVar :: String -> TypeRep a -> Size a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: freshVar :: String -> TypeRep a -> Size a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: initReader :: Readers
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: initReader :: Options -> Readers
- Feldspar.Compiler.Imperative.FromCore.Interpretation: mkLength :: (Project (Literal :|| Type) dom, Project (Variable :|| Type) dom, Compile dom dom) => ASTF (Decor Info dom) a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkLength :: (Project (Literal :|| Type) dom, Project (Variable :|| Type) dom, Compile dom dom) => ASTF (Decor Info dom) a -> TypeRep a -> Size a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: mkVar :: Type -> VarId -> Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkVar :: Type -> VarId -> Expression ()
- Feldspar.Compiler.Imperative.FromCore.Interpretation: mkVariable :: Type -> VarId -> Var
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: mkVariable :: Type -> VarId -> Variable ()
- Feldspar.Compiler.Imperative.FromCore.Interpretation: tellDef :: [Ent] -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: tellDef :: [Entity ()] -> CodeWriter ()
- Feldspar.Compiler.Imperative.FromCore.Interpretation: tellProg :: [Prog] -> CodeWriter ()
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: tellProg :: [Program ()] -> CodeWriter ()
- Feldspar.Compiler.Imperative.FromCore.Interpretation: type Location = Expr
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: type Location = Maybe (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Interpretation: withAlias :: VarId -> Expr -> CodeWriter a -> CodeWriter a
+ Feldspar.Compiler.Imperative.FromCore.Interpretation: withAlias :: VarId -> Expression () -> CodeWriter a -> CodeWriter a
- Feldspar.Compiler.Imperative.FromCore.Literal: literal :: TypeRep a -> Size a -> a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Literal: literal :: TypeRep a -> Size a -> a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.FromCore.Primitive: compilePrim :: (Semantic expr, Compile dom dom) => (expr :|| Type) a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a -> CodeWriter Expr
+ Feldspar.Compiler.Imperative.FromCore.Primitive: compilePrim :: (Semantic expr, Compile dom dom) => (expr :|| Type) a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a -> CodeWriter (Expression ())
- Feldspar.Compiler.Imperative.Frontend: arrayLength :: Expr -> Expr
+ Feldspar.Compiler.Imperative.Frontend: arrayLength :: Expression () -> Expression ()
- Feldspar.Compiler.Imperative.Frontend: copyProg :: Expr -> Expr -> Prog
+ Feldspar.Compiler.Imperative.Frontend: copyProg :: Maybe (Expression ()) -> [Expression ()] -> Program ()
- Feldspar.Compiler.Imperative.Frontend: freeArray :: Var -> Prog
+ Feldspar.Compiler.Imperative.Frontend: freeArray :: Variable () -> Program ()
- Feldspar.Compiler.Imperative.Frontend: iVarGet :: Expr -> Expr -> Prog
+ Feldspar.Compiler.Imperative.Frontend: iVarGet :: Expression () -> Expression () -> Program ()
- Feldspar.Compiler.Imperative.Frontend: iVarInit :: Expr -> Prog
+ Feldspar.Compiler.Imperative.Frontend: iVarInit :: Expression () -> Program ()
- Feldspar.Compiler.Imperative.Frontend: iVarPut :: Expr -> Expr -> Prog
+ Feldspar.Compiler.Imperative.Frontend: iVarPut :: Expression () -> Expression () -> Program ()
- Feldspar.Compiler.Imperative.Frontend: initArray :: Expr -> Expr -> Prog
+ Feldspar.Compiler.Imperative.Frontend: initArray :: Maybe (Expression ()) -> Expression () -> Program ()
- Feldspar.Compiler.Imperative.Frontend: lName :: Expr -> String
+ Feldspar.Compiler.Imperative.Frontend: lName :: Expression t -> String
- Feldspar.Compiler.Imperative.Frontend: litB :: Bool -> Expr
+ Feldspar.Compiler.Imperative.Frontend: litB :: Bool -> Expression ()
- Feldspar.Compiler.Imperative.Frontend: run :: String -> [Var] -> Prog
+ Feldspar.Compiler.Imperative.Frontend: run :: String -> [Variable ()] -> Program ()
- Feldspar.Compiler.Imperative.Frontend: setLength :: Expr -> Expr -> Prog
+ Feldspar.Compiler.Imperative.Frontend: setLength :: Maybe (Expression ()) -> Expression () -> Program ()
- Feldspar.Compiler.Imperative.Frontend: spawn :: String -> [Var] -> Prog
+ Feldspar.Compiler.Imperative.Frontend: spawn :: String -> [Variable ()] -> Program ()
- Feldspar.Compiler.Imperative.Frontend: toBlock :: Prog -> Block ()
+ Feldspar.Compiler.Imperative.Frontend: toBlock :: Program () -> Block ()
- Feldspar.Compiler.Imperative.Frontend: toProg :: Block () -> Prog
+ Feldspar.Compiler.Imperative.Frontend: toProg :: Block () -> Program ()
- Feldspar.Compiler.Imperative.Frontend: vName :: Var -> String
+ Feldspar.Compiler.Imperative.Frontend: vName :: Variable t -> String
- Feldspar.Compiler.Imperative.Frontend: varToExpr :: Var -> Expr
+ Feldspar.Compiler.Imperative.Frontend: varToExpr :: Variable t -> Expression t
- Feldspar.Compiler.Imperative.Representation: ArrayElem :: Expression t -> Expression t -> Label t ArrayElem -> Label t Expression -> Expression t
+ Feldspar.Compiler.Imperative.Representation: ArrayElem :: Expression t -> Expression t -> Expression t
- Feldspar.Compiler.Imperative.Representation: ArrayType :: Length -> Type -> Type
+ Feldspar.Compiler.Imperative.Representation: ArrayType :: (Range Length) -> Type -> Type
- Feldspar.Compiler.Imperative.Representation: Assign :: Expression t -> Expression t -> Label t Assign -> Label t Program -> Program t
+ Feldspar.Compiler.Imperative.Representation: Assign :: Expression t -> Expression t -> Program t
- Feldspar.Compiler.Imperative.Representation: Block :: [Declaration t] -> Program t -> Label t Block -> Block t
+ Feldspar.Compiler.Imperative.Representation: Block :: [Declaration t] -> Program t -> Block t
- Feldspar.Compiler.Imperative.Representation: BlockProgram :: Block t -> Label t Program -> Program t
+ Feldspar.Compiler.Imperative.Representation: BlockProgram :: Block t -> Program t
- Feldspar.Compiler.Imperative.Representation: BoolConst :: Bool -> Label t BoolConst -> Label t Constant -> Constant t
+ Feldspar.Compiler.Imperative.Representation: BoolConst :: Bool -> Constant t
- Feldspar.Compiler.Imperative.Representation: Cast :: Type -> Expression t -> Label t Cast -> Label t Expression -> Expression t
+ Feldspar.Compiler.Imperative.Representation: Cast :: Type -> Expression t -> Expression t
- Feldspar.Compiler.Imperative.Representation: Comment :: Bool -> String -> Label t Comment -> Label t Program -> Program t
+ Feldspar.Compiler.Imperative.Representation: Comment :: Bool -> String -> Program t
- Feldspar.Compiler.Imperative.Representation: ComplexConst :: Constant t -> Constant t -> Label t ComplexConst -> Label t Constant -> Constant t
+ Feldspar.Compiler.Imperative.Representation: ComplexConst :: Constant t -> Constant t -> Constant t
- Feldspar.Compiler.Imperative.Representation: ConstExpr :: Constant t -> Label t Expression -> Expression t
+ Feldspar.Compiler.Imperative.Representation: ConstExpr :: Constant t -> Expression t
- Feldspar.Compiler.Imperative.Representation: Declaration :: Variable t -> Maybe (Expression t) -> Label t Declaration -> Declaration t
+ Feldspar.Compiler.Imperative.Representation: Declaration :: Variable t -> Maybe (Expression t) -> Declaration t
- Feldspar.Compiler.Imperative.Representation: Empty :: Label t Empty -> Label t Program -> Program t
+ Feldspar.Compiler.Imperative.Representation: Empty :: Program t
- Feldspar.Compiler.Imperative.Representation: FloatConst :: Double -> Label t FloatConst -> Label t Constant -> Constant t
+ Feldspar.Compiler.Imperative.Representation: FloatConst :: Float -> Constant t
- Feldspar.Compiler.Imperative.Representation: FunParameter :: String -> Bool -> Label t ActualParameter -> ActualParameter t
+ Feldspar.Compiler.Imperative.Representation: FunParameter :: String -> ActualParameter t
- Feldspar.Compiler.Imperative.Representation: FunctionCall :: Function -> [Expression t] -> Label t FunctionCall -> Label t Expression -> Expression t
+ Feldspar.Compiler.Imperative.Representation: FunctionCall :: Function -> [Expression t] -> Expression t
- Feldspar.Compiler.Imperative.Representation: IntConst :: Integer -> Type -> Label t IntConst -> Label t Constant -> Constant t
+ Feldspar.Compiler.Imperative.Representation: IntConst :: Integer -> Type -> Constant t
- Feldspar.Compiler.Imperative.Representation: Module :: [Entity t] -> Label t Module -> Module t
+ Feldspar.Compiler.Imperative.Representation: Module :: [Entity t] -> Module t
- Feldspar.Compiler.Imperative.Representation: ParLoop :: Variable t -> Expression t -> Int -> Block t -> Label t ParLoop -> Label t Program -> Program t
+ Feldspar.Compiler.Imperative.Representation: ParLoop :: Bool -> Variable t -> Expression t -> Expression t -> Block t -> Program t
- Feldspar.Compiler.Imperative.Representation: Pointer :: VariableRole
+ Feldspar.Compiler.Imperative.Representation: Pointer :: Type -> Type
- Feldspar.Compiler.Imperative.Representation: ProcedureCall :: String -> [ActualParameter t] -> Label t ProcedureCall -> Label t Program -> Program t
+ Feldspar.Compiler.Imperative.Representation: ProcedureCall :: String -> [ActualParameter t] -> Program t
- Feldspar.Compiler.Imperative.Representation: SeqLoop :: Expression t -> Block t -> Block t -> Label t SeqLoop -> Label t Program -> Program t
+ Feldspar.Compiler.Imperative.Representation: SeqLoop :: Expression t -> Block t -> Block t -> Program t
- Feldspar.Compiler.Imperative.Representation: Sequence :: [Program t] -> Label t Sequence -> Label t Program -> Program t
+ Feldspar.Compiler.Imperative.Representation: Sequence :: [Program t] -> Program t
- Feldspar.Compiler.Imperative.Representation: SizeOf :: Either Type (Expression t) -> Label t SizeOf -> Label t Expression -> Expression t
+ Feldspar.Compiler.Imperative.Representation: SizeOf :: Type -> Expression t
- Feldspar.Compiler.Imperative.Representation: StructDef :: String -> [StructMember t] -> Label t Struct -> Label t Entity -> Entity t
+ Feldspar.Compiler.Imperative.Representation: StructDef :: String -> [StructMember t] -> Entity t
- Feldspar.Compiler.Imperative.Representation: StructField :: Expression t -> String -> Label t StructField -> Label t Expression -> Expression t
+ Feldspar.Compiler.Imperative.Representation: StructField :: Expression t -> String -> Expression t
- Feldspar.Compiler.Imperative.Representation: StructMember :: String -> Type -> Label t StructMember -> StructMember t
+ Feldspar.Compiler.Imperative.Representation: StructMember :: String -> Type -> StructMember t
- Feldspar.Compiler.Imperative.Representation: StructType :: [(String, Type)] -> Type
+ Feldspar.Compiler.Imperative.Representation: StructType :: String -> [(String, Type)] -> Type
- Feldspar.Compiler.Imperative.Representation: TypeDef :: Type -> String -> Label t Entity -> Entity t
+ Feldspar.Compiler.Imperative.Representation: TypeDef :: Type -> String -> Entity t
- Feldspar.Compiler.Imperative.Representation: TypeParameter :: Type -> TypeParameterMode -> Label t ActualParameter -> ActualParameter t
+ Feldspar.Compiler.Imperative.Representation: TypeParameter :: Type -> ActualParameter t
- Feldspar.Compiler.Imperative.Representation: VarExpr :: Variable t -> Label t Expression -> Expression t
+ Feldspar.Compiler.Imperative.Representation: VarExpr :: Variable t -> Expression t
- Feldspar.Compiler.Imperative.Representation: Variable :: String -> Type -> VariableRole -> Label t Variable -> Variable t
+ Feldspar.Compiler.Imperative.Representation: Variable :: Type -> String -> Variable t
- Feldspar.Compiler.Imperative.Representation: floatValue :: Constant t -> Double
+ Feldspar.Compiler.Imperative.Representation: floatValue :: Constant t -> Float
- Feldspar.Compiler.Imperative.Representation: pLoopStep :: Program t -> Int
+ Feldspar.Compiler.Imperative.Representation: pLoopStep :: Program t -> Expression t
- Feldspar.Compiler.Imperative.Representation: procBody :: Entity t -> Block t
+ Feldspar.Compiler.Imperative.Representation: procBody :: Entity t -> Maybe (Block t)
- Feldspar.Compiler.Imperative.Representation: sizeOf :: Expression t -> Either Type (Expression t)
+ Feldspar.Compiler.Imperative.Representation: sizeOf :: Expression t -> Type
Files
- LICENSE +4/−2
- benchs/CRC.hs +55/−0
- feldspar-compiler.cabal +114/−88
- lib/Feldspar/C/feldspar_array.c +0/−61
- lib/Feldspar/C/feldspar_array.h +51/−63
- lib/Feldspar/C/feldspar_c99.c +346/−278
- lib/Feldspar/C/feldspar_c99.h +246/−236
- lib/Feldspar/C/ivar.c +4/−1
- lib/Feldspar/C/ivar.h +2/−0
- lib/Feldspar/C/taskpool.c +4/−1
- lib/Feldspar/C/taskpool.h +10/−8
- lib/Feldspar/Compiler.hs +14/−33
- lib/Feldspar/Compiler/Backend/C/CodeGeneration.hs +214/−92
- lib/Feldspar/Compiler/Backend/C/Library.hs +9/−39
- lib/Feldspar/Compiler/Backend/C/Options.hs +15/−11
- lib/Feldspar/Compiler/Backend/C/Platforms.hs +270/−171
- lib/Feldspar/Compiler/Backend/C/Plugin/BlockProgramHandler.hs +0/−78
- lib/Feldspar/Compiler/Backend/C/Plugin/Locator.hs +0/−232
- lib/Feldspar/Compiler/Backend/C/Plugin/PrettyPrint.hs +0/−714
- lib/Feldspar/Compiler/Backend/C/Plugin/Rule.hs +8/−1
- lib/Feldspar/Compiler/Backend/C/Plugin/TypeCorrector.hs +0/−199
- lib/Feldspar/Compiler/Backend/C/Plugin/TypeDefinitionGenerator.hs +0/−87
- lib/Feldspar/Compiler/Backend/C/Plugin/VariableRoleAssigner.hs +0/−76
- lib/Feldspar/Compiler/CallConv.hs +65/−0
- lib/Feldspar/Compiler/Compiler.hs +74/−152
- lib/Feldspar/Compiler/Frontend/Interactive/Interface.hs +31/−38
- lib/Feldspar/Compiler/Imperative/FromCore.hs +86/−50
- lib/Feldspar/Compiler/Imperative/FromCore/Array.hs +112/−33
- lib/Feldspar/Compiler/Imperative/FromCore/Binding.hs +20/−8
- lib/Feldspar/Compiler/Imperative/FromCore/Condition.hs +2/−6
- lib/Feldspar/Compiler/Imperative/FromCore/ConditionM.hs +2/−6
- lib/Feldspar/Compiler/Imperative/FromCore/Error.hs +5/−3
- lib/Feldspar/Compiler/Imperative/FromCore/FFI.hs +2/−2
- lib/Feldspar/Compiler/Imperative/FromCore/Future.hs +27/−21
- lib/Feldspar/Compiler/Imperative/FromCore/Interpretation.hs +276/−106
- lib/Feldspar/Compiler/Imperative/FromCore/Literal.hs +61/−79
- lib/Feldspar/Compiler/Imperative/FromCore/Loop.hs +41/−24
- lib/Feldspar/Compiler/Imperative/FromCore/Mutable.hs +34/−28
- lib/Feldspar/Compiler/Imperative/FromCore/MutableToPure.hs +40/−5
- lib/Feldspar/Compiler/Imperative/FromCore/NoInline.hs +17/−15
- lib/Feldspar/Compiler/Imperative/FromCore/Par.hs +29/−25
- lib/Feldspar/Compiler/Imperative/FromCore/Primitive.hs +6/−3
- lib/Feldspar/Compiler/Imperative/FromCore/SourceInfo.hs +4/−4
- lib/Feldspar/Compiler/Imperative/FromCore/Switch.hs +59/−0
- lib/Feldspar/Compiler/Imperative/FromCore/Tuple.hs +36/−35
- lib/Feldspar/Compiler/Imperative/Frontend.hs +170/−397
- lib/Feldspar/Compiler/Imperative/Plugin/CollectFreeVars.hs +0/−82
- lib/Feldspar/Compiler/Imperative/Plugin/ConstantFolding.hs +0/−69
- lib/Feldspar/Compiler/Imperative/Plugin/Free.hs +0/−61
- lib/Feldspar/Compiler/Imperative/Plugin/IVars.hs +4/−18
- lib/Feldspar/Compiler/Imperative/Plugin/Naming.hs +0/−194
- lib/Feldspar/Compiler/Imperative/Plugin/Unroll.hs +0/−285
- lib/Feldspar/Compiler/Imperative/Representation.hs +102/−384
- lib/Feldspar/Compiler/Imperative/TransformationInstance.hs +79/−74
- lib/Feldspar/Compiler/Internal.hs +46/−0
- lib/Feldspar/Compiler/Marshal.hs +212/−0
- lib/Feldspar/Compiler/Plugin.hs +174/−0
- lib/Feldspar/NameExtractor.hs +0/−159
- lib/Feldspar/Runtime.hs +26/−0
- lib/Feldspar/Transformation.hs +1/−1
- lib/Feldspar/Transformation/Framework.hs +0/−6
- src/Feldspar/Compiler/Frontend/CommandLine/API.hs +0/−155
- src/Feldspar/Compiler/Frontend/CommandLine/API/Constants.hs +0/−36
- src/Feldspar/Compiler/Frontend/CommandLine/API/Library.hs +0/−72
- src/Feldspar/Compiler/Frontend/CommandLine/API/Options.hs +0/−135
- src/Feldspar/Compiler/Frontend/CommandLine/Main.hs +0/−219
- tests/CallingConvention.hs +57/−0
- tests/RegressionTests.hs +175/−0
LICENSE view
@@ -1,3 +1,5 @@+Copyright (c) 2013, Emil Axelsson, Peter Jonsson, Anders Persson and+ Josef Svenningsson Copyright (c) 2012, Emil Axelsson, Gergely Dévai, Anders Persson and Josef Svenningsson Copyright (c) 2009-2011, ERICSSON AB@@ -6,7 +8,7 @@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright notice, + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the@@ -17,7 +19,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ benchs/CRC.hs view
@@ -0,0 +1,55 @@+{-# LANGUAGE TemplateHaskell #-}++import Feldspar hiding (force)+import Feldspar.Vector+import Feldspar.Compiler.Plugin+import Feldspar.Algorithm.CRC++import Foreign.Marshal (with)+import Data.Default+import Control.DeepSeq (force)+import Control.Exception (evaluate)++import Criterion.Main++testdata :: [Word8]+testdata = Prelude.take (16*1024) $ cycle [1,2,3,4]++naive :: Vector1 Word8 -> Data Word16+naive = crcNaive 0x8005 0++normal :: Vector1 Word8 -> Data Word16+normal v = share (makeCrcTable 0x8005) $ \t -> crcNormal t 0 v++h_naive :: [Word8] -> Word16+h_naive = eval naive++h_normal :: [Word8] -> Word16+h_normal = eval normal++loadFun ['naive, 'normal]++main :: IO ()+main = with def $ \out -> do+ d <- evaluate $ force testdata+ pd <- pack d >>= evaluate+ _ <- evaluate c_naive_builder+ _ <- evaluate c_normal_builder+ defaultMain+ [+ bgroup "evaluated"+ [ bench "h_naive" $ nf h_naive (Prelude.take 1024 d)+ , bench "h_normal" $ nf h_normal (Prelude.take 1024 d)+ ]+ , bgroup "compiled"+ [ bgroup "marshal"+ [ bench "c_naive" $ c_naive_worker d+ , bench "c_normal" $ c_normal_worker d+ ]+ , bgroup "raw"+ [ bench "c_naive" $ c_naive_raw pd out+ , bench "c_normal" $ c_normal_raw pd out+ ]+ ]+ ]+
feldspar-compiler.cabal view
@@ -1,17 +1,19 @@ name: feldspar-compiler-version: 0.6.0.2+version: 0.7 cabal-version: >= 1.14 build-type: Simple license: BSD3 license-file: LICENSE-copyright: Copyright (c) 2012 Emil Axelsson, Gergely Dévai,+copyright: Copyright (c) 2013-2014 Emil Axelsson, Peter Jonsson,+ Anders Persson, Josef Svenningsson+ Copyright (c) 2012 Emil Axelsson, Gergely Dévai, Anders Persson, Josef Svenningsson Copyright (c) 2009-2011, ERICSSON AB author: Feldspar group, Eotvos Lorand University Faculty of Informatics-maintainer: deva@inf.elte.hu+maintainer: anders.cj.persson@gmail.com stability: experimental-homepage: https://feldspar.github.com+homepage: http://feldspar.github.com bug-reports: https://github.com/feldspar/feldspar-compiler/issues synopsis: Compiler for the Feldspar language description: Feldspar (**F**unctional **E**mbedded **L**anguage for **DSP**@@ -22,11 +24,11 @@ language both according to ANSI C and also targeted to a real DSP HW. category: Compiler-tested-with: GHC==7.6.1, GHC==7.4.2+tested-with: GHC==7.8, GHC==7.6, GHC==7.4 source-repository head type: git- location: git://github.com/feldspar/feldspar-compiler.git+ location: git://github.com/Feldspar/feldspar-compiler.git library hs-source-dirs: lib@@ -53,80 +55,65 @@ Feldspar.Compiler.Imperative.FromCore.Tuple Feldspar.Compiler.Imperative.FromCore.FFI Feldspar.Compiler.Imperative.FromCore.Save+ Feldspar.Compiler.Imperative.FromCore.Switch Feldspar.Compiler.Imperative.Frontend Feldspar.Compiler.Imperative.TransformationInstance- Feldspar.Compiler.Imperative.Plugin.CollectFreeVars- Feldspar.Compiler.Imperative.Plugin.ConstantFolding- Feldspar.Compiler.Imperative.Plugin.Free Feldspar.Compiler.Imperative.Plugin.IVars- Feldspar.Compiler.Imperative.Plugin.Unroll- Feldspar.Compiler.Imperative.Plugin.Naming Feldspar.Compiler.Backend.C.CodeGeneration- Feldspar.Compiler.Backend.C.Plugin.PrettyPrint- Feldspar.Compiler.Backend.C.Plugin.Locator- Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler- Feldspar.Compiler.Backend.C.Plugin.TypeCorrector- Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator- Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner Feldspar.Compiler.Backend.C.Plugin.Rule Feldspar.Compiler.Backend.C.Library Feldspar.Compiler.Backend.C.Options Feldspar.Compiler.Backend.C.Platforms Feldspar.Compiler.Frontend.Interactive.Interface+ Feldspar.Compiler.Plugin+ Feldspar.Compiler.Marshal+ Feldspar.Compiler.CallConv Feldspar.Compiler.Compiler Feldspar.Compiler.Error+ Feldspar.Compiler.Internal Feldspar.Compiler Feldspar.Transformation Feldspar.Transformation.Framework- Feldspar.NameExtractor+ Feldspar.Runtime - default-language: Haskell98+ default-language: Haskell2010 build-depends:- feldspar-language >= 0.6 && < 0.7,- ansi-terminal,- base >= 4 && < 4.7,- containers,- haskell-src-exts >= 1.12,- directory,- filepath,- MonadCatchIO-mtl,+ base == 4.*,+ Cabal,+ ghc-paths,+ syntactic,+ plugins-multistage >= 0.5 && < 0.6,+ feldspar-language >= 0.7 && < 0.8, mtl,+ pretty,+ filepath,+ containers, process,- syntactic >= 1.4 && < 1.5+ directory >= 1.1,+ template-haskell,+ plugins >= 1.5.4,+ data-default >= 0.5,+ storable-tuple >= 0.0.2,+ storable-record >= 0.0.2.5 default-extensions:- DeriveDataTypeable- EmptyDataDecls- FlexibleContexts- FlexibleInstances- GADTs- MultiParamTypeClasses- PatternGuards- Rank2Types- ScopedTypeVariables- StandaloneDeriving- TypeFamilies- TypeOperators- TypeSynonymInstances- UndecidableInstances- FunctionalDependencies- ViewPatterns include-dirs: ./lib/Feldspar/C c-sources:--- lib/Feldspar/C/feldspar_c99.c--- lib/Feldspar/C/feldspar_array.c--- lib/Feldspar/C/ivar.c--- lib/Feldspar/C/taskpool.c+ lib/Feldspar/C/feldspar_c99.c+ lib/Feldspar/C/taskpool.c+ lib/Feldspar/C/ivar.c cc-options: -std=c99 -Wall + if os(linux)+ extra-libraries: gcc_s+ install-includes: feldspar_array.h- feldspar_array.c feldspar_c99.h feldspar_c99.c feldspar_tic64x.h@@ -142,54 +129,93 @@ cpp-options: -DRELEASE -executable feldspar- hs-source-dirs: src+-- executable feldspar+-- hs-source-dirs: src - main-is : Feldspar/Compiler/Frontend/CommandLine/Main.hs+-- main-is : Feldspar/Compiler/Frontend/CommandLine/Main.hs - default-language: Haskell98+-- default-language: Haskell2010 - other-modules:- Feldspar.Compiler.Frontend.CommandLine.API.Library- Feldspar.Compiler.Frontend.CommandLine.API.Constants- Feldspar.Compiler.Frontend.CommandLine.API.Options- Feldspar.Compiler.Frontend.CommandLine.API+-- other-modules:+-- Feldspar.Compiler.Frontend.CommandLine.NameExtractor+-- Feldspar.Compiler.Frontend.CommandLine.API.Library+-- Feldspar.Compiler.Frontend.CommandLine.API.Constants+-- Feldspar.Compiler.Frontend.CommandLine.API.Options+-- Feldspar.Compiler.Frontend.CommandLine.API +-- build-depends:+-- feldspar-language,+-- feldspar-compiler,+-- mtl,+-- base,+-- hint,+-- process,+-- filepath,+-- directory,+-- ansi-terminal,+-- MonadCatchIO-mtl,+-- haskell-src-exts >= 1.14++-- default-extensions:++-- ghc-options: -fcontext-stack=100++-- cpp-options: -DRELEASE++test-suite regression+ type: exitcode-stdio-1.0++ hs-source-dirs: tests++ main-is: RegressionTests.hs++ default-language: Haskell2010+ build-depends:- feldspar-language >= 0.6 && < 0.7,+ feldspar-language, feldspar-compiler,- syntactic >= 1.4 && < 1.5,- base >= 4 && < 4.7,- hint,- MonadCatchIO-mtl, mtl,- directory,- filepath,+ base,+ Cabal, process,- ansi-terminal,- containers,- haskell-src-exts >= 1.12+ bytestring >= 0.9 && < 0.11,+ tasty >= 0.3,+ tasty-golden >= 2.0,+ tasty-quickcheck >= 0.3,+ QuickCheck >= 2.5 && < 3.0 - default-extensions:- CPP- DeriveDataTypeable- EmptyDataDecls- FlexibleContexts- FlexibleInstances- GADTs- MultiParamTypeClasses- PatternGuards- Rank2Types- ScopedTypeVariables- StandaloneDeriving- TypeFamilies- TypeOperators- TypeSynonymInstances- UndecidableInstances- FunctionalDependencies- ViewPatterns+test-suite callconv+ type: exitcode-stdio-1.0 - ghc-options: -fcontext-stack=100+ hs-source-dirs: tests - cpp-options: -DRELEASE+ main-is: CallingConvention.hs + default-language: Haskell2010++ build-depends:+ feldspar-language,+ feldspar-compiler,+ base,+ tasty >= 0.3,+ tasty-quickcheck >= 0.3,+ QuickCheck >= 2.5 && < 3.0++benchmark crc+ type: exitcode-stdio-1.0++ hs-source-dirs: benchs++ main-is: CRC.hs++ default-language: Haskell2010++ ghc-options: -O2++ build-depends:+ feldspar-language,+ feldspar-compiler,+ data-default >= 0.5.3 && < 0.6,+ base,+ deepseq,+ criterion
− lib/Feldspar/C/feldspar_array.c
@@ -1,61 +0,0 @@-//-// Copyright (c) 2009-2011, ERICSSON AB-// All rights reserved.-// -// Redistribution and use in source and binary forms, with or without-// modification, are permitted provided that the following conditions are met:-// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer.-// * Redistributions in binary form must reproduce the above copyright-// notice, this list of conditions and the following disclaimer in the-// documentation and/or other materials provided with the distribution.-// * Neither the name of the ERICSSON AB nor the names of its contributors-// may be used to endorse or promote products derived from this software-// without specific prior written permission.-// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE-// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL-// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR-// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER-// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,-// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-//--#include "feldspar_array.h"-#include <string.h>-#include <assert.h>-#include <stdio.h>-//#define LOG-#include "log.h"--unsigned int feldspar_array_linker_hook = 0xDECAFBAD;--/* Deep array copy with a given length */-void copyArrayLen(struct array *to, struct array *from, int32_t len)-{- assert(to);- assert(from);- log_3("copyArrayLen %p %p %d - enter\n", to, from, len);- if( from->elemSize < 0 )- {- unsigned i;- log_3("copyArrayLen %p %p %d - nested\n", to, from, len);- for( i = 0; i < len; ++i )- copyArray( &at(struct array, to, i), &at(struct array, from, i) );- }- else- {- assert(to->buffer);- assert(from->buffer);- log_4("copyArrayLen %p %p %d - memcpy %d bytes\n", to, from, len- , len*from->elemSize);- memcpy( to->buffer, from->buffer, len * from->elemSize );- }- log_3("copyArrayLen %p %p %d - leave\n", to, from, len);-}-
lib/Feldspar/C/feldspar_array.h view
@@ -1,11 +1,11 @@ // // Copyright (c) 2009-2011, ERICSSON AB // All rights reserved.-// +// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met:-// -// * Redistributions of source code must retain the above copyright notice, +//+// * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the@@ -13,10 +13,10 @@ // * Neither the name of the ERICSSON AB nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission.-// +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR@@ -38,17 +38,6 @@ #include <stdio.h> /* to be removed */ -/* Important: Always zero-initialize struct arrays in the definitions- * and call initArray on them before use:- * - * struct array my = {0};- * initArray( &my, sizeof(elementType), numberOfElements );- * - * Zero initialization certifies that initArray works correctly.- * (There is a "magic number" check in initArray in case you forget to- * zero-initialize, but it is not 100% safe.)- */- /* TODO qualify the names to avoid clashes with Haskell names */ struct array@@ -57,29 +46,33 @@ int32_t length; /* number of elements in the array */ int32_t elemSize; /* size of elements in bytes; (- sizeof(struct array)) for nested arrays */ uint32_t bytes; /* The number of bytes the buffer can hold */- uint32_t inited; /* To decide between first initialization and reinitialization - This is to catch */ }; -/* Magic number */-#define INITED 0x89abcdef- /* Indexing into an array: */ /* Result: element of type 'type' */ #define at(type,arr,idx) (((type*)((arr)->buffer))[idx]) /* Array (re)initialization */-static inline void initArray(struct array *arr, int32_t size, int32_t len)+static inline struct array *initArray(struct array *arr, int32_t size, int32_t len) { int newBytes; log_3("initArray %p %d %d - enter\n", arr, size, len);+ if ( !arr )+ {+ struct array * ptr;+ ptr = calloc(1, sizeof(struct array));+ log_4("initArray %p %d %d - alloc fresh struct array %p\n", arr, size, len, ptr);+ arr = ptr;+ }+ assert(arr); arr->elemSize = size;- arr->length = len;+ arr->length = len; if( size < 0 ) size = sizeof(struct array); newBytes = size * len;- if( arr->buffer && (arr->inited == INITED) )+ if( arr->buffer ) { // Re-initialization log_1("initArray %p - reinitialize\n",arr);@@ -88,9 +81,8 @@ log_3("initArray %p - realloc since %d < %d\n" , arr, arr->bytes, newBytes); // Not enough space: reallocation needed- arr->bytes = newBytes;- free(arr->buffer);- arr->buffer = (void*)malloc( newBytes );+ arr->bytes = newBytes;+ arr->buffer = realloc(arr->buffer, newBytes); } else {@@ -103,13 +95,13 @@ { // First initialization arr->bytes = newBytes;- arr->buffer = (void*)malloc( newBytes ); - log_5("initArray %p - alloc %d * %d bytes %d at %p\n"+ arr->buffer = (void*)calloc(len,size);+ log_5("initArray %p - alloc %d * %d = %d bytes at %p\n" , arr, arr->length, arr->elemSize, newBytes, arr->buffer);- arr->inited = INITED; } assert( arr->buffer ); log_3("initArray %p %d %d - leave\n", arr, size, len);+ return arr; } // Free array@@ -117,23 +109,20 @@ static inline void freeArray(struct array *arr) { log_1("freeArray %p - enter\n", arr);- // assert(arr);- // if( !arr->buffer || arr->inited != INITED )- // {- // return;- // }- // if( arr->elemSize < 0 )- // {- // int i;- // for( i=0; i<arr->length; ++i )- // freeArray( &at(struct array,arr,i) );- // }- // free(arr->buffer);- // For the sake of extra safety:- // arr->buffer = 0;- // arr->length = 0;- // arr->bytes = 0;- // arr->inited = 0;+ if( arr && arr->buffer )+ {+ if( arr->elemSize < 0 )+ {+ for(int i=0; i<arr->length; ++i )+ freeArray( &at(struct array,arr,i) );+ }+ free(arr->buffer);+ // For the sake of extra safety:+ arr->buffer = 0;+ arr->length = 0;+ arr->bytes = 0;+ free(arr);+ } log_1("freeArray %p - leave\n", arr); } @@ -149,10 +138,10 @@ unsigned i; for( i = 0; i < from->length; ++i ) {- struct array *to_row = &at(struct array, to, i);+ struct array *to_row = &at(struct array, to, i); struct array *from_row = &at(struct array, from, i);- if( !to_row->buffer || to_row->inited != INITED )- initArray( to_row, from_row->elemSize, from_row->length );+ if( to_row == NULL )+ to_row = initArray( to_row, from_row->elemSize, from_row->length ); copyArray( to_row, from_row ); } log_2("copyArray %p %p - nested leave\n", to, from);@@ -190,9 +179,6 @@ } -/* Deep array copy with a given length */-void copyArrayLen(struct array *to, struct array *from, int32_t len);- /* Array length */ static inline int32_t getLength(struct array *arr) {@@ -201,25 +187,27 @@ } /* Reset array length */-static inline void setLength(struct array *arr, int32_t len)+static inline struct array *setLength(struct array *arr, int32_t size, int32_t len) {+ if ( !arr )+ arr = calloc(1, sizeof(struct array));+ assert(arr); log_2("setLength %p %d - enter\n", arr, len);+ arr->elemSize = size;+ if( size < 0 )+ size = sizeof(struct array); int newBytes = arr->elemSize * len;- if( arr->bytes >= newBytes )- {- arr->length = len;- }- else+ arr->length = len;+ if( arr->bytes < newBytes ) { log_3("setLength %p %d - realloc %d bytes\n", arr, len, newBytes);- // TODO: copy- arr->bytes = newBytes;- free( arr->buffer );- arr->buffer = malloc( newBytes );- assert( arr->buffer );+ arr->buffer = realloc(arr->buffer,newBytes);+ assert(arr->buffer);+ arr->bytes = newBytes; } log_2("setLength %p %d - leave\n", arr, len);+ return arr; } #endif
lib/Feldspar/C/feldspar_c99.c view
@@ -41,14 +41,16 @@ #include <time.h> #endif /* WIN32 */ --unsigned int feldspar_c99_linker_hook = 0xDECAFBAD;+int feldspar_c99_hook(void)+{+ return 0;+} /*--------------------------------------------------------------------------* * pow(), abs(), signum(), logBase() * *--------------------------------------------------------------------------*/ -int8_t pow_fun_int8( int8_t a, int8_t b )+int8_t pow_fun_int8_t( int8_t a, int8_t b ) { int8_t r = 1; int i;@@ -61,7 +63,7 @@ return r; } -int16_t pow_fun_int16( int16_t a, int16_t b )+int16_t pow_fun_int16_t( int16_t a, int16_t b ) { int16_t r = 1; int i;@@ -74,7 +76,7 @@ return r; } -int32_t pow_fun_int32( int32_t a, int32_t b )+int32_t pow_fun_int32_t( int32_t a, int32_t b ) { int32_t r = 1; int i;@@ -87,7 +89,7 @@ return r; } -int64_t pow_fun_int64( int64_t a, int64_t b )+int64_t pow_fun_int64_t( int64_t a, int64_t b ) { int64_t r = 1; int i;@@ -100,7 +102,7 @@ return r; } -uint8_t pow_fun_uint8( uint8_t a, uint8_t b )+uint8_t pow_fun_uint8_t( uint8_t a, uint8_t b ) { uint8_t r = 1; int i;@@ -109,7 +111,7 @@ return r; } -uint16_t pow_fun_uint16( uint16_t a, uint16_t b )+uint16_t pow_fun_uint16_t( uint16_t a, uint16_t b ) { uint16_t r = 1; int i;@@ -118,7 +120,7 @@ return r; } -uint32_t pow_fun_uint32( uint32_t a, uint32_t b )+uint32_t pow_fun_uint32_t( uint32_t a, uint32_t b ) { uint32_t r = 1; int i;@@ -127,7 +129,7 @@ return r; } -uint64_t pow_fun_uint64( uint64_t a, uint64_t b )+uint64_t pow_fun_uint64_t( uint64_t a, uint64_t b ) { uint64_t r = 1; int i;@@ -138,7 +140,7 @@ -int8_t abs_fun_int8( int8_t a )+int8_t abs_fun_int8_t( int8_t a ) { // From Bit Twiddling Hacks: // "Compute the integer absolute value (abs) without branching"@@ -146,7 +148,7 @@ return (a + mask) ^ mask; } -int16_t abs_fun_int16( int16_t a )+int16_t abs_fun_int16_t( int16_t a ) { // From Bit Twiddling Hacks: // "Compute the integer absolute value (abs) without branching"@@ -154,7 +156,7 @@ return (a + mask) ^ mask; } -int32_t abs_fun_int32( int32_t a )+int32_t abs_fun_int32_t( int32_t a ) { // From Bit Twiddling Hacks: // "Compute the integer absolute value (abs) without branching"@@ -162,7 +164,7 @@ return (a + mask) ^ mask; } -int64_t abs_fun_int64( int64_t a )+int64_t abs_fun_int64_t( int64_t a ) { // From Bit Twiddling Hacks: // "Compute the integer absolute value (abs) without branching"@@ -172,46 +174,46 @@ -int8_t signum_fun_int8( int8_t a )+int8_t signum_fun_int8_t( int8_t a ) { // From Bit Twiddling Hacks: "Compute the sign of an integer" return (a != 0) | (a >> 7); } -int16_t signum_fun_int16( int16_t a )+int16_t signum_fun_int16_t( int16_t a ) { // From Bit Twiddling Hacks: "Compute the sign of an integer" return (a != 0) | (a >> 15); } -int32_t signum_fun_int32( int32_t a )+int32_t signum_fun_int32_t( int32_t a ) { // From Bit Twiddling Hacks: "Compute the sign of an integer" return (a != 0) | (a >> 31); } -int64_t signum_fun_int64( int64_t a )+int64_t signum_fun_int64_t( int64_t a ) { // From Bit Twiddling Hacks: "Compute the sign of an integer" return (a != 0) | (a >> 63); } -uint8_t signum_fun_uint8( uint8_t a )+uint8_t signum_fun_uint8_t( uint8_t a ) { return (a > 0); } -uint16_t signum_fun_uint16( uint16_t a )+uint16_t signum_fun_uint16_t( uint16_t a ) { return (a > 0); } -uint32_t signum_fun_uint32( uint32_t a )+uint32_t signum_fun_uint32_t( uint32_t a ) { return (a > 0); } -uint64_t signum_fun_uint64( uint64_t a )+uint64_t signum_fun_uint64_t( uint64_t a ) { return (a > 0); }@@ -230,222 +232,236 @@ } +double signum_fun_double( double a )+{+ // From Bit Twiddling Hacks: "Compute the sign of an integer"+ return (a > 0) - (a < 0);+} +++double logBase_fun_double( double a, double b )+{+ return log(b) / log(a);+}+++ /*--------------------------------------------------------------------------* * Bit operations * *--------------------------------------------------------------------------*/ -int8_t setBit_fun_int8( int8_t x, uint32_t i )+int8_t setBit_fun_int8_t( int8_t x, uint32_t i ) { return x | 1 << i; } -int16_t setBit_fun_int16( int16_t x, uint32_t i )+int16_t setBit_fun_int16_t( int16_t x, uint32_t i ) { return x | 1 << i; } -int32_t setBit_fun_int32( int32_t x, uint32_t i )+int32_t setBit_fun_int32_t( int32_t x, uint32_t i ) { return x | 1 << i; } -int64_t setBit_fun_int64( int64_t x, uint32_t i )+int64_t setBit_fun_int64_t( int64_t x, uint32_t i ) { return x | 1 << i; } -uint8_t setBit_fun_uint8( uint8_t x, uint32_t i )+uint8_t setBit_fun_uint8_t( uint8_t x, uint32_t i ) { return x | 1 << i; } -uint16_t setBit_fun_uint16( uint16_t x, uint32_t i )+uint16_t setBit_fun_uint16_t( uint16_t x, uint32_t i ) { return x | 1 << i; } -uint32_t setBit_fun_uint32( uint32_t x, uint32_t i )+uint32_t setBit_fun_uint32_t( uint32_t x, uint32_t i ) { return x | 1 << i; } -uint64_t setBit_fun_uint64( uint64_t x, uint32_t i )+uint64_t setBit_fun_uint64_t( uint64_t x, uint32_t i ) { return x | 1 << i; } -int8_t clearBit_fun_int8( int8_t x, uint32_t i )+int8_t clearBit_fun_int8_t( int8_t x, uint32_t i ) { return x & ~(1 << i); } -int16_t clearBit_fun_int16( int16_t x, uint32_t i )+int16_t clearBit_fun_int16_t( int16_t x, uint32_t i ) { return x & ~(1 << i); } -int32_t clearBit_fun_int32( int32_t x, uint32_t i )+int32_t clearBit_fun_int32_t( int32_t x, uint32_t i ) { return x & ~(1 << i); } -int64_t clearBit_fun_int64( int64_t x, uint32_t i )+int64_t clearBit_fun_int64_t( int64_t x, uint32_t i ) { return x & ~(1 << i); } -uint8_t clearBit_fun_uint8( uint8_t x, uint32_t i )+uint8_t clearBit_fun_uint8_t( uint8_t x, uint32_t i ) { return x & ~(1 << i); } -uint16_t clearBit_fun_uint16( uint16_t x, uint32_t i )+uint16_t clearBit_fun_uint16_t( uint16_t x, uint32_t i ) { return x & ~(1 << i); } -uint32_t clearBit_fun_uint32( uint32_t x, uint32_t i )+uint32_t clearBit_fun_uint32_t( uint32_t x, uint32_t i ) { return x & ~(1 << i); } -uint64_t clearBit_fun_uint64( uint64_t x, uint32_t i )+uint64_t clearBit_fun_uint64_t( uint64_t x, uint32_t i ) { return x & ~(1 << i); } -int8_t complementBit_fun_int8( int8_t x, uint32_t i )+int8_t complementBit_fun_int8_t( int8_t x, uint32_t i ) { return x ^ 1 << i; } -int16_t complementBit_fun_int16( int16_t x, uint32_t i )+int16_t complementBit_fun_int16_t( int16_t x, uint32_t i ) { return x ^ 1 << i; } -int32_t complementBit_fun_int32( int32_t x, uint32_t i )+int32_t complementBit_fun_int32_t( int32_t x, uint32_t i ) { return x ^ 1 << i; } -int64_t complementBit_fun_int64( int64_t x, uint32_t i )+int64_t complementBit_fun_int64_t( int64_t x, uint32_t i ) { return x ^ 1 << i; } -uint8_t complementBit_fun_uint8( uint8_t x, uint32_t i )+uint8_t complementBit_fun_uint8_t( uint8_t x, uint32_t i ) { return x ^ 1 << i; } -uint16_t complementBit_fun_uint16( uint16_t x, uint32_t i )+uint16_t complementBit_fun_uint16_t( uint16_t x, uint32_t i ) { return x ^ 1 << i; } -uint32_t complementBit_fun_uint32( uint32_t x, uint32_t i )+uint32_t complementBit_fun_uint32_t( uint32_t x, uint32_t i ) { return x ^ 1 << i; } -uint64_t complementBit_fun_uint64( uint64_t x, uint32_t i )+uint64_t complementBit_fun_uint64_t( uint64_t x, uint32_t i ) { return x ^ 1 << i; } -int testBit_fun_int8( int8_t x, uint32_t i )+int testBit_fun_int8_t( int8_t x, uint32_t i ) { return (x & 1 << i) != 0; } -int testBit_fun_int16( int16_t x, uint32_t i )+int testBit_fun_int16_t( int16_t x, uint32_t i ) { return (x & 1 << i) != 0; } -int testBit_fun_int32( int32_t x, uint32_t i )+int testBit_fun_int32_t( int32_t x, uint32_t i ) { return (x & 1 << i) != 0; } -int testBit_fun_int64( int64_t x, uint32_t i )+int testBit_fun_int64_t( int64_t x, uint32_t i ) { return (x & 1 << i) != 0; } -int testBit_fun_uint8( uint8_t x, uint32_t i )+int testBit_fun_uint8_t( uint8_t x, uint32_t i ) { return (x & 1 << i) != 0; } -int testBit_fun_uint16( uint16_t x, uint32_t i )+int testBit_fun_uint16_t( uint16_t x, uint32_t i ) { return (x & 1 << i) != 0; } -int testBit_fun_uint32( uint32_t x, uint32_t i )+int testBit_fun_uint32_t( uint32_t x, uint32_t i ) { return (x & 1 << i) != 0; } -int testBit_fun_uint64( uint64_t x, uint32_t i )+int testBit_fun_uint64_t( uint64_t x, uint32_t i ) { return (x & 1 << i) != 0; } -int8_t rotateL_fun_int8( int8_t x, int32_t i )+int8_t rotateL_fun_int8_t( int8_t x, int32_t i ) { if ((i %= 8) == 0) return x; return (x << i) | ((0x7f >> (7 - i)) & (x >> (8 - i))); } -int16_t rotateL_fun_int16( int16_t x, int32_t i )+int16_t rotateL_fun_int16_t( int16_t x, int32_t i ) { if ((i %= 16) == 0) return x; return (x << i) | ((0x7fff >> (15 - i)) & (x >> (16 - i))); } -int32_t rotateL_fun_int32( int32_t x, int32_t i )+int32_t rotateL_fun_int32_t( int32_t x, int32_t i ) { if ((i %= 32) == 0) return x; return (x << i) | ((0x7fffffff >> (31 - i)) & (x >> (32 - i))); } -int64_t rotateL_fun_int64( int64_t x, int32_t i )+int64_t rotateL_fun_int64_t( int64_t x, int32_t i ) { if ((i %= 64) == 0) return x; return (x << i) | ((0x7fffffffffffffffll >> (63 - i)) & (x >> (64 - i))); } -uint8_t rotateL_fun_uint8( uint8_t x, int32_t i )+uint8_t rotateL_fun_uint8_t( uint8_t x, int32_t i ) { if ((i %= 8) == 0) return x; return (x << i) | (x >> (8 - i)); } -uint16_t rotateL_fun_uint16( uint16_t x, int32_t i )+uint16_t rotateL_fun_uint16_t( uint16_t x, int32_t i ) { if ((i %= 16) == 0) return x; return (x << i) | (x >> (16 - i)); } -uint32_t rotateL_fun_uint32( uint32_t x, int32_t i )+uint32_t rotateL_fun_uint32_t( uint32_t x, int32_t i ) { if ((i %= 32) == 0) return x; return (x << i) | (x >> (32 - i)); } -uint64_t rotateL_fun_uint64( uint64_t x, int32_t i )+uint64_t rotateL_fun_uint64_t( uint64_t x, int32_t i ) { if ((i %= 64) == 0) return x; return (x << i) | (x >> (64 - i));@@ -453,49 +469,49 @@ -int8_t rotateR_fun_int8( int8_t x, int32_t i )+int8_t rotateR_fun_int8_t( int8_t x, int32_t i ) { if ((i %= 8) == 0) return x; return (x << (8 - i)) | ((0x7f >> (i - 1)) & (x >> i)); } -int16_t rotateR_fun_int16( int16_t x, int32_t i )+int16_t rotateR_fun_int16_t( int16_t x, int32_t i ) { if ((i %= 16) == 0) return x; return (x << (16 - i)) | ((0x7fff >> (i - 1)) & (x >> i)); } -int32_t rotateR_fun_int32( int32_t x, int32_t i )+int32_t rotateR_fun_int32_t( int32_t x, int32_t i ) { if ((i %= 32) == 0) return x; return (x << (32 - i)) | ((0x7fffffff >> (i - 1)) & (x >> i)); } -int64_t rotateR_fun_int64( int64_t x, int32_t i )+int64_t rotateR_fun_int64_t( int64_t x, int32_t i ) { if ((i %= 64) == 0) return x; return (x << (64 - i)) | ((0x7fffffffffffffffll >> (i - 1)) & (x >> i)); } -uint8_t rotateR_fun_uint8( uint8_t x, int32_t i )+uint8_t rotateR_fun_uint8_t( uint8_t x, int32_t i ) { if ((i %= 8) == 0) return x; return (x << (8 - i)) | (x >> i); } -uint16_t rotateR_fun_uint16( uint16_t x, int32_t i )+uint16_t rotateR_fun_uint16_t( uint16_t x, int32_t i ) { if ((i %= 16) == 0) return x; return (x << (16 - i)) | (x >> i); } -uint32_t rotateR_fun_uint32( uint32_t x, int32_t i )+uint32_t rotateR_fun_uint32_t( uint32_t x, int32_t i ) { if ((i %= 32) == 0) return x; return (x << (32 - i)) | (x >> i); } -uint64_t rotateR_fun_uint64( uint64_t x, int32_t i )+uint64_t rotateR_fun_uint64_t( uint64_t x, int32_t i ) { if ((i %= 64) == 0) return x; return (x << (64 - i)) | (x >> i);@@ -503,7 +519,7 @@ -int8_t reverseBits_fun_int8( int8_t x )+int8_t reverseBits_fun_int8_t( int8_t x ) { int8_t r = x; int i = 7;@@ -515,7 +531,7 @@ return r << i; } -int16_t reverseBits_fun_int16( int16_t x )+int16_t reverseBits_fun_int16_t( int16_t x ) { int16_t r = x; int i = 15;@@ -527,7 +543,7 @@ return r << i; } -int32_t reverseBits_fun_int32( int32_t x )+int32_t reverseBits_fun_int32_t( int32_t x ) { int32_t r = x; int i = 31;@@ -539,7 +555,7 @@ return r << i; } -int64_t reverseBits_fun_int64( int64_t x )+int64_t reverseBits_fun_int64_t( int64_t x ) { int64_t r = x; int i = 63;@@ -551,7 +567,7 @@ return r << i; } -uint8_t reverseBits_fun_uint8( uint8_t x )+uint8_t reverseBits_fun_uint8_t( uint8_t x ) { uint8_t r = x; int i = 7;@@ -563,7 +579,7 @@ return r << i; } -uint16_t reverseBits_fun_uint16( uint16_t x )+uint16_t reverseBits_fun_uint16_t( uint16_t x ) { uint16_t r = x; int i = 15;@@ -575,7 +591,7 @@ return r << i; } -uint32_t reverseBits_fun_uint32( uint32_t x )+uint32_t reverseBits_fun_uint32_t( uint32_t x ) { uint32_t r = x; int i = 31;@@ -587,7 +603,7 @@ return r << i; } -uint64_t reverseBits_fun_uint64( uint64_t x )+uint64_t reverseBits_fun_uint64_t( uint64_t x ) { uint64_t r = x; int i = 63;@@ -601,7 +617,7 @@ -uint32_t bitScan_fun_int8( int8_t x )+uint32_t bitScan_fun_int8_t( int8_t x ) { uint32_t r = 0; int8_t s = (x & 0x80);@@ -611,7 +627,7 @@ return r; } -uint32_t bitScan_fun_int16( int16_t x )+uint32_t bitScan_fun_int16_t( int16_t x ) { uint32_t r = 0; int16_t s = (x & 0x8000);@@ -621,7 +637,7 @@ return r; } -uint32_t bitScan_fun_int32( int32_t x )+uint32_t bitScan_fun_int32_t( int32_t x ) { uint32_t r = 0; int32_t s = (x & 0x80000000);@@ -631,7 +647,7 @@ return r; } -uint32_t bitScan_fun_int64( int64_t x )+uint32_t bitScan_fun_int64_t( int64_t x ) { uint32_t r = 0; int64_t s = (x & 0x8000000000000000ll);@@ -641,7 +657,7 @@ return r; } -uint32_t bitScan_fun_uint8( uint8_t x )+uint32_t bitScan_fun_uint8_t( uint8_t x ) { uint32_t r = 8; while (x)@@ -652,7 +668,7 @@ return r; } -uint32_t bitScan_fun_uint16( uint16_t x )+uint32_t bitScan_fun_uint16_t( uint16_t x ) { uint32_t r = 16; while (x)@@ -663,7 +679,7 @@ return r; } -uint32_t bitScan_fun_uint32( uint32_t x )+uint32_t bitScan_fun_uint32_t( uint32_t x ) { uint32_t r = 32; while (x)@@ -674,7 +690,7 @@ return r; } -uint32_t bitScan_fun_uint64( uint64_t x )+uint32_t bitScan_fun_uint64_t( uint64_t x ) { uint32_t r = 64; while (x)@@ -687,7 +703,7 @@ -uint32_t bitCount_fun_int8( int8_t x )+uint32_t bitCount_fun_int8_t( int8_t x ) { uint32_t r = x & 1; for (x = x >> 1 & 0x7f; x; x >>= 1)@@ -695,7 +711,7 @@ return r; } -uint32_t bitCount_fun_int16( int16_t x )+uint32_t bitCount_fun_int16_t( int16_t x ) { uint32_t r = x & 1; for (x = x >> 1 & 0x7fff; x; x >>= 1)@@ -703,7 +719,7 @@ return r; } -uint32_t bitCount_fun_int32( int32_t x )+uint32_t bitCount_fun_int32_t( int32_t x ) { uint32_t r = x & 1; for (x = x >> 1 & 0x7fffffff; x; x >>= 1)@@ -711,7 +727,7 @@ return r; } -uint32_t bitCount_fun_int64( int64_t x )+uint32_t bitCount_fun_int64_t( int64_t x ) { uint32_t r = x & 1; for (x = x >> 1 & 0x7fffffffffffffffll; x; x >>= 1)@@ -719,7 +735,7 @@ return r; } -uint32_t bitCount_fun_uint8( uint8_t x )+uint32_t bitCount_fun_uint8_t( uint8_t x ) { uint32_t r = x & 1; while (x >>= 1)@@ -727,7 +743,7 @@ return r; } -uint32_t bitCount_fun_uint16( uint16_t x )+uint32_t bitCount_fun_uint16_t( uint16_t x ) { uint32_t r = x & 1; while (x >>= 1)@@ -735,7 +751,7 @@ return r; } -uint32_t bitCount_fun_uint32( uint32_t x )+uint32_t bitCount_fun_uint32_t( uint32_t x ) { uint32_t r = x & 1; while (x >>= 1)@@ -743,7 +759,7 @@ return r; } -uint32_t bitCount_fun_uint64( uint64_t x )+uint32_t bitCount_fun_uint64_t( uint64_t x ) { uint32_t r = x & 1; while (x >>= 1)@@ -757,98 +773,98 @@ * Complex numbers * *--------------------------------------------------------------------------*/ -int equal_fun_complexOf_int8( complexOf_int8 a, complexOf_int8 b )+int equal_fun_complexOf_int8_t( complexOf_int8_t a, complexOf_int8_t b ) { return a.re == b.re && a.im == b.im; } -int equal_fun_complexOf_int16( complexOf_int16 a, complexOf_int16 b )+int equal_fun_complexOf_int16_t( complexOf_int16_t a, complexOf_int16_t b ) { return a.re == b.re && a.im == b.im; } -int equal_fun_complexOf_int32( complexOf_int32 a, complexOf_int32 b )+int equal_fun_complexOf_int32_t( complexOf_int32_t a, complexOf_int32_t b ) { return a.re == b.re && a.im == b.im; } -int equal_fun_complexOf_int64( complexOf_int64 a, complexOf_int64 b )+int equal_fun_complexOf_int64_t( complexOf_int64_t a, complexOf_int64_t b ) { return a.re == b.re && a.im == b.im; } -int equal_fun_complexOf_uint8( complexOf_uint8 a, complexOf_uint8 b )+int equal_fun_complexOf_uint8_t( complexOf_uint8_t a, complexOf_uint8_t b ) { return a.re == b.re && a.im == b.im; } -int equal_fun_complexOf_uint16( complexOf_uint16 a, complexOf_uint16 b )+int equal_fun_complexOf_uint16_t( complexOf_uint16_t a, complexOf_uint16_t b ) { return a.re == b.re && a.im == b.im; } -int equal_fun_complexOf_uint32( complexOf_uint32 a, complexOf_uint32 b )+int equal_fun_complexOf_uint32_t( complexOf_uint32_t a, complexOf_uint32_t b ) { return a.re == b.re && a.im == b.im; } -int equal_fun_complexOf_uint64( complexOf_uint64 a, complexOf_uint64 b )+int equal_fun_complexOf_uint64_t( complexOf_uint64_t a, complexOf_uint64_t b ) { return a.re == b.re && a.im == b.im; } -complexOf_int8 negate_fun_complexOf_int8( complexOf_int8 a )+complexOf_int8_t negate_fun_complexOf_int8_t( complexOf_int8_t a ) { a.re = -a.re; a.im = -a.im; return a; } -complexOf_int16 negate_fun_complexOf_int16( complexOf_int16 a )+complexOf_int16_t negate_fun_complexOf_int16_t( complexOf_int16_t a ) { a.re = -a.re; a.im = -a.im; return a; } -complexOf_int32 negate_fun_complexOf_int32( complexOf_int32 a )+complexOf_int32_t negate_fun_complexOf_int32_t( complexOf_int32_t a ) { a.re = -a.re; a.im = -a.im; return a; } -complexOf_int64 negate_fun_complexOf_int64( complexOf_int64 a )+complexOf_int64_t negate_fun_complexOf_int64_t( complexOf_int64_t a ) { a.re = -a.re; a.im = -a.im; return a; } -complexOf_uint8 negate_fun_complexOf_uint8( complexOf_uint8 a )+complexOf_uint8_t negate_fun_complexOf_uint8_t( complexOf_uint8_t a ) { a.re = -a.re; a.im = -a.im; return a; } -complexOf_uint16 negate_fun_complexOf_uint16( complexOf_uint16 a )+complexOf_uint16_t negate_fun_complexOf_uint16_t( complexOf_uint16_t a ) { a.re = -a.re; a.im = -a.im; return a; } -complexOf_uint32 negate_fun_complexOf_uint32( complexOf_uint32 a )+complexOf_uint32_t negate_fun_complexOf_uint32_t( complexOf_uint32_t a ) { a.re = -a.re; a.im = -a.im; return a; } -complexOf_uint64 negate_fun_complexOf_uint64( complexOf_uint64 a )+complexOf_uint64_t negate_fun_complexOf_uint64_t( complexOf_uint64_t a ) { a.re = -a.re; a.im = -a.im;@@ -857,162 +873,162 @@ -complexOf_int8 abs_fun_complexOf_int8( complexOf_int8 a )+complexOf_int8_t abs_fun_complexOf_int8_t( complexOf_int8_t a ) {- a.re = magnitude_fun_complexOf_int8(a);+ a.re = magnitude_fun_complexOf_int8_t(a); a.im = 0; return a; } -complexOf_int16 abs_fun_complexOf_int16( complexOf_int16 a )+complexOf_int16_t abs_fun_complexOf_int16_t( complexOf_int16_t a ) {- a.re = magnitude_fun_complexOf_int16(a);+ a.re = magnitude_fun_complexOf_int16_t(a); a.im = 0; return a; } -complexOf_int32 abs_fun_complexOf_int32( complexOf_int32 a )+complexOf_int32_t abs_fun_complexOf_int32_t( complexOf_int32_t a ) {- a.re = magnitude_fun_complexOf_int32(a);+ a.re = magnitude_fun_complexOf_int32_t(a); a.im = 0; return a; } -complexOf_int64 abs_fun_complexOf_int64( complexOf_int64 a )+complexOf_int64_t abs_fun_complexOf_int64_t( complexOf_int64_t a ) {- a.re = magnitude_fun_complexOf_int64(a);+ a.re = magnitude_fun_complexOf_int64_t(a); a.im = 0; return a; } -complexOf_uint8 abs_fun_complexOf_uint8( complexOf_uint8 a )+complexOf_uint8_t abs_fun_complexOf_uint8_t( complexOf_uint8_t a ) {- a.re = magnitude_fun_complexOf_uint8(a);+ a.re = magnitude_fun_complexOf_uint8_t(a); a.im = 0; return a; } -complexOf_uint16 abs_fun_complexOf_uint16( complexOf_uint16 a )+complexOf_uint16_t abs_fun_complexOf_uint16_t( complexOf_uint16_t a ) {- a.re = magnitude_fun_complexOf_uint16(a);+ a.re = magnitude_fun_complexOf_uint16_t(a); a.im = 0; return a; } -complexOf_uint32 abs_fun_complexOf_uint32( complexOf_uint32 a )+complexOf_uint32_t abs_fun_complexOf_uint32_t( complexOf_uint32_t a ) {- a.re = magnitude_fun_complexOf_uint32(a);+ a.re = magnitude_fun_complexOf_uint32_t(a); a.im = 0; return a; } -complexOf_uint64 abs_fun_complexOf_uint64( complexOf_uint64 a )+complexOf_uint64_t abs_fun_complexOf_uint64_t( complexOf_uint64_t a ) {- a.re = magnitude_fun_complexOf_uint64(a);+ a.re = magnitude_fun_complexOf_uint64_t(a); a.im = 0; return a; } -complexOf_int8 signum_fun_complexOf_int8( complexOf_int8 a )+complexOf_int8_t signum_fun_complexOf_int8_t( complexOf_int8_t a ) { int8_t m; if (a.re == 0 && a.im == 0) { return a; } else {- m = magnitude_fun_complexOf_int8(a);+ m = magnitude_fun_complexOf_int8_t(a); a.re = a.re / m; a.im = a.im / m; return a; } } -complexOf_int16 signum_fun_complexOf_int16( complexOf_int16 a )+complexOf_int16_t signum_fun_complexOf_int16_t( complexOf_int16_t a ) { int16_t m; if (a.re == 0 && a.im == 0) { return a; } else {- m = magnitude_fun_complexOf_int16(a);+ m = magnitude_fun_complexOf_int16_t(a); a.re = a.re / m; a.im = a.im / m; return a; } } -complexOf_int32 signum_fun_complexOf_int32( complexOf_int32 a )+complexOf_int32_t signum_fun_complexOf_int32_t( complexOf_int32_t a ) { int32_t m; if (a.re == 0 && a.im == 0) { return a; } else {- m = magnitude_fun_complexOf_int32(a);+ m = magnitude_fun_complexOf_int32_t(a); a.re = a.re / m; a.im = a.im / m; return a; } } -complexOf_int64 signum_fun_complexOf_int64( complexOf_int64 a )+complexOf_int64_t signum_fun_complexOf_int64_t( complexOf_int64_t a ) { int64_t m; if (a.re == 0 && a.im == 0) { return a; } else {- m = magnitude_fun_complexOf_int64(a);+ m = magnitude_fun_complexOf_int64_t(a); a.re = a.re / m; a.im = a.im / m; return a; } } -complexOf_uint8 signum_fun_complexOf_uint8( complexOf_uint8 a )+complexOf_uint8_t signum_fun_complexOf_uint8_t( complexOf_uint8_t a ) { uint8_t m; if (a.re == 0 && a.im == 0) { return a; } else {- m = magnitude_fun_complexOf_uint8(a);+ m = magnitude_fun_complexOf_uint8_t(a); a.re = a.re / m; a.im = a.im / m; return a; } } -complexOf_uint16 signum_fun_complexOf_uint16( complexOf_uint16 a )+complexOf_uint16_t signum_fun_complexOf_uint16_t( complexOf_uint16_t a ) { uint16_t m; if (a.re == 0 && a.im == 0) { return a; } else {- m = magnitude_fun_complexOf_uint16(a);+ m = magnitude_fun_complexOf_uint16_t(a); a.re = a.re / m; a.im = a.im / m; return a; } } -complexOf_uint32 signum_fun_complexOf_uint32( complexOf_uint32 a )+complexOf_uint32_t signum_fun_complexOf_uint32_t( complexOf_uint32_t a ) { uint32_t m; if (a.re == 0 && a.im == 0) { return a; } else {- m = magnitude_fun_complexOf_uint32(a);+ m = magnitude_fun_complexOf_uint32_t(a); a.re = a.re / m; a.im = a.im / m; return a; } } -complexOf_uint64 signum_fun_complexOf_uint64( complexOf_uint64 a )+complexOf_uint64_t signum_fun_complexOf_uint64_t( complexOf_uint64_t a ) { uint64_t m; if (a.re == 0 && a.im == 0) { return a; } else {- m = magnitude_fun_complexOf_uint64(a);+ m = magnitude_fun_complexOf_uint64_t(a); a.re = a.re / m; a.im = a.im / m; return a;@@ -1031,57 +1047,69 @@ } +double complex signum_fun_complexOf_double( double complex a )+{+ double m;+ if (a == 0) {+ return a;+ } else {+ m = cabsf(a);+ return crealf(a) / m + cimagf(a) / m * I;+ }+} -complexOf_int8 add_fun_complexOf_int8( complexOf_int8 a, complexOf_int8 b )+++complexOf_int8_t add_fun_complexOf_int8_t( complexOf_int8_t a, complexOf_int8_t b ) { a.re = a.re + b.re; a.im = a.im + b.im; return a; } -complexOf_int16 add_fun_complexOf_int16( complexOf_int16 a, complexOf_int16 b )+complexOf_int16_t add_fun_complexOf_int16_t( complexOf_int16_t a, complexOf_int16_t b ) { a.re = a.re + b.re; a.im = a.im + b.im; return a; } -complexOf_int32 add_fun_complexOf_int32( complexOf_int32 a, complexOf_int32 b )+complexOf_int32_t add_fun_complexOf_int32_t( complexOf_int32_t a, complexOf_int32_t b ) { a.re = a.re + b.re; a.im = a.im + b.im; return a; } -complexOf_int64 add_fun_complexOf_int64( complexOf_int64 a, complexOf_int64 b )+complexOf_int64_t add_fun_complexOf_int64_t( complexOf_int64_t a, complexOf_int64_t b ) { a.re = a.re + b.re; a.im = a.im + b.im; return a; } -complexOf_uint8 add_fun_complexOf_uint8( complexOf_uint8 a, complexOf_uint8 b )+complexOf_uint8_t add_fun_complexOf_uint8_t( complexOf_uint8_t a, complexOf_uint8_t b ) { a.re = a.re + b.re; a.im = a.im + b.im; return a; } -complexOf_uint16 add_fun_complexOf_uint16( complexOf_uint16 a, complexOf_uint16 b )+complexOf_uint16_t add_fun_complexOf_uint16_t( complexOf_uint16_t a, complexOf_uint16_t b ) { a.re = a.re + b.re; a.im = a.im + b.im; return a; } -complexOf_uint32 add_fun_complexOf_uint32( complexOf_uint32 a, complexOf_uint32 b )+complexOf_uint32_t add_fun_complexOf_uint32_t( complexOf_uint32_t a, complexOf_uint32_t b ) { a.re = a.re + b.re; a.im = a.im + b.im; return a; } -complexOf_uint64 add_fun_complexOf_uint64( complexOf_uint64 a, complexOf_uint64 b )+complexOf_uint64_t add_fun_complexOf_uint64_t( complexOf_uint64_t a, complexOf_uint64_t b ) { a.re = a.re + b.re; a.im = a.im + b.im;@@ -1090,56 +1118,56 @@ -complexOf_int8 sub_fun_complexOf_int8( complexOf_int8 a, complexOf_int8 b )+complexOf_int8_t sub_fun_complexOf_int8_t( complexOf_int8_t a, complexOf_int8_t b ) { a.re = a.re - b.re; a.im = a.im - b.im; return a; } -complexOf_int16 sub_fun_complexOf_int16( complexOf_int16 a, complexOf_int16 b )+complexOf_int16_t sub_fun_complexOf_int16_t( complexOf_int16_t a, complexOf_int16_t b ) { a.re = a.re - b.re; a.im = a.im - b.im; return a; } -complexOf_int32 sub_fun_complexOf_int32( complexOf_int32 a, complexOf_int32 b )+complexOf_int32_t sub_fun_complexOf_int32_t( complexOf_int32_t a, complexOf_int32_t b ) { a.re = a.re - b.re; a.im = a.im - b.im; return a; } -complexOf_int64 sub_fun_complexOf_int64( complexOf_int64 a, complexOf_int64 b )+complexOf_int64_t sub_fun_complexOf_int64_t( complexOf_int64_t a, complexOf_int64_t b ) { a.re = a.re - b.re; a.im = a.im - b.im; return a; } -complexOf_uint8 sub_fun_complexOf_uint8( complexOf_uint8 a, complexOf_uint8 b )+complexOf_uint8_t sub_fun_complexOf_uint8_t( complexOf_uint8_t a, complexOf_uint8_t b ) { a.re = a.re - b.re; a.im = a.im - b.im; return a; } -complexOf_uint16 sub_fun_complexOf_uint16( complexOf_uint16 a, complexOf_uint16 b )+complexOf_uint16_t sub_fun_complexOf_uint16_t( complexOf_uint16_t a, complexOf_uint16_t b ) { a.re = a.re - b.re; a.im = a.im - b.im; return a; } -complexOf_uint32 sub_fun_complexOf_uint32( complexOf_uint32 a, complexOf_uint32 b )+complexOf_uint32_t sub_fun_complexOf_uint32_t( complexOf_uint32_t a, complexOf_uint32_t b ) { a.re = a.re - b.re; a.im = a.im - b.im; return a; } -complexOf_uint64 sub_fun_complexOf_uint64( complexOf_uint64 a, complexOf_uint64 b )+complexOf_uint64_t sub_fun_complexOf_uint64_t( complexOf_uint64_t a, complexOf_uint64_t b ) { a.re = a.re - b.re; a.im = a.im - b.im;@@ -1148,65 +1176,65 @@ -complexOf_int8 mult_fun_complexOf_int8( complexOf_int8 a, complexOf_int8 b )+complexOf_int8_t mult_fun_complexOf_int8_t( complexOf_int8_t a, complexOf_int8_t b ) {- complexOf_int8 r;+ complexOf_int8_t r; r.re = a.re * b.re - a.im * b.im; r.im = a.im * b.re + a.re * b.im; return r; } -complexOf_int16 mult_fun_complexOf_int16( complexOf_int16 a, complexOf_int16 b )+complexOf_int16_t mult_fun_complexOf_int16_t( complexOf_int16_t a, complexOf_int16_t b ) {- complexOf_int16 r;+ complexOf_int16_t r; r.re = a.re * b.re - a.im * b.im; r.im = a.im * b.re + a.re * b.im; return r; } -complexOf_int32 mult_fun_complexOf_int32( complexOf_int32 a, complexOf_int32 b )+complexOf_int32_t mult_fun_complexOf_int32_t( complexOf_int32_t a, complexOf_int32_t b ) {- complexOf_int32 r;+ complexOf_int32_t r; r.re = a.re * b.re - a.im * b.im; r.im = a.im * b.re + a.re * b.im; return r; } -complexOf_int64 mult_fun_complexOf_int64( complexOf_int64 a, complexOf_int64 b )+complexOf_int64_t mult_fun_complexOf_int64_t( complexOf_int64_t a, complexOf_int64_t b ) {- complexOf_int64 r;+ complexOf_int64_t r; r.re = a.re * b.re - a.im * b.im; r.im = a.im * b.re + a.re * b.im; return r; } -complexOf_uint8 mult_fun_complexOf_uint8( complexOf_uint8 a, complexOf_uint8 b )+complexOf_uint8_t mult_fun_complexOf_uint8_t( complexOf_uint8_t a, complexOf_uint8_t b ) {- complexOf_uint8 r;+ complexOf_uint8_t r; r.re = a.re * b.re - a.im * b.im; r.im = a.im * b.re + a.re * b.im; return r; } -complexOf_uint16 mult_fun_complexOf_uint16( complexOf_uint16 a, complexOf_uint16 b )+complexOf_uint16_t mult_fun_complexOf_uint16_t( complexOf_uint16_t a, complexOf_uint16_t b ) {- complexOf_uint16 r;+ complexOf_uint16_t r; r.re = a.re * b.re - a.im * b.im; r.im = a.im * b.re + a.re * b.im; return r; } -complexOf_uint32 mult_fun_complexOf_uint32( complexOf_uint32 a, complexOf_uint32 b )+complexOf_uint32_t mult_fun_complexOf_uint32_t( complexOf_uint32_t a, complexOf_uint32_t b ) {- complexOf_uint32 r;+ complexOf_uint32_t r; r.re = a.re * b.re - a.im * b.im; r.im = a.im * b.re + a.re * b.im; return r; } -complexOf_uint64 mult_fun_complexOf_uint64( complexOf_uint64 a, complexOf_uint64 b )+complexOf_uint64_t mult_fun_complexOf_uint64_t( complexOf_uint64_t a, complexOf_uint64_t b ) {- complexOf_uint64 r;+ complexOf_uint64_t r; r.re = a.re * b.re - a.im * b.im; r.im = a.im * b.re + a.re * b.im; return r;@@ -1226,66 +1254,72 @@ } +double complex logBase_fun_complexOf_double( double complex a, double complex b )+{+ return clogf(b) / clogf(a);+} -complexOf_int8 complex_fun_int8( int8_t re, int8_t im )+++complexOf_int8_t complex_fun_int8_t( int8_t re, int8_t im ) {- complexOf_int8 r;+ complexOf_int8_t r; r.re = re; r.im = im; return r; } -complexOf_int16 complex_fun_int16( int16_t re, int16_t im )+complexOf_int16_t complex_fun_int16_t( int16_t re, int16_t im ) {- complexOf_int16 r;+ complexOf_int16_t r; r.re = re; r.im = im; return r; } -complexOf_int32 complex_fun_int32( int32_t re, int32_t im )+complexOf_int32_t complex_fun_int32_t( int32_t re, int32_t im ) {- complexOf_int32 r;+ complexOf_int32_t r; r.re = re; r.im = im; return r; } -complexOf_int64 complex_fun_int64( int64_t re, int64_t im )+complexOf_int64_t complex_fun_int64_t( int64_t re, int64_t im ) {- complexOf_int64 r;+ complexOf_int64_t r; r.re = re; r.im = im; return r; } -complexOf_uint8 complex_fun_uint8( uint8_t re, uint8_t im )+complexOf_uint8_t complex_fun_uint8_t( uint8_t re, uint8_t im ) {- complexOf_uint8 r;+ complexOf_uint8_t r; r.re = re; r.im = im; return r; } -complexOf_uint16 complex_fun_uint16( uint16_t re, uint16_t im )+complexOf_uint16_t complex_fun_uint16_t( uint16_t re, uint16_t im ) {- complexOf_uint16 r;+ complexOf_uint16_t r; r.re = re; r.im = im; return r; } -complexOf_uint32 complex_fun_uint32( uint32_t re, uint32_t im )+complexOf_uint32_t complex_fun_uint32_t( uint32_t re, uint32_t im ) {- complexOf_uint32 r;+ complexOf_uint32_t r; r.re = re; r.im = im; return r; } -complexOf_uint64 complex_fun_uint64( uint64_t re, uint64_t im )+complexOf_uint64_t complex_fun_uint64_t( uint64_t re, uint64_t im ) {- complexOf_uint64 r;+ complexOf_uint64_t r; r.re = re; r.im = im; return r;@@ -1297,134 +1331,140 @@ } +double complex complex_fun_double( double re, double im )+{+ return ( re + im * I );+} -int8_t creal_fun_complexOf_int8( complexOf_int8 a )+++int8_t creal_fun_complexOf_int8_t( complexOf_int8_t a ) { return a.re; } -int16_t creal_fun_complexOf_int16( complexOf_int16 a )+int16_t creal_fun_complexOf_int16_t( complexOf_int16_t a ) { return a.re; } -int32_t creal_fun_complexOf_int32( complexOf_int32 a )+int32_t creal_fun_complexOf_int32_t( complexOf_int32_t a ) { return a.re; } -int64_t creal_fun_complexOf_int64( complexOf_int64 a )+int64_t creal_fun_complexOf_int64_t( complexOf_int64_t a ) { return a.re; } -uint8_t creal_fun_complexOf_uint8( complexOf_uint8 a )+uint8_t creal_fun_complexOf_uint8_t( complexOf_uint8_t a ) { return a.re; } -uint16_t creal_fun_complexOf_uint16( complexOf_uint16 a )+uint16_t creal_fun_complexOf_uint16_t( complexOf_uint16_t a ) { return a.re; } -uint32_t creal_fun_complexOf_uint32( complexOf_uint32 a )+uint32_t creal_fun_complexOf_uint32_t( complexOf_uint32_t a ) { return a.re; } -uint64_t creal_fun_complexOf_uint64( complexOf_uint64 a )+uint64_t creal_fun_complexOf_uint64_t( complexOf_uint64_t a ) { return a.re; } -int8_t cimag_fun_complexOf_int8( complexOf_int8 a )+int8_t cimag_fun_complexOf_int8_t( complexOf_int8_t a ) { return a.im; } -int16_t cimag_fun_complexOf_int16( complexOf_int16 a )+int16_t cimag_fun_complexOf_int16_t( complexOf_int16_t a ) { return a.im; } -int32_t cimag_fun_complexOf_int32( complexOf_int32 a )+int32_t cimag_fun_complexOf_int32_t( complexOf_int32_t a ) { return a.im; } -int64_t cimag_fun_complexOf_int64( complexOf_int64 a )+int64_t cimag_fun_complexOf_int64_t( complexOf_int64_t a ) { return a.im; } -uint8_t cimag_fun_complexOf_uint8( complexOf_uint8 a )+uint8_t cimag_fun_complexOf_uint8_t( complexOf_uint8_t a ) { return a.im; } -uint16_t cimag_fun_complexOf_uint16( complexOf_uint16 a )+uint16_t cimag_fun_complexOf_uint16_t( complexOf_uint16_t a ) { return a.im; } -uint32_t cimag_fun_complexOf_uint32( complexOf_uint32 a )+uint32_t cimag_fun_complexOf_uint32_t( complexOf_uint32_t a ) { return a.im; } -uint64_t cimag_fun_complexOf_uint64( complexOf_uint64 a )+uint64_t cimag_fun_complexOf_uint64_t( complexOf_uint64_t a ) { return a.im; } -complexOf_int8 conj_fun_complexOf_int8( complexOf_int8 a )+complexOf_int8_t conj_fun_complexOf_int8_t( complexOf_int8_t a ) { a.im = -a.im; return a; } -complexOf_int16 conj_fun_complexOf_int16( complexOf_int16 a )+complexOf_int16_t conj_fun_complexOf_int16_t( complexOf_int16_t a ) { a.im = -a.im; return a; } -complexOf_int32 conj_fun_complexOf_int32( complexOf_int32 a )+complexOf_int32_t conj_fun_complexOf_int32_t( complexOf_int32_t a ) { a.im = -a.im; return a; } -complexOf_int64 conj_fun_complexOf_int64( complexOf_int64 a )+complexOf_int64_t conj_fun_complexOf_int64_t( complexOf_int64_t a ) { a.im = -a.im; return a; } -complexOf_uint8 conj_fun_complexOf_uint8( complexOf_uint8 a )+complexOf_uint8_t conj_fun_complexOf_uint8_t( complexOf_uint8_t a ) { a.im = -a.im; return a; } -complexOf_uint16 conj_fun_complexOf_uint16( complexOf_uint16 a )+complexOf_uint16_t conj_fun_complexOf_uint16_t( complexOf_uint16_t a ) { a.im = -a.im; return a; } -complexOf_uint32 conj_fun_complexOf_uint32( complexOf_uint32 a )+complexOf_uint32_t conj_fun_complexOf_uint32_t( complexOf_uint32_t a ) { a.im = -a.im; return a; } -complexOf_uint64 conj_fun_complexOf_uint64( complexOf_uint64 a )+complexOf_uint64_t conj_fun_complexOf_uint64_t( complexOf_uint64_t a ) { a.im = -a.im; return a;@@ -1432,91 +1472,91 @@ -int8_t magnitude_fun_complexOf_int8( complexOf_int8 a )+int8_t magnitude_fun_complexOf_int8_t( complexOf_int8_t a ) { return lroundf(hypotf(a.re, a.im)); } -int16_t magnitude_fun_complexOf_int16( complexOf_int16 a )+int16_t magnitude_fun_complexOf_int16_t( complexOf_int16_t a ) { return lroundf(hypotf(a.re, a.im)); } -int32_t magnitude_fun_complexOf_int32( complexOf_int32 a )+int32_t magnitude_fun_complexOf_int32_t( complexOf_int32_t a ) { return lroundf(hypotf(a.re, a.im)); } -int64_t magnitude_fun_complexOf_int64( complexOf_int64 a )+int64_t magnitude_fun_complexOf_int64_t( complexOf_int64_t a ) { return llroundf(hypotf(a.re, a.im)); } -uint8_t magnitude_fun_complexOf_uint8( complexOf_uint8 a )+uint8_t magnitude_fun_complexOf_uint8_t( complexOf_uint8_t a ) { return lroundf(hypotf(a.re, a.im)); } -uint16_t magnitude_fun_complexOf_uint16( complexOf_uint16 a )+uint16_t magnitude_fun_complexOf_uint16_t( complexOf_uint16_t a ) { return lroundf(hypotf(a.re, a.im)); } -uint32_t magnitude_fun_complexOf_uint32( complexOf_uint32 a )+uint32_t magnitude_fun_complexOf_uint32_t( complexOf_uint32_t a ) { return lroundf(hypotf(a.re, a.im)); } -uint64_t magnitude_fun_complexOf_uint64( complexOf_uint64 a )+uint64_t magnitude_fun_complexOf_uint64_t( complexOf_uint64_t a ) { return llroundf(hypotf(a.re, a.im)); } -int8_t phase_fun_complexOf_int8( complexOf_int8 a )+int8_t phase_fun_complexOf_int8_t( complexOf_int8_t a ) { if (a.re == 0 && a.im == 0) return 0; else return lroundf(atan2f(a.im, a.re)); } -int16_t phase_fun_complexOf_int16( complexOf_int16 a )+int16_t phase_fun_complexOf_int16_t( complexOf_int16_t a ) { if (a.re == 0 && a.im == 0) return 0; else return lroundf(atan2f(a.im, a.re)); } -int32_t phase_fun_complexOf_int32( complexOf_int32 a )+int32_t phase_fun_complexOf_int32_t( complexOf_int32_t a ) { if (a.re == 0 && a.im == 0) return 0; else return lroundf(atan2f(a.im, a.re)); } -int64_t phase_fun_complexOf_int64( complexOf_int64 a )+int64_t phase_fun_complexOf_int64_t( complexOf_int64_t a ) { if (a.re == 0 && a.im == 0) return 0; else return llroundf(atan2f(a.im, a.re)); } -uint8_t phase_fun_complexOf_uint8( complexOf_uint8 a )+uint8_t phase_fun_complexOf_uint8_t( complexOf_uint8_t a ) { if (a.re == 0 && a.im == 0) return 0; else return lroundf(atan2f(a.im, a.re)); } -uint16_t phase_fun_complexOf_uint16( complexOf_uint16 a )+uint16_t phase_fun_complexOf_uint16_t( complexOf_uint16_t a ) { if (a.re == 0 && a.im == 0) return 0; else return lroundf(atan2f(a.im, a.re)); } -uint32_t phase_fun_complexOf_uint32( complexOf_uint32 a )+uint32_t phase_fun_complexOf_uint32_t( complexOf_uint32_t a ) { if (a.re == 0 && a.im == 0) return 0; else return lroundf(atan2f(a.im, a.re)); } -uint64_t phase_fun_complexOf_uint64( complexOf_uint64 a )+uint64_t phase_fun_complexOf_uint64_t( complexOf_uint64_t a ) { if (a.re == 0 && a.im == 0) return 0; else return llroundf(atan2f(a.im, a.re));@@ -1524,65 +1564,65 @@ -complexOf_int8 mkPolar_fun_int8( int8_t r, int8_t t )+complexOf_int8_t mkPolar_fun_int8_t( int8_t r, int8_t t ) {- complexOf_int8 a;+ complexOf_int8_t a; a.re = lroundf(r * cosf(t)); a.im = lroundf(r * sinf(t)); return a; } -complexOf_int16 mkPolar_fun_int16( int16_t r, int16_t t )+complexOf_int16_t mkPolar_fun_int16_t( int16_t r, int16_t t ) {- complexOf_int16 a;+ complexOf_int16_t a; a.re = lroundf(r * cosf(t)); a.im = lroundf(r * sinf(t)); return a; } -complexOf_int32 mkPolar_fun_int32( int32_t r, int32_t t )+complexOf_int32_t mkPolar_fun_int32_t( int32_t r, int32_t t ) {- complexOf_int32 a;+ complexOf_int32_t a; a.re = lroundf(r * cosf(t)); a.im = lroundf(r * sinf(t)); return a; } -complexOf_int64 mkPolar_fun_int64( int64_t r, int64_t t )+complexOf_int64_t mkPolar_fun_int64_t( int64_t r, int64_t t ) {- complexOf_int64 a;+ complexOf_int64_t a; a.re = llroundf(r * cosf(t)); a.im = llroundf(r * sinf(t)); return a; } -complexOf_uint8 mkPolar_fun_uint8( uint8_t r, uint8_t t )+complexOf_uint8_t mkPolar_fun_uint8_t( uint8_t r, uint8_t t ) {- complexOf_uint8 a;+ complexOf_uint8_t a; a.re = lroundf(r * cosf(t)); a.im = lroundf(r * sinf(t)); return a; } -complexOf_uint16 mkPolar_fun_uint16( uint16_t r, uint16_t t )+complexOf_uint16_t mkPolar_fun_uint16_t( uint16_t r, uint16_t t ) {- complexOf_uint16 a;+ complexOf_uint16_t a; a.re = lroundf(r * cosf(t)); a.im = lroundf(r * sinf(t)); return a; } -complexOf_uint32 mkPolar_fun_uint32( uint32_t r, uint32_t t )+complexOf_uint32_t mkPolar_fun_uint32_t( uint32_t r, uint32_t t ) {- complexOf_uint32 a;+ complexOf_uint32_t a; a.re = lroundf(r * cosf(t)); a.im = lroundf(r * sinf(t)); return a; } -complexOf_uint64 mkPolar_fun_uint64( uint64_t r, uint64_t t )+complexOf_uint64_t mkPolar_fun_uint64_t( uint64_t r, uint64_t t ) {- complexOf_uint64 a;+ complexOf_uint64_t a; a.re = llroundf(r * cosf(t)); a.im = llroundf(r * sinf(t)); return a;@@ -1594,66 +1634,72 @@ } +double complex mkPolar_fun_double( double r, double t )+{+ return r * cosf(t) + r * sinf(t) * I;+} -complexOf_int8 cis_fun_int8( int8_t t )+++complexOf_int8_t cis_fun_int8_t( int8_t t ) {- complexOf_int8 r;+ complexOf_int8_t r; r.re = lroundf(cosf(t)); r.im = lroundf(sinf(t)); return r; } -complexOf_int16 cis_fun_int16( int16_t t )+complexOf_int16_t cis_fun_int16_t( int16_t t ) {- complexOf_int16 r;+ complexOf_int16_t r; r.re = lroundf(cosf(t)); r.im = lroundf(sinf(t)); return r; } -complexOf_int32 cis_fun_int32( int32_t t )+complexOf_int32_t cis_fun_int32_t( int32_t t ) {- complexOf_int32 r;+ complexOf_int32_t r; r.re = lroundf(cosf(t)); r.im = lroundf(sinf(t)); return r; } -complexOf_int64 cis_fun_int64( int64_t t )+complexOf_int64_t cis_fun_int64_t( int64_t t ) {- complexOf_int64 r;+ complexOf_int64_t r; r.re = llroundf(cosf(t)); r.im = llroundf(sinf(t)); return r; } -complexOf_uint8 cis_fun_uint8( uint8_t t )+complexOf_uint8_t cis_fun_uint8_t( uint8_t t ) {- complexOf_uint8 r;+ complexOf_uint8_t r; r.re = lroundf(cosf(t)); r.im = lroundf(sinf(t)); return r; } -complexOf_uint16 cis_fun_uint16( uint16_t t )+complexOf_uint16_t cis_fun_uint16_t( uint16_t t ) {- complexOf_uint16 r;+ complexOf_uint16_t r; r.re = lroundf(cosf(t)); r.im = lroundf(sinf(t)); return r; } -complexOf_uint32 cis_fun_uint32( uint32_t t )+complexOf_uint32_t cis_fun_uint32_t( uint32_t t ) {- complexOf_uint32 r;+ complexOf_uint32_t r; r.re = lroundf(cosf(t)); r.im = lroundf(sinf(t)); return r; } -complexOf_uint64 cis_fun_uint64( uint64_t t )+complexOf_uint64_t cis_fun_uint64_t( uint64_t t ) {- complexOf_uint64 r;+ complexOf_uint64_t r; r.re = llroundf(cosf(t)); r.im = llroundf(sinf(t)); return r;@@ -1665,7 +1711,13 @@ } +double complex cis_fun_double( double t )+{+ return cosf(t) + sinf(t) * I;+} ++ /*--------------------------------------------------------------------------* * Trace functions * *--------------------------------------------------------------------------*/@@ -1748,7 +1800,7 @@ fclose(trace_log_file); } -void trace_int8( int8_t val, int32_t id )+void trace_int8_t( int8_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1756,7 +1808,7 @@ fflush(trace_log_file); } -void trace_int16( int16_t val, int32_t id )+void trace_int16_t( int16_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1764,7 +1816,7 @@ fflush(trace_log_file); } -void trace_int32( int32_t val, int32_t id )+void trace_int32_t( int32_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1772,7 +1824,7 @@ fflush(trace_log_file); } -void trace_int64( int64_t val, int32_t id )+void trace_int64_t( int64_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1780,7 +1832,7 @@ fflush(trace_log_file); } -void trace_uint8( uint8_t val, int32_t id )+void trace_uint8_t( uint8_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1788,7 +1840,7 @@ fflush(trace_log_file); } -void trace_uint16( uint16_t val, int32_t id )+void trace_uint16_t( uint16_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1796,7 +1848,7 @@ fflush(trace_log_file); } -void trace_uint32( uint32_t val, int32_t id )+void trace_uint32_t( uint32_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1804,7 +1856,7 @@ fflush(trace_log_file); } -void trace_uint64( uint64_t val, int32_t id )+void trace_uint64_t( uint64_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1820,15 +1872,23 @@ fflush(trace_log_file); } -void trace_complexOf_int8( complexOf_int8 val, int32_t id )+void trace_double( double val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);+ fprintf(trace_log_file, "id=%d, time=%s, value=%f\n", id, timestr, val);+ fflush(trace_log_file);+}++void trace_complexOf_int8_t( complexOf_int8_t val, int32_t id )+{+ char timestr [80];+ elapsedTimeString(timestr); fprintf(trace_log_file, "id=%d, time=%s, value=%d+%d*I\n", id, timestr, val.re, val.im); fflush(trace_log_file); } -void trace_complexOf_int16( complexOf_int16 val, int32_t id )+void trace_complexOf_int16_t( complexOf_int16_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1836,7 +1896,7 @@ fflush(trace_log_file); } -void trace_complexOf_int32( complexOf_int32 val, int32_t id )+void trace_complexOf_int32_t( complexOf_int32_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1844,7 +1904,7 @@ fflush(trace_log_file); } -void trace_complexOf_int64( complexOf_int64 val, int32_t id )+void trace_complexOf_int64_t( complexOf_int64_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1852,7 +1912,7 @@ fflush(trace_log_file); } -void trace_complexOf_uint8( complexOf_uint8 val, int32_t id )+void trace_complexOf_uint8_t( complexOf_uint8_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1860,7 +1920,7 @@ fflush(trace_log_file); } -void trace_complexOf_uint16( complexOf_uint16 val, int32_t id )+void trace_complexOf_uint16_t( complexOf_uint16_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1868,7 +1928,7 @@ fflush(trace_log_file); } -void trace_complexOf_uint32( complexOf_uint32 val, int32_t id )+void trace_complexOf_uint32_t( complexOf_uint32_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1876,7 +1936,7 @@ fflush(trace_log_file); } -void trace_complexOf_uint64( complexOf_uint64 val, int32_t id )+void trace_complexOf_uint64_t( complexOf_uint64_t val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);@@ -1885,6 +1945,14 @@ } void trace_complexOf_float( float complex val, int32_t id )+{+ char timestr [80];+ elapsedTimeString(timestr);+ fprintf(trace_log_file, "id=%d, time=%s, value=%f+%f*I\n", id, timestr, creal(val), cimag(val));+ fflush(trace_log_file);+}++void trace_complexOf_double( double complex val, int32_t id ) { char timestr [80]; elapsedTimeString(timestr);
lib/Feldspar/C/feldspar_c99.h view
@@ -33,324 +33,334 @@ #include <complex.h> +int feldspar_c99_hook(void); #define min(X, Y) ((X) < (Y) ? (X) : (Y)) #define max(X, Y) ((X) > (Y) ? (X) : (Y)) -int8_t pow_fun_int8( int8_t, int8_t );-int16_t pow_fun_int16( int16_t, int16_t );-int32_t pow_fun_int32( int32_t, int32_t );-int64_t pow_fun_int64( int64_t, int64_t );-uint8_t pow_fun_uint8( uint8_t, uint8_t );-uint16_t pow_fun_uint16( uint16_t, uint16_t );-uint32_t pow_fun_uint32( uint32_t, uint32_t );-uint64_t pow_fun_uint64( uint64_t, uint64_t );+int8_t pow_fun_int8_t( int8_t, int8_t );+int16_t pow_fun_int16_t( int16_t, int16_t );+int32_t pow_fun_int32_t( int32_t, int32_t );+int64_t pow_fun_int64_t( int64_t, int64_t );+uint8_t pow_fun_uint8_t( uint8_t, uint8_t );+uint16_t pow_fun_uint16_t( uint16_t, uint16_t );+uint32_t pow_fun_uint32_t( uint32_t, uint32_t );+uint64_t pow_fun_uint64_t( uint64_t, uint64_t ); -int8_t abs_fun_int8( int8_t );-int16_t abs_fun_int16( int16_t );-int32_t abs_fun_int32( int32_t );-int64_t abs_fun_int64( int64_t );+int8_t abs_fun_int8_t( int8_t );+int16_t abs_fun_int16_t( int16_t );+int32_t abs_fun_int32_t( int32_t );+int64_t abs_fun_int64_t( int64_t ); -int8_t signum_fun_int8( int8_t );-int16_t signum_fun_int16( int16_t );-int32_t signum_fun_int32( int32_t );-int64_t signum_fun_int64( int64_t );-uint8_t signum_fun_uint8( uint8_t );-uint16_t signum_fun_uint16( uint16_t );-uint32_t signum_fun_uint32( uint32_t );-uint64_t signum_fun_uint64( uint64_t );+int8_t signum_fun_int8_t( int8_t );+int16_t signum_fun_int16_t( int16_t );+int32_t signum_fun_int32_t( int32_t );+int64_t signum_fun_int64_t( int64_t );+uint8_t signum_fun_uint8_t( uint8_t );+uint16_t signum_fun_uint16_t( uint16_t );+uint32_t signum_fun_uint32_t( uint32_t );+uint64_t signum_fun_uint64_t( uint64_t ); float signum_fun_float( float );+double signum_fun_double( double ); float logBase_fun_float( float, float );+double logBase_fun_double( double, double ); -int8_t setBit_fun_int8( int8_t, uint32_t );-int16_t setBit_fun_int16( int16_t, uint32_t );-int32_t setBit_fun_int32( int32_t, uint32_t );-int64_t setBit_fun_int64( int64_t, uint32_t );-uint8_t setBit_fun_uint8( uint8_t, uint32_t );-uint16_t setBit_fun_uint16( uint16_t, uint32_t );-uint32_t setBit_fun_uint32( uint32_t, uint32_t );-uint64_t setBit_fun_uint64( uint64_t, uint32_t );+int8_t setBit_fun_int8_t( int8_t, uint32_t );+int16_t setBit_fun_int16_t( int16_t, uint32_t );+int32_t setBit_fun_int32_t( int32_t, uint32_t );+int64_t setBit_fun_int64_t( int64_t, uint32_t );+uint8_t setBit_fun_uint8_t( uint8_t, uint32_t );+uint16_t setBit_fun_uint16_t( uint16_t, uint32_t );+uint32_t setBit_fun_uint32_t( uint32_t, uint32_t );+uint64_t setBit_fun_uint64_t( uint64_t, uint32_t ); -int8_t clearBit_fun_int8( int8_t, uint32_t );-int16_t clearBit_fun_int16( int16_t, uint32_t );-int32_t clearBit_fun_int32( int32_t, uint32_t );-int64_t clearBit_fun_int64( int64_t, uint32_t );-uint8_t clearBit_fun_uint8( uint8_t, uint32_t );-uint16_t clearBit_fun_uint16( uint16_t, uint32_t );-uint32_t clearBit_fun_uint32( uint32_t, uint32_t );-uint64_t clearBit_fun_uint64( uint64_t, uint32_t );+int8_t clearBit_fun_int8_t( int8_t, uint32_t );+int16_t clearBit_fun_int16_t( int16_t, uint32_t );+int32_t clearBit_fun_int32_t( int32_t, uint32_t );+int64_t clearBit_fun_int64_t( int64_t, uint32_t );+uint8_t clearBit_fun_uint8_t( uint8_t, uint32_t );+uint16_t clearBit_fun_uint16_t( uint16_t, uint32_t );+uint32_t clearBit_fun_uint32_t( uint32_t, uint32_t );+uint64_t clearBit_fun_uint64_t( uint64_t, uint32_t ); -int8_t complementBit_fun_int8( int8_t, uint32_t );-int16_t complementBit_fun_int16( int16_t, uint32_t );-int32_t complementBit_fun_int32( int32_t, uint32_t );-int64_t complementBit_fun_int64( int64_t, uint32_t );-uint8_t complementBit_fun_uint8( uint8_t, uint32_t );-uint16_t complementBit_fun_uint16( uint16_t, uint32_t );-uint32_t complementBit_fun_uint32( uint32_t, uint32_t );-uint64_t complementBit_fun_uint64( uint64_t, uint32_t );+int8_t complementBit_fun_int8_t( int8_t, uint32_t );+int16_t complementBit_fun_int16_t( int16_t, uint32_t );+int32_t complementBit_fun_int32_t( int32_t, uint32_t );+int64_t complementBit_fun_int64_t( int64_t, uint32_t );+uint8_t complementBit_fun_uint8_t( uint8_t, uint32_t );+uint16_t complementBit_fun_uint16_t( uint16_t, uint32_t );+uint32_t complementBit_fun_uint32_t( uint32_t, uint32_t );+uint64_t complementBit_fun_uint64_t( uint64_t, uint32_t ); -int testBit_fun_int8( int8_t, uint32_t );-int testBit_fun_int16( int16_t, uint32_t );-int testBit_fun_int32( int32_t, uint32_t );-int testBit_fun_int64( int64_t, uint32_t );-int testBit_fun_uint8( uint8_t, uint32_t );-int testBit_fun_uint16( uint16_t, uint32_t );-int testBit_fun_uint32( uint32_t, uint32_t );-int testBit_fun_uint64( uint64_t, uint32_t );+int testBit_fun_int8_t( int8_t, uint32_t );+int testBit_fun_int16_t( int16_t, uint32_t );+int testBit_fun_int32_t( int32_t, uint32_t );+int testBit_fun_int64_t( int64_t, uint32_t );+int testBit_fun_uint8_t( uint8_t, uint32_t );+int testBit_fun_uint16_t( uint16_t, uint32_t );+int testBit_fun_uint32_t( uint32_t, uint32_t );+int testBit_fun_uint64_t( uint64_t, uint32_t ); -int8_t rotateL_fun_int8( int8_t, int32_t );-int16_t rotateL_fun_int16( int16_t, int32_t );-int32_t rotateL_fun_int32( int32_t, int32_t );-int64_t rotateL_fun_int64( int64_t, int32_t );-uint8_t rotateL_fun_uint8( uint8_t, int32_t );-uint16_t rotateL_fun_uint16( uint16_t, int32_t );-uint32_t rotateL_fun_uint32( uint32_t, int32_t );-uint64_t rotateL_fun_uint64( uint64_t, int32_t );+int8_t rotateL_fun_int8_t( int8_t, int32_t );+int16_t rotateL_fun_int16_t( int16_t, int32_t );+int32_t rotateL_fun_int32_t( int32_t, int32_t );+int64_t rotateL_fun_int64_t( int64_t, int32_t );+uint8_t rotateL_fun_uint8_t( uint8_t, int32_t );+uint16_t rotateL_fun_uint16_t( uint16_t, int32_t );+uint32_t rotateL_fun_uint32_t( uint32_t, int32_t );+uint64_t rotateL_fun_uint64_t( uint64_t, int32_t ); -int8_t rotateR_fun_int8( int8_t, int32_t );-int16_t rotateR_fun_int16( int16_t, int32_t );-int32_t rotateR_fun_int32( int32_t, int32_t );-int64_t rotateR_fun_int64( int64_t, int32_t );-uint8_t rotateR_fun_uint8( uint8_t, int32_t );-uint16_t rotateR_fun_uint16( uint16_t, int32_t );-uint32_t rotateR_fun_uint32( uint32_t, int32_t );-uint64_t rotateR_fun_uint64( uint64_t, int32_t );+int8_t rotateR_fun_int8_t( int8_t, int32_t );+int16_t rotateR_fun_int16_t( int16_t, int32_t );+int32_t rotateR_fun_int32_t( int32_t, int32_t );+int64_t rotateR_fun_int64_t( int64_t, int32_t );+uint8_t rotateR_fun_uint8_t( uint8_t, int32_t );+uint16_t rotateR_fun_uint16_t( uint16_t, int32_t );+uint32_t rotateR_fun_uint32_t( uint32_t, int32_t );+uint64_t rotateR_fun_uint64_t( uint64_t, int32_t ); -int8_t reverseBits_fun_int8( int8_t );-int16_t reverseBits_fun_int16( int16_t );-int32_t reverseBits_fun_int32( int32_t );-int64_t reverseBits_fun_int64( int64_t );-uint8_t reverseBits_fun_uint8( uint8_t );-uint16_t reverseBits_fun_uint16( uint16_t );-uint32_t reverseBits_fun_uint32( uint32_t );-uint64_t reverseBits_fun_uint64( uint64_t );+int8_t reverseBits_fun_int8_t( int8_t );+int16_t reverseBits_fun_int16_t( int16_t );+int32_t reverseBits_fun_int32_t( int32_t );+int64_t reverseBits_fun_int64_t( int64_t );+uint8_t reverseBits_fun_uint8_t( uint8_t );+uint16_t reverseBits_fun_uint16_t( uint16_t );+uint32_t reverseBits_fun_uint32_t( uint32_t );+uint64_t reverseBits_fun_uint64_t( uint64_t ); -uint32_t bitScan_fun_int8( int8_t );-uint32_t bitScan_fun_int16( int16_t );-uint32_t bitScan_fun_int32( int32_t );-uint32_t bitScan_fun_int64( int64_t );-uint32_t bitScan_fun_uint8( uint8_t );-uint32_t bitScan_fun_uint16( uint16_t );-uint32_t bitScan_fun_uint32( uint32_t );-uint32_t bitScan_fun_uint64( uint64_t );+uint32_t bitScan_fun_int8_t( int8_t );+uint32_t bitScan_fun_int16_t( int16_t );+uint32_t bitScan_fun_int32_t( int32_t );+uint32_t bitScan_fun_int64_t( int64_t );+uint32_t bitScan_fun_uint8_t( uint8_t );+uint32_t bitScan_fun_uint16_t( uint16_t );+uint32_t bitScan_fun_uint32_t( uint32_t );+uint32_t bitScan_fun_uint64_t( uint64_t ); -uint32_t bitCount_fun_int8( int8_t );-uint32_t bitCount_fun_int16( int16_t );-uint32_t bitCount_fun_int32( int32_t );-uint32_t bitCount_fun_int64( int64_t );-uint32_t bitCount_fun_uint8( uint8_t );-uint32_t bitCount_fun_uint16( uint16_t );-uint32_t bitCount_fun_uint32( uint32_t );-uint32_t bitCount_fun_uint64( uint64_t );+uint32_t bitCount_fun_int8_t( int8_t );+uint32_t bitCount_fun_int16_t( int16_t );+uint32_t bitCount_fun_int32_t( int32_t );+uint32_t bitCount_fun_int64_t( int64_t );+uint32_t bitCount_fun_uint8_t( uint8_t );+uint32_t bitCount_fun_uint16_t( uint16_t );+uint32_t bitCount_fun_uint32_t( uint32_t );+uint32_t bitCount_fun_uint64_t( uint64_t ); typedef struct { int8_t re; int8_t im;-} complexOf_int8;+} complexOf_int8_t; typedef struct { int16_t re; int16_t im;-} complexOf_int16;+} complexOf_int16_t; typedef struct { int32_t re; int32_t im;-} complexOf_int32;+} complexOf_int32_t; typedef struct { int64_t re; int64_t im;-} complexOf_int64;+} complexOf_int64_t; typedef struct { uint8_t re; uint8_t im;-} complexOf_uint8;+} complexOf_uint8_t; typedef struct { uint16_t re; uint16_t im;-} complexOf_uint16;+} complexOf_uint16_t; typedef struct { uint32_t re; uint32_t im;-} complexOf_uint32;+} complexOf_uint32_t; typedef struct { uint64_t re; uint64_t im;-} complexOf_uint64;+} complexOf_uint64_t; -int equal_fun_complexOf_int8( complexOf_int8, complexOf_int8 );-int equal_fun_complexOf_int16( complexOf_int16, complexOf_int16 );-int equal_fun_complexOf_int32( complexOf_int32, complexOf_int32 );-int equal_fun_complexOf_int64( complexOf_int64, complexOf_int64 );-int equal_fun_complexOf_uint8( complexOf_uint8, complexOf_uint8 );-int equal_fun_complexOf_uint16( complexOf_uint16, complexOf_uint16 );-int equal_fun_complexOf_uint32( complexOf_uint32, complexOf_uint32 );-int equal_fun_complexOf_uint64( complexOf_uint64, complexOf_uint64 );+int equal_fun_complexOf_int8_t( complexOf_int8_t, complexOf_int8_t );+int equal_fun_complexOf_int16_t( complexOf_int16_t, complexOf_int16_t );+int equal_fun_complexOf_int32_t( complexOf_int32_t, complexOf_int32_t );+int equal_fun_complexOf_int64_t( complexOf_int64_t, complexOf_int64_t );+int equal_fun_complexOf_uint8_t( complexOf_uint8_t, complexOf_uint8_t );+int equal_fun_complexOf_uint16_t( complexOf_uint16_t, complexOf_uint16_t );+int equal_fun_complexOf_uint32_t( complexOf_uint32_t, complexOf_uint32_t );+int equal_fun_complexOf_uint64_t( complexOf_uint64_t, complexOf_uint64_t ); -complexOf_int8 negate_fun_complexOf_int8( complexOf_int8 );-complexOf_int16 negate_fun_complexOf_int16( complexOf_int16 );-complexOf_int32 negate_fun_complexOf_int32( complexOf_int32 );-complexOf_int64 negate_fun_complexOf_int64( complexOf_int64 );-complexOf_uint8 negate_fun_complexOf_uint8( complexOf_uint8 );-complexOf_uint16 negate_fun_complexOf_uint16( complexOf_uint16 );-complexOf_uint32 negate_fun_complexOf_uint32( complexOf_uint32 );-complexOf_uint64 negate_fun_complexOf_uint64( complexOf_uint64 );+complexOf_int8_t negate_fun_complexOf_int8_t( complexOf_int8_t );+complexOf_int16_t negate_fun_complexOf_int16_t( complexOf_int16_t );+complexOf_int32_t negate_fun_complexOf_int32_t( complexOf_int32_t );+complexOf_int64_t negate_fun_complexOf_int64_t( complexOf_int64_t );+complexOf_uint8_t negate_fun_complexOf_uint8_t( complexOf_uint8_t );+complexOf_uint16_t negate_fun_complexOf_uint16_t( complexOf_uint16_t );+complexOf_uint32_t negate_fun_complexOf_uint32_t( complexOf_uint32_t );+complexOf_uint64_t negate_fun_complexOf_uint64_t( complexOf_uint64_t ); -complexOf_int8 abs_fun_complexOf_int8( complexOf_int8 );-complexOf_int16 abs_fun_complexOf_int16( complexOf_int16 );-complexOf_int32 abs_fun_complexOf_int32( complexOf_int32 );-complexOf_int64 abs_fun_complexOf_int64( complexOf_int64 );-complexOf_uint8 abs_fun_complexOf_uint8( complexOf_uint8 );-complexOf_uint16 abs_fun_complexOf_uint16( complexOf_uint16 );-complexOf_uint32 abs_fun_complexOf_uint32( complexOf_uint32 );-complexOf_uint64 abs_fun_complexOf_uint64( complexOf_uint64 );+complexOf_int8_t abs_fun_complexOf_int8_t( complexOf_int8_t );+complexOf_int16_t abs_fun_complexOf_int16_t( complexOf_int16_t );+complexOf_int32_t abs_fun_complexOf_int32_t( complexOf_int32_t );+complexOf_int64_t abs_fun_complexOf_int64_t( complexOf_int64_t );+complexOf_uint8_t abs_fun_complexOf_uint8_t( complexOf_uint8_t );+complexOf_uint16_t abs_fun_complexOf_uint16_t( complexOf_uint16_t );+complexOf_uint32_t abs_fun_complexOf_uint32_t( complexOf_uint32_t );+complexOf_uint64_t abs_fun_complexOf_uint64_t( complexOf_uint64_t ); -complexOf_int8 signum_fun_complexOf_int8( complexOf_int8 );-complexOf_int16 signum_fun_complexOf_int16( complexOf_int16 );-complexOf_int32 signum_fun_complexOf_int32( complexOf_int32 );-complexOf_int64 signum_fun_complexOf_int64( complexOf_int64 );-complexOf_uint8 signum_fun_complexOf_uint8( complexOf_uint8 );-complexOf_uint16 signum_fun_complexOf_uint16( complexOf_uint16 );-complexOf_uint32 signum_fun_complexOf_uint32( complexOf_uint32 );-complexOf_uint64 signum_fun_complexOf_uint64( complexOf_uint64 );+complexOf_int8_t signum_fun_complexOf_int8_t( complexOf_int8_t );+complexOf_int16_t signum_fun_complexOf_int16_t( complexOf_int16_t );+complexOf_int32_t signum_fun_complexOf_int32_t( complexOf_int32_t );+complexOf_int64_t signum_fun_complexOf_int64_t( complexOf_int64_t );+complexOf_uint8_t signum_fun_complexOf_uint8_t( complexOf_uint8_t );+complexOf_uint16_t signum_fun_complexOf_uint16_t( complexOf_uint16_t );+complexOf_uint32_t signum_fun_complexOf_uint32_t( complexOf_uint32_t );+complexOf_uint64_t signum_fun_complexOf_uint64_t( complexOf_uint64_t ); float complex signum_fun_complexOf_float( float complex );+double complex signum_fun_complexOf_double( double complex ); -complexOf_int8 add_fun_complexOf_int8( complexOf_int8, complexOf_int8 );-complexOf_int16 add_fun_complexOf_int16( complexOf_int16, complexOf_int16 );-complexOf_int32 add_fun_complexOf_int32( complexOf_int32, complexOf_int32 );-complexOf_int64 add_fun_complexOf_int64( complexOf_int64, complexOf_int64 );-complexOf_uint8 add_fun_complexOf_uint8( complexOf_uint8, complexOf_uint8 );-complexOf_uint16 add_fun_complexOf_uint16( complexOf_uint16, complexOf_uint16 );-complexOf_uint32 add_fun_complexOf_uint32( complexOf_uint32, complexOf_uint32 );-complexOf_uint64 add_fun_complexOf_uint64( complexOf_uint64, complexOf_uint64 );+complexOf_int8_t add_fun_complexOf_int8_t( complexOf_int8_t, complexOf_int8_t );+complexOf_int16_t add_fun_complexOf_int16_t( complexOf_int16_t, complexOf_int16_t );+complexOf_int32_t add_fun_complexOf_int32_t( complexOf_int32_t, complexOf_int32_t );+complexOf_int64_t add_fun_complexOf_int64_t( complexOf_int64_t, complexOf_int64_t );+complexOf_uint8_t add_fun_complexOf_uint8_t( complexOf_uint8_t, complexOf_uint8_t );+complexOf_uint16_t add_fun_complexOf_uint16_t( complexOf_uint16_t, complexOf_uint16_t );+complexOf_uint32_t add_fun_complexOf_uint32_t( complexOf_uint32_t, complexOf_uint32_t );+complexOf_uint64_t add_fun_complexOf_uint64_t( complexOf_uint64_t, complexOf_uint64_t ); -complexOf_int8 sub_fun_complexOf_int8( complexOf_int8, complexOf_int8 );-complexOf_int16 sub_fun_complexOf_int16( complexOf_int16, complexOf_int16 );-complexOf_int32 sub_fun_complexOf_int32( complexOf_int32, complexOf_int32 );-complexOf_int64 sub_fun_complexOf_int64( complexOf_int64, complexOf_int64 );-complexOf_uint8 sub_fun_complexOf_uint8( complexOf_uint8, complexOf_uint8 );-complexOf_uint16 sub_fun_complexOf_uint16( complexOf_uint16, complexOf_uint16 );-complexOf_uint32 sub_fun_complexOf_uint32( complexOf_uint32, complexOf_uint32 );-complexOf_uint64 sub_fun_complexOf_uint64( complexOf_uint64, complexOf_uint64 );+complexOf_int8_t sub_fun_complexOf_int8_t( complexOf_int8_t, complexOf_int8_t );+complexOf_int16_t sub_fun_complexOf_int16_t( complexOf_int16_t, complexOf_int16_t );+complexOf_int32_t sub_fun_complexOf_int32_t( complexOf_int32_t, complexOf_int32_t );+complexOf_int64_t sub_fun_complexOf_int64_t( complexOf_int64_t, complexOf_int64_t );+complexOf_uint8_t sub_fun_complexOf_uint8_t( complexOf_uint8_t, complexOf_uint8_t );+complexOf_uint16_t sub_fun_complexOf_uint16_t( complexOf_uint16_t, complexOf_uint16_t );+complexOf_uint32_t sub_fun_complexOf_uint32_t( complexOf_uint32_t, complexOf_uint32_t );+complexOf_uint64_t sub_fun_complexOf_uint64_t( complexOf_uint64_t, complexOf_uint64_t ); -complexOf_int8 mult_fun_complexOf_int8( complexOf_int8, complexOf_int8 );-complexOf_int16 mult_fun_complexOf_int16( complexOf_int16, complexOf_int16 );-complexOf_int32 mult_fun_complexOf_int32( complexOf_int32, complexOf_int32 );-complexOf_int64 mult_fun_complexOf_int64( complexOf_int64, complexOf_int64 );-complexOf_uint8 mult_fun_complexOf_uint8( complexOf_uint8, complexOf_uint8 );-complexOf_uint16 mult_fun_complexOf_uint16( complexOf_uint16, complexOf_uint16 );-complexOf_uint32 mult_fun_complexOf_uint32( complexOf_uint32, complexOf_uint32 );-complexOf_uint64 mult_fun_complexOf_uint64( complexOf_uint64, complexOf_uint64 );+complexOf_int8_t mult_fun_complexOf_int8_t( complexOf_int8_t, complexOf_int8_t );+complexOf_int16_t mult_fun_complexOf_int16_t( complexOf_int16_t, complexOf_int16_t );+complexOf_int32_t mult_fun_complexOf_int32_t( complexOf_int32_t, complexOf_int32_t );+complexOf_int64_t mult_fun_complexOf_int64_t( complexOf_int64_t, complexOf_int64_t );+complexOf_uint8_t mult_fun_complexOf_uint8_t( complexOf_uint8_t, complexOf_uint8_t );+complexOf_uint16_t mult_fun_complexOf_uint16_t( complexOf_uint16_t, complexOf_uint16_t );+complexOf_uint32_t mult_fun_complexOf_uint32_t( complexOf_uint32_t, complexOf_uint32_t );+complexOf_uint64_t mult_fun_complexOf_uint64_t( complexOf_uint64_t, complexOf_uint64_t ); float complex logBase_fun_complexOf_float( float complex, float complex );+double complex logBase_fun_complexOf_double( double complex, double complex ); -complexOf_int8 complex_fun_int8( int8_t, int8_t );-complexOf_int16 complex_fun_int16( int16_t, int16_t );-complexOf_int32 complex_fun_int32( int32_t, int32_t );-complexOf_int64 complex_fun_int64( int64_t, int64_t );-complexOf_uint8 complex_fun_uint8( uint8_t, uint8_t );-complexOf_uint16 complex_fun_uint16( uint16_t, uint16_t );-complexOf_uint32 complex_fun_uint32( uint32_t, uint32_t );-complexOf_uint64 complex_fun_uint64( uint64_t, uint64_t );+complexOf_int8_t complex_fun_int8_t( int8_t, int8_t );+complexOf_int16_t complex_fun_int16_t( int16_t, int16_t );+complexOf_int32_t complex_fun_int32_t( int32_t, int32_t );+complexOf_int64_t complex_fun_int64_t( int64_t, int64_t );+complexOf_uint8_t complex_fun_uint8_t( uint8_t, uint8_t );+complexOf_uint16_t complex_fun_uint16_t( uint16_t, uint16_t );+complexOf_uint32_t complex_fun_uint32_t( uint32_t, uint32_t );+complexOf_uint64_t complex_fun_uint64_t( uint64_t, uint64_t ); float complex complex_fun_float( float, float );+double complex complex_fun_double( double, double ); -int8_t creal_fun_complexOf_int8( complexOf_int8 );-int16_t creal_fun_complexOf_int16( complexOf_int16 );-int32_t creal_fun_complexOf_int32( complexOf_int32 );-int64_t creal_fun_complexOf_int64( complexOf_int64 );-uint8_t creal_fun_complexOf_uint8( complexOf_uint8 );-uint16_t creal_fun_complexOf_uint16( complexOf_uint16 );-uint32_t creal_fun_complexOf_uint32( complexOf_uint32 );-uint64_t creal_fun_complexOf_uint64( complexOf_uint64 );+int8_t creal_fun_complexOf_int8_t( complexOf_int8_t );+int16_t creal_fun_complexOf_int16_t( complexOf_int16_t );+int32_t creal_fun_complexOf_int32_t( complexOf_int32_t );+int64_t creal_fun_complexOf_int64_t( complexOf_int64_t );+uint8_t creal_fun_complexOf_uint8_t( complexOf_uint8_t );+uint16_t creal_fun_complexOf_uint16_t( complexOf_uint16_t );+uint32_t creal_fun_complexOf_uint32_t( complexOf_uint32_t );+uint64_t creal_fun_complexOf_uint64_t( complexOf_uint64_t ); -int8_t cimag_fun_complexOf_int8( complexOf_int8 );-int16_t cimag_fun_complexOf_int16( complexOf_int16 );-int32_t cimag_fun_complexOf_int32( complexOf_int32 );-int64_t cimag_fun_complexOf_int64( complexOf_int64 );-uint8_t cimag_fun_complexOf_uint8( complexOf_uint8 );-uint16_t cimag_fun_complexOf_uint16( complexOf_uint16 );-uint32_t cimag_fun_complexOf_uint32( complexOf_uint32 );-uint64_t cimag_fun_complexOf_uint64( complexOf_uint64 );+int8_t cimag_fun_complexOf_int8_t( complexOf_int8_t );+int16_t cimag_fun_complexOf_int16_t( complexOf_int16_t );+int32_t cimag_fun_complexOf_int32_t( complexOf_int32_t );+int64_t cimag_fun_complexOf_int64_t( complexOf_int64_t );+uint8_t cimag_fun_complexOf_uint8_t( complexOf_uint8_t );+uint16_t cimag_fun_complexOf_uint16_t( complexOf_uint16_t );+uint32_t cimag_fun_complexOf_uint32_t( complexOf_uint32_t );+uint64_t cimag_fun_complexOf_uint64_t( complexOf_uint64_t ); -complexOf_int8 conj_fun_complexOf_int8( complexOf_int8 );-complexOf_int16 conj_fun_complexOf_int16( complexOf_int16 );-complexOf_int32 conj_fun_complexOf_int32( complexOf_int32 );-complexOf_int64 conj_fun_complexOf_int64( complexOf_int64 );-complexOf_uint8 conj_fun_complexOf_uint8( complexOf_uint8 );-complexOf_uint16 conj_fun_complexOf_uint16( complexOf_uint16 );-complexOf_uint32 conj_fun_complexOf_uint32( complexOf_uint32 );-complexOf_uint64 conj_fun_complexOf_uint64( complexOf_uint64 );+complexOf_int8_t conj_fun_complexOf_int8_t( complexOf_int8_t );+complexOf_int16_t conj_fun_complexOf_int16_t( complexOf_int16_t );+complexOf_int32_t conj_fun_complexOf_int32_t( complexOf_int32_t );+complexOf_int64_t conj_fun_complexOf_int64_t( complexOf_int64_t );+complexOf_uint8_t conj_fun_complexOf_uint8_t( complexOf_uint8_t );+complexOf_uint16_t conj_fun_complexOf_uint16_t( complexOf_uint16_t );+complexOf_uint32_t conj_fun_complexOf_uint32_t( complexOf_uint32_t );+complexOf_uint64_t conj_fun_complexOf_uint64_t( complexOf_uint64_t ); -int8_t magnitude_fun_complexOf_int8( complexOf_int8 );-int16_t magnitude_fun_complexOf_int16( complexOf_int16 );-int32_t magnitude_fun_complexOf_int32( complexOf_int32 );-int64_t magnitude_fun_complexOf_int64( complexOf_int64 );-uint8_t magnitude_fun_complexOf_uint8( complexOf_uint8 );-uint16_t magnitude_fun_complexOf_uint16( complexOf_uint16 );-uint32_t magnitude_fun_complexOf_uint32( complexOf_uint32 );-uint64_t magnitude_fun_complexOf_uint64( complexOf_uint64 );+int8_t magnitude_fun_complexOf_int8_t( complexOf_int8_t );+int16_t magnitude_fun_complexOf_int16_t( complexOf_int16_t );+int32_t magnitude_fun_complexOf_int32_t( complexOf_int32_t );+int64_t magnitude_fun_complexOf_int64_t( complexOf_int64_t );+uint8_t magnitude_fun_complexOf_uint8_t( complexOf_uint8_t );+uint16_t magnitude_fun_complexOf_uint16_t( complexOf_uint16_t );+uint32_t magnitude_fun_complexOf_uint32_t( complexOf_uint32_t );+uint64_t magnitude_fun_complexOf_uint64_t( complexOf_uint64_t ); -int8_t phase_fun_complexOf_int8( complexOf_int8 );-int16_t phase_fun_complexOf_int16( complexOf_int16 );-int32_t phase_fun_complexOf_int32( complexOf_int32 );-int64_t phase_fun_complexOf_int64( complexOf_int64 );-uint8_t phase_fun_complexOf_uint8( complexOf_uint8 );-uint16_t phase_fun_complexOf_uint16( complexOf_uint16 );-uint32_t phase_fun_complexOf_uint32( complexOf_uint32 );-uint64_t phase_fun_complexOf_uint64( complexOf_uint64 );+int8_t phase_fun_complexOf_int8_t( complexOf_int8_t );+int16_t phase_fun_complexOf_int16_t( complexOf_int16_t );+int32_t phase_fun_complexOf_int32_t( complexOf_int32_t );+int64_t phase_fun_complexOf_int64_t( complexOf_int64_t );+uint8_t phase_fun_complexOf_uint8_t( complexOf_uint8_t );+uint16_t phase_fun_complexOf_uint16_t( complexOf_uint16_t );+uint32_t phase_fun_complexOf_uint32_t( complexOf_uint32_t );+uint64_t phase_fun_complexOf_uint64_t( complexOf_uint64_t ); -complexOf_int8 mkPolar_fun_int8( int8_t, int8_t );-complexOf_int16 mkPolar_fun_int16( int16_t, int16_t );-complexOf_int32 mkPolar_fun_int32( int32_t, int32_t );-complexOf_int64 mkPolar_fun_int64( int64_t, int64_t );-complexOf_uint8 mkPolar_fun_uint8( uint8_t, uint8_t );-complexOf_uint16 mkPolar_fun_uint16( uint16_t, uint16_t );-complexOf_uint32 mkPolar_fun_uint32( uint32_t, uint32_t );-complexOf_uint64 mkPolar_fun_uint64( uint64_t, uint64_t );+complexOf_int8_t mkPolar_fun_int8_t( int8_t, int8_t );+complexOf_int16_t mkPolar_fun_int16_t( int16_t, int16_t );+complexOf_int32_t mkPolar_fun_int32_t( int32_t, int32_t );+complexOf_int64_t mkPolar_fun_int64_t( int64_t, int64_t );+complexOf_uint8_t mkPolar_fun_uint8_t( uint8_t, uint8_t );+complexOf_uint16_t mkPolar_fun_uint16_t( uint16_t, uint16_t );+complexOf_uint32_t mkPolar_fun_uint32_t( uint32_t, uint32_t );+complexOf_uint64_t mkPolar_fun_uint64_t( uint64_t, uint64_t ); float complex mkPolar_fun_float( float, float );+double complex mkPolar_fun_double( double, double ); -complexOf_int8 cis_fun_int8( int8_t );-complexOf_int16 cis_fun_int16( int16_t );-complexOf_int32 cis_fun_int32( int32_t );-complexOf_int64 cis_fun_int64( int64_t );-complexOf_uint8 cis_fun_uint8( uint8_t );-complexOf_uint16 cis_fun_uint16( uint16_t );-complexOf_uint32 cis_fun_uint32( uint32_t );-complexOf_uint64 cis_fun_uint64( uint64_t );+complexOf_int8_t cis_fun_int8_t( int8_t );+complexOf_int16_t cis_fun_int16_t( int16_t );+complexOf_int32_t cis_fun_int32_t( int32_t );+complexOf_int64_t cis_fun_int64_t( int64_t );+complexOf_uint8_t cis_fun_uint8_t( uint8_t );+complexOf_uint16_t cis_fun_uint16_t( uint16_t );+complexOf_uint32_t cis_fun_uint32_t( uint32_t );+complexOf_uint64_t cis_fun_uint64_t( uint64_t ); float complex cis_fun_float( float );+double complex cis_fun_double( double ); void traceStart(); void traceEnd(); -void trace_int8( int8_t, int32_t );-void trace_int16( int16_t, int32_t );-void trace_int32( int32_t, int32_t );-void trace_int64( int64_t, int32_t );-void trace_uint8( uint8_t, int32_t );-void trace_uint16( uint16_t, int32_t );-void trace_uint32( uint32_t, int32_t );-void trace_uint64( uint64_t, int32_t );+void trace_int8_t( int8_t, int32_t );+void trace_int16_t( int16_t, int32_t );+void trace_int32_t( int32_t, int32_t );+void trace_int64_t( int64_t, int32_t );+void trace_uint8_t( uint8_t, int32_t );+void trace_uint16_t( uint16_t, int32_t );+void trace_uint32_t( uint32_t, int32_t );+void trace_uint64_t( uint64_t, int32_t ); void trace_float( float, int32_t );-void trace_complexOf_int8( complexOf_int8, int32_t );-void trace_complexOf_int16( complexOf_int16, int32_t );-void trace_complexOf_int32( complexOf_int32, int32_t );-void trace_complexOf_int64( complexOf_int64, int32_t );-void trace_complexOf_uint8( complexOf_uint8, int32_t );-void trace_complexOf_uint16( complexOf_uint16, int32_t );-void trace_complexOf_uint32( complexOf_uint32, int32_t );-void trace_complexOf_uint64( complexOf_uint64, int32_t );+void trace_double( double, int32_t );+void trace_complexOf_int8_t( complexOf_int8_t, int32_t );+void trace_complexOf_int16_t( complexOf_int16_t, int32_t );+void trace_complexOf_int32_t( complexOf_int32_t, int32_t );+void trace_complexOf_int64_t( complexOf_int64_t, int32_t );+void trace_complexOf_uint8_t( complexOf_uint8_t, int32_t );+void trace_complexOf_uint16_t( complexOf_uint16_t, int32_t );+void trace_complexOf_uint32_t( complexOf_uint32_t, int32_t );+void trace_complexOf_uint64_t( complexOf_uint64_t, int32_t ); void trace_complexOf_float( float complex, int32_t );+void trace_complexOf_double( double complex, int32_t ); #endif /* FELDSPAR_C99_H */
lib/Feldspar/C/ivar.c view
@@ -32,7 +32,10 @@ //#define LOG #include "log.h" -unsigned int ivar_linker_hook = 0xDECAFBAD;+int feldspar_ivar_hook(void)+{+ return 0;+} void *worker( void *p );
lib/Feldspar/C/ivar.h view
@@ -33,6 +33,8 @@ #include "taskpool.h" #include "feldspar_array.h" +int feldspar_ivar_hook(void);+ /* Declaration of the Feldspar application's global taskpool. */ extern struct taskpool feldspar_taskpool;
lib/Feldspar/C/taskpool.c view
@@ -32,7 +32,10 @@ //#define LOG #include "log.h" -unsigned int taskpool_linker_hook = 0xDECAFBAD;+int feldspar_taskpool_hook(void)+{+ return 0;+} /* Definition of the Feldspar application's global taskpool. */ struct taskpool *feldspar_taskpool = 0;
lib/Feldspar/C/taskpool.h view
@@ -31,6 +31,8 @@ #include <pthread.h> +int feldspar_taskpool_hook(void);+ struct taskpool { int capacity;@@ -63,7 +65,7 @@ { \ void *buffer = malloc( sizeof(void(*)()) ); \ char *p = buffer; \- void *t0 = (task); \+ void *t0 = &task; \ memcpy( p, &t0, sizeof(void(*)()) ); \ spawn( buffer ); \ } \@@ -72,7 +74,7 @@ { \ void *buffer = malloc( sizeof(void(*)()) + sizeof(t1) ); \ char *p = buffer; \- void *t0 = task; \+ void *t0 = &task; \ t1 temp1 = (p1); \ memcpy( p, &t0, sizeof(void(*)()) ); \ p += sizeof(void(*)()); \@@ -85,7 +87,7 @@ { \ void *buffer = malloc( sizeof(void(*)()) + sizeof(t1) + sizeof(t2) ); \ char *p = buffer; \- void *t0 = task; \+ void *t0 = &task; \ t1 temp1 = (p1); \ t2 temp2 = (p2); \ memcpy( p, &t0, sizeof(void(*)()) ); \@@ -102,7 +104,7 @@ { \ void *buffer = malloc( sizeof(void(*)()) + sizeof(t1) + sizeof(t2) + sizeof(t3) ); \ char *p = buffer; \- void *t0 = task; \+ void *t0 = &task; \ t1 temp1 = (p1); \ t2 temp2 = (p2); \ t3 temp3 = (p3); \@@ -123,7 +125,7 @@ { \ void *buffer = malloc( sizeof(void(*)()) + sizeof(t1) + sizeof(t2) + sizeof(t3) + sizeof(t4) ); \ char *p = buffer; \- void *t0 = task; \+ void *t0 = &task; \ t1 temp1 = (p1); \ t2 temp2 = (p2); \ t3 temp3 = (p3); \@@ -148,7 +150,7 @@ { \ void *buffer = malloc( sizeof(void(*)()) + sizeof(t1) + sizeof(t2) + sizeof(t3) + sizeof(t4) + sizeof(t5) ); \ char *p = buffer; \- void *t0 = task; \+ void *t0 = &task; \ t1 temp1 = (p1); \ t2 temp2 = (p2); \ t3 temp3 = (p3); \@@ -177,7 +179,7 @@ { \ void *buffer = malloc( sizeof(void(*)()) + sizeof(t1) + sizeof(t2) + sizeof(t3) + sizeof(t4) + sizeof(t5) + sizeof(t6) ); \ char *p = buffer; \- void *t0 = task; \+ void *t0 = &task; \ t1 temp1 = (p1); \ t2 temp2 = (p2); \ t3 temp3 = (p3); \@@ -210,7 +212,7 @@ { \ void *buffer = malloc( sizeof(void(*)()) + sizeof(t1) + sizeof(t2) + sizeof(t3) + sizeof(t4) + sizeof(t5) + sizeof(t6) + sizeof(t7) ); \ char *p = buffer; \- void *t0 = task; \+ void *t0 = &task; \ t1 temp1 = (p1); \ t2 temp2 = (p2); \ t3 temp3 = (p3); \
lib/Feldspar/Compiler.hs view
@@ -1,43 +1,24 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.--- module Feldspar.Compiler- ( defaultOptions+ ( compile+ , icompile+ , icompileWith+ , icompile'+ , getCore+ , printCore+ , Options (..)+ , defaultOptions+ , FeldOpts(..)+ , Target(..) , c99PlatformOptions+ , c99OpenMpPlatformOptions , tic64xPlatformOptions+ , nativeArrayRules , unrollOptions , noPrimitiveInstructionHandling , noMemoryInformation- , module Internal ) where -import Feldspar.Compiler.Compiler-import Feldspar.Compiler.Frontend.Interactive.Interface as Internal-import Feldspar.Compiler.Backend.C.Options as Internal-import Feldspar.Compiler.Imperative.Frontend as Internal hiding (Type, spawn)+import Feldspar.Compiler.Internal+import Feldspar.Core.Interpretation (FeldOpts(..), Target(..))
lib/Feldspar/Compiler/Backend/C/CodeGeneration.hs view
@@ -1,11 +1,11 @@ -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved.--- +-- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, +--+-- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the@@ -13,10 +13,10 @@ -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission.--- +-- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR@@ -26,119 +26,241 @@ -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- +{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleInstances #-} module Feldspar.Compiler.Backend.C.CodeGeneration where import Feldspar.Compiler.Imperative.Representation-import Feldspar.Compiler.Error+import Feldspar.Compiler.Error (handleError, ErrorClass(..)) import Feldspar.Compiler.Backend.C.Options-import Feldspar.Compiler.Backend.C.Library--import qualified Data.List as List (find)+import Feldspar.Compiler.Imperative.Frontend (isNativeArray) --- =======================--- == C code generation ==--- =======================+import Text.PrettyPrint codeGenerationError :: ErrorClass -> String -> a codeGenerationError = handleError "CodeGeneration" -defaultMemberName :: String-defaultMemberName = "member"+data PrintEnv = PEnv+ { options :: Options+ } -class ToC a where- toC :: Options -> Place -> a -> String+compToCWithInfos :: Options -> Module () -> String+compToCWithInfos opts procedure = render $ cgen (PEnv opts) procedure -getStructTypeName :: Options -> Place -> Type -> String-getStructTypeName options place (StructType ts) =- '_' : concatMap (\(_,t) -> (++"_") $ getStructTypeName options place t) ts-getStructTypeName options place (ArrayType len innerType) =- "arr_T" ++ getStructTypeName options place innerType ++ "_S" ++ len2str len- where- len2str :: Length -> String- len2str UndefinedLen = "UD"- len2str (LiteralLen i) = show i-getStructTypeName options place t = replace (toC options place t) " " "" -- float complex -> floatcomplex+class CodeGen a+ where+ cgen :: PrintEnv -> a -> Doc+ cgenList :: PrintEnv -> [a] -> Doc -instance ToC Type where- toC _ MainParameter_pl VoidType = "void"- toC _ _ VoidType = "int"- toC options place t@(StructType _) = "struct s" ++ getStructTypeName options place t- toC _ _ (UserType u) = u- toC _ _ (ArrayType _ _) = arrayTypeName- toC _ _ (IVarType _) = ivarTypeName- toC options place t = case List.find (\(t',_,_) -> t == t') $ types $ platform options of- Just (_,s,_) -> s- Nothing -> codeGenerationError InternalError $- "Unhandled type in platform " ++ name (platform options) ++ ": " ++ show t ++ " place: " ++ show place+instance CodeGen (Module ())+ where+ cgen env Module{..} = cgenList env entities+ cgenList env = sep . map (cgen env) -instance ToC (Variable ()) where- toC options place (Variable vname typ role _) = showVariable options place role typ vname+instance CodeGen (Entity ())+ where+ cgen env StructDef{..} = text "struct" <+> text structName $+$ block env (cgenList env structMembers) <> semi+ cgen env TypeDef{..} = text "typedef" <+> cgen env actualType <+> text typeName <> semi+ cgen env Proc{..}+ | Just body <- procBody = start $$ block env (cgen env body)+ | otherwise = start <> semi+ where+ start = text "void" <+> text procName <> parens (pvars env $ inParams ++ outParams)+ cgen env ValueDef{..} = static <+> typ <+> text "const" <+> name <+> equals <+> vals <> semi+ where+ static = text "static"+ typ = cgen env (typeof valVar)+ name = cgen env valVar <> size valValue+ vals = cgen env valValue+ size (ArrayConst vs) = brackets $ text $ show $ length vs+ size _ = empty -showVariable :: Options -> Place -> VariableRole -> Type -> String -> String-showVariable options place role typ vname = listprint id " " [variableType, showName role place typ vname] where- variableType = showType options role place typ restr- restr- | place == MainParameter_pl = isRestrict $ platform options- | otherwise = NoRestrict+ cgenList env = vcat . punctuate (text "\n") . map (cgen env) -showType :: Options -> VariableRole -> Place -> Type -> IsRestrict -> String-showType options role MainParameter_pl t _- | passByReference t || role == Pointer = tname ++ " *"- | otherwise = tname+instance CodeGen (StructMember ()) where- tname = toC options MainParameter_pl t-showType options _ Declaration_pl t _ = toC options Declaration_pl t-showType _ _ _ _ _ = ""+ cgen env StructMember{..} = cgen env structMemberType <+> text structMemberName <> sizeInBrackets structMemberType <> semi -arrayTypeName :: String-arrayTypeName = "struct array"+ cgenList env = vcat . map (cgen env) -ivarTypeName :: String-ivarTypeName = "struct ivar"+instance CodeGen (Block ())+ where+ cgen env Block{..} = sep [ cgenList env locals+ , if null locals then empty else text ""+ , cgen env blockBody+ ]+ cgenList env = sep . punctuate (text "\n") . map (cgen env) -showName :: VariableRole -> Place -> Type -> String -> String-showName Value place t n- | place == AddressNeed_pl = '&' : n- | place == FunctionCallIn_pl && passByReference t = '&' : n- | otherwise = n-showName Pointer _ ArrayType{} n = n-showName Pointer place _ n- | place == AddressNeed_pl = n- | place == Declaration_pl = codeGenerationError InternalError "Output variable of the function declared!"- | place == MainParameter_pl = n- | otherwise = "(* " ++ n ++ ")"+instance CodeGen (Declaration ())+ where+ cgen env Declaration{..} = pvar env declVar <+> nest (nestSize $ options env) initial <> semi+ where+ initial = case (initVal, varType declVar) of+ (Just i, _) -> equals <+> cgen env i+ (_ , Pointer{}) -> equals <+> text "NULL"+ (_ , ArrayType{}) -> equals <+> text "NULL"+ _ -> empty+ cgenList env = vcat . map (cgen env) -passByReference :: Type -> Bool-passByReference ArrayType{} = True-passByReference StructType{} = True-passByReference _ = False+instance CodeGen (Program ())+ where+ cgen _ Empty = empty+ cgen _ Comment{..}+ | isBlockComment = blockComment $ map text $ lines commentValue+ | otherwise = text "//" <+> text commentValue+ cgen env Assign{..} = cgen env lhs <+> equals <+> nest (nestSize $ options env) (cgen env rhs) <> semi+ cgen env ProcedureCall{..} = stmt $ call (text procCallName) (map (cgen env) procCallParams)+ cgen env Sequence{..} = cgenList env sequenceProgs+ cgen env (Switch scrut [(Pat (ConstExpr (BoolConst True)), thenBlock),+ (Pat (ConstExpr (BoolConst False)), elseBlock)])+ = text "if" <+> parens (cgen env scrut)+ $$ block env (cgen env thenBlock)+ $$ text "else"+ $$ block env (cgen env elseBlock)+ cgen env Switch{..} = text "switch" <+> parens (cgen env scrutinee)+ $$ block env (vcat [ cgen env p $$ nest (nestSize $ options env) (cgen env b $$ text "break" <> semi) | (p, b) <- alts])+ cgen env SeqLoop{..} = cgen env sLoopCondCalc+ $$ text "while" <+> parens (cgen env sLoopCond)+ $$ block env (cgen env sLoopBlock $+$ cgen env sLoopCondCalc)+ cgen env ParLoop{..}+ | pParallel && (name . platform . options $ env) == "c99OpenMp"+ = text "#pragma omp parallel for" $$ forL+ | otherwise = forL+ where+ forL = text "for" <+> parens (sep $ map (nest 4) $ punctuate semi [ini, guard, next])+ $$ block env (cgen env pLoopBlock)+ ixd = pvar env pLoopCounter+ ixv = cgen env pLoopCounter+ ini = ixd <+> equals <+> int 0+ guard = ixv <+> char '<' <+> cgen env pLoopBound+ next = ixv <+> text "+=" <+> cgen env pLoopStep -------------------------- Helper functions -------------------------+ cgen env BlockProgram{..} = block env (cgen env blockProgram) -ind :: (a-> String) -> a -> String-ind f x = unlines $ map (\a -> " " ++ a) $ lines $ f x+ cgenList env = vcat . map (cgen env) -listprint :: (a->String) -> String -> [a] -> String-listprint f s = listprint' . filter (/= "") . map f+instance CodeGen (Pattern ()) where- listprint' [] = ""- listprint' [x] = x- listprint' (x:xs) = x ++ s ++ listprint' xs+ cgen _ PatDefault = text "default" <> colon+ cgen env (Pat c) = text "case" <+> cgen env c <> colon -decrArrayDepth :: Type -> Type-decrArrayDepth (ArrayType _ t) = t-decrArrayDepth t = codeGenerationError InternalError $ "Non-array variable of type " ++ show t ++ " is indexed!"+ cgenList env = vcat . map (cgen env) -getStructFieldType :: String -> Type -> Type-getStructFieldType f (StructType l) = case List.find (\(a,_) -> a == f) l of- Just (_,t) -> t- Nothing -> structFieldNotFound f-getStructFieldType f t = codeGenerationError InternalError $- "Trying to get a struct field from not a struct typed expression\n" ++ "Field: " ++ f ++ "\nType: " ++ show t+instance CodeGen (ActualParameter ())+ where+ cgen env ValueParameter{..} = cgen env valueParam+ cgen env TypeParameter{..} = cgen env typeParam+ cgen _ FunParameter{..} = text funParamName+ cgenList env = hsep . punctuate comma . map (cgen env) -structFieldNotFound :: String -> a-structFieldNotFound f = codeGenerationError InternalError $ "Not found struct field with this name: " ++ f+instance CodeGen (Expression ())+ where+ cgen env VarExpr{..} = cgen env varExpr+ cgen env e@ArrayElem{..}+ | c@ConstExpr{} <- array+ , (NativeArray _ t) <- typeof c+ = parens (parens (cgen env t <> brackets empty) <> cgen env c) <> brackets (cgen env arrayIndex)+ | isNativeArray $ typeof array+ = cgen env array <> brackets (cgen env arrayIndex)+ | otherwise = text "at" <> parens (hcat $ punctuate comma [ cgen env $ typeof e+ , cgen env array+ , cgen env arrayIndex+ ])+ cgen env StructField{..} = parens (cgen env struct) <> char '.' <> text fieldName+ cgen env ConstExpr{..} = cgen env constExpr+ cgen env FunctionCall{..}+ | funName function == "!" = call (text "at") $ map (cgen env) funCallParams+ | funMode function == Infix+ , [a,b] <- funCallParams = parens (cgen env a <+> text (funName function) <+> cgen env b)+ | otherwise = call (text $ funName function) $ map (cgen env) funCallParams+ cgen env Cast{..} = parens $ parens (cgen env castType) <> parens (cgen env castExpr)+ cgen env AddrOf{..}+ | VarExpr v@(Variable{..}) <- addrExpr+ , Pointer t <- typeof addrExpr = cgen env (v{varType = t})+ | otherwise = prefix <> cgen env addrExpr+ where+ prefix = case (addrExpr, typeof addrExpr) of+ (e, Pointer{}) | specialConstruct e -> empty -- Skip single level AddrOf+ where specialConstruct ArrayElem{} = True+ specialConstruct StructField{} = True+ specialConstruct _ = False++ _ -> text "&"+ cgen env SizeOf{..} = call (text "sizeof") [cgen env sizeOf]++ cgenList env = sep . punctuate comma . map (cgen env)++instance CodeGen (Variable t)+ where+ cgen _ = go+ where+ go v@Variable{..} = case varType of+ Pointer t -> text "*" <> go (v {varType = t})-- char '*'+ _ -> text varName++ cgenList env = hsep . punctuate comma . map (cgen env)++instance CodeGen (Constant ())+ where+ cgen env cnst@(IntConst c _) = maybe (integer c) text $ transformConst env cnst+ cgen env cnst@(DoubleConst c) = maybe (double c) text $ transformConst env cnst+ cgen env cnst@(FloatConst c) = maybe (float c) text $ transformConst env cnst+ cgen env cnst@(BoolConst False) = maybe (int 0) text $ transformConst env cnst+ cgen env cnst@(BoolConst True) = maybe (int 1) text $ transformConst env cnst+ cgen env (ArrayConst cs) = braces (cgenList env cs)+ cgen env cnst@ComplexConst{..} = maybe cmplxCnst text $ transformConst env cnst+ where+ cmplxCnst = text "complex" <> parens (cgenList env [realPartComplexValue, imagPartComplexValue])+ cgenList env = sep . punctuate comma . map (cgen env)++transformConst :: PrintEnv -> Constant () -> Maybe String+transformConst PEnv{..} cnst = do+ f <- lookup (typeof cnst) $ values $ platform options+ return $ f cnst++instance CodeGen Type+ where+ cgen env = toC+ where+ toC VoidType = text "void"+ toC ArrayType{} = text "struct array *"+ toC IVarType{} = text "struct ivar"+ toC (UserType u) = text u+ toC (StructType n _) = text "struct" <+> text n+ toC (NativeArray _ t) = toC t+ toC (Pointer t) = toC t <+> text "*"+ toC t | Just s <- lookup t pts = text s+ toC t = codeGenerationError InternalError+ $ unwords ["Unhandled type in platform ", name pfm, ": ", show t]+ pfm = platform $ options env+ pts = types pfm++ cgenList env = sep . map (cgen env)++call :: Doc -> [Doc] -> Doc+call fn args = fn <> parens (hsep $ punctuate comma args)++blockComment :: [Doc] -> Doc+blockComment ds = vcat (zipWith (<+>) (text "/*" : repeat (text " *")) ds)+ $$ text " */"++sizeInBrackets :: Type -> Doc+sizeInBrackets (NativeArray l t) = brackets (maybe empty (text . show) l) <> sizeInBrackets t+sizeInBrackets _ = empty++stmt :: Doc -> Doc+stmt = (<>semi)++block :: PrintEnv -> Doc -> Doc+block env d = lbrace $+$ nest (nestSize $ options env) d $+$ rbrace++pvar :: PrintEnv -> Variable t -> Doc+pvar env Variable{..} = typ <+> (name <> size)+ where+ typ = cgen env varType+ size = sizeInBrackets varType+ name = text varName++pvars :: PrintEnv -> [Variable t] -> Doc+pvars env = hsep . punctuate comma . map (pvar env)
lib/Feldspar/Compiler/Backend/C/Library.hs view
@@ -26,37 +26,26 @@ -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -module Feldspar.Compiler.Backend.C.Library- (module System.Console.ANSI,- module Feldspar.Compiler.Backend.C.Library) where--import Control.Monad.State-import System.Console.ANSI-import System.FilePath-import qualified Feldspar.Compiler.Imperative.Representation as AIR+module Feldspar.Compiler.Backend.C.Library where -data CompilationMode = Interactive | Standalone- deriving (Show, Eq)+import Data.List (isPrefixOf)+import System.FilePath ((<.>)) -type AllocationInfo = ([AIR.Type],[AIR.Type],[AIR.Type])- -- =========================================================================== -- == String tools -- =========================================================================== replace :: Eq a => [a] -> [a] -> [a] -> [a] replace [] _ _ = []-replace s find repl | take (length find) s == find = repl ++ replace (drop (length find) s) find repl+replace s find repl | find `isPrefixOf` s = repl ++ replace (drop (length find) s) find repl | otherwise = head s : replace (tail s) find repl -fixFunctionName :: String -> String-fixFunctionName functionName = replace (replace functionName "_" "__") "'" "_prime"--makeDebugHFileName :: String -> String-makeDebugHFileName = (<.> "h.dbg.txt")+-- | Encode special characters in function names +encodeFunctionName :: String -> String+encodeFunctionName functionName = replace (replace functionName "_" "__") "'" "_prime" -makeDebugCFileName :: String -> String-makeDebugCFileName = (<.> "c.dbg.txt")+makeDebugFileName :: String -> String+makeDebugFileName = (<.> "dbg.txt") makeHFileName :: String -> String makeHFileName = (<.> "h")@@ -64,22 +53,3 @@ makeCFileName :: String -> String makeCFileName = (<.> "c") --- ===========================================================================--- == Name generator--- ===========================================================================--newName :: (Monad m) => String -> StateT Integer m String-newName name = do- n <- get- put $ n+1- return $ name ++ show n---- ===========================================================================--- == Console tools--- ===========================================================================--withColor :: Color -> IO () -> IO ()-withColor color action = do- setSGR [SetColor Foreground Vivid color, SetColor Background Dull Black] -- , SetConsoleIntensity BoldIntensity]- action- setSGR [Reset]
lib/Feldspar/Compiler/Backend/C/Options.hs view
@@ -36,19 +36,22 @@ module Feldspar.Compiler.Backend.C.Options where import Data.Typeable-import Text.Show.Functions -import Feldspar.Compiler.Imperative.Representation-import Feldspar.Compiler.Imperative.Frontend hiding (UserType, Type, Var)+import Feldspar.Core.Interpretation (FeldOpts(..)) +import Feldspar.Compiler.Imperative.Representation (Type(..), Constant(..))+ data Options = Options { platform :: Platform , unroll :: UnrollStrategy , debug :: DebugOption , memoryInfoVisible :: Bool+ , printHeader :: Bool , rules :: [Rule]- } deriving (Eq, Show)+ , frontendOpts :: FeldOpts+ , nestSize :: Int -- ^ Indentation size for PrettyPrinting+ } data UnrollStrategy = NoUnroll | Unroll Int deriving (Eq, Show)@@ -58,12 +61,13 @@ data Platform = Platform { name :: String,- types :: [(Type, String, String)],+ types :: [(Type, String)], values :: [(Type, ShowValue)], includes :: [String], platformRules :: [Rule],+ varFloating :: Bool, isRestrict :: IsRestrict-} deriving (Eq, Show)+} deriving (Show) type ShowValue = Constant () -> String @@ -91,11 +95,11 @@ instance Eq Rule where _ == _ = False -rule :: (Interface t, Typeable (Repr t)) => (t -> [Action (Repr t)]) -> Rule-rule f = Rule $ \x -> f $ toInterface x+rule :: (Typeable t) => (t -> [Action t]) -> Rule+rule f = Rule $ \x -> f x -replaceWith :: (Interface t) => t -> Action (Repr t)-replaceWith = Replace . fromInterface+replaceWith :: t -> Action t+replaceWith = Replace -propagate :: (Interface t, Typeable (Repr t)) => (t -> [Action (Repr t)]) -> Action t'+propagate :: (Typeable t) => (t -> [Action t]) -> Action t' propagate = Propagate . rule
lib/Feldspar/Compiler/Backend/C/Platforms.hs view
@@ -27,83 +27,101 @@ -- {-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE RecordWildCards #-} module Feldspar.Compiler.Backend.C.Platforms ( availablePlatforms , c99+ , c99OpenMp , tic64x , c99Rules , tic64xRules , traceRules+ , nativeArrayRules ) where +import Data.Maybe (fromMaybe) +import Feldspar.Range import Feldspar.Compiler.Backend.C.Options-import Feldspar.Compiler.Imperative.Representation hiding (Type, Cast, In, Out, Block)+import Feldspar.Compiler.Imperative.Representation import Feldspar.Compiler.Imperative.Frontend availablePlatforms :: [Platform]-availablePlatforms = [ c99, tic64x ]+availablePlatforms = [ c99, c99OpenMp, tic64x ] c99 :: Platform c99 = Platform { name = "c99", types =- [ (NumType Signed S8, "int8_t", "int8")- , (NumType Signed S16, "int16_t", "int16")- , (NumType Signed S32, "int32_t", "int32")- , (NumType Signed S64, "int64_t", "int64")- , (NumType Unsigned S8, "uint8_t", "uint8")- , (NumType Unsigned S16, "uint16_t", "uint16")- , (NumType Unsigned S32, "uint32_t", "uint32")- , (NumType Unsigned S64, "uint64_t", "uint64")- , (BoolType, "uint32_t", "uint32_t") -- TODO sizeof(bool) is implementation dependent- , (FloatType, "float", "float")- , (ComplexType FloatType, "float complex", "complexOf_float")+ [ (NumType Signed S8, "int8_t")+ , (NumType Signed S16, "int16_t")+ , (NumType Signed S32, "int32_t")+ , (NumType Signed S64, "int64_t")+ , (NumType Unsigned S8, "uint8_t")+ , (NumType Unsigned S16, "uint16_t")+ , (NumType Unsigned S32, "uint32_t")+ , (NumType Unsigned S64, "uint64_t")+ , (BoolType, "uint32_t")+ , (FloatType, "float")+ , (DoubleType, "double")+ , (ComplexType FloatType, "float complex")+ , (ComplexType DoubleType,"double complex") ] , values = [ (ComplexType FloatType, \cx -> "(" ++ showRe cx ++ "+" ++ showIm cx ++ "i)")+ , (ComplexType DoubleType, \cx -> "(" ++ showRe cx ++ "+" ++ showIm cx ++ "i)") , (BoolType, \b -> if boolValue b then "true" else "false") ] , includes =- [ "\"feldspar_c99.h\""- , "\"feldspar_array.h\""- , "\"feldspar_future.h\""- , "\"ivar.h\""- , "\"taskpool.h\""+ [ "feldspar_c99.h"+ , "feldspar_array.h"+ , "feldspar_future.h"+ , "ivar.h"+ , "taskpool.h" , "<stdint.h>" , "<string.h>" , "<math.h>" , "<stdbool.h>" , "<complex.h>"],- platformRules = c99Rules ++ traceRules,+ platformRules = c99Rules ++ traceRules ++ arrayRules,+ varFloating = True, isRestrict = NoRestrict } +c99OpenMp :: Platform+c99OpenMp = c99 { name = "c99OpenMp"+ , varFloating = False+ }+ tic64x :: Platform tic64x = Platform { name = "tic64x", types =- [ (NumType Signed S8, "char", "char")- , (NumType Signed S16, "short", "short")- , (NumType Signed S32, "int", "int")- , (NumType Signed S40, "long", "long")- , (NumType Signed S64, "long long","llong")- , (NumType Unsigned S8, "unsigned char", "uchar")- , (NumType Unsigned S16, "unsigned short", "ushort")- , (NumType Unsigned S32, "unsigned", "uint")- , (NumType Unsigned S40, "unsigned long", "ulong")- , (NumType Unsigned S64, "unsigned long long", "ullong")- , (BoolType, "int", "bool")- , (FloatType, "float", "float")- , (ComplexType FloatType, "complexOf_float", "complexOf_float")+ [ (NumType Signed S8, "char")+ , (NumType Signed S16, "short")+ , (NumType Signed S32, "int")+ , (NumType Signed S40, "long")+ , (NumType Signed S64, "long long")+ , (NumType Unsigned S8, "unsigned char")+ , (NumType Unsigned S16, "unsigned short")+ , (NumType Unsigned S32, "unsigned")+ , (NumType Unsigned S40, "unsigned long")+ , (NumType Unsigned S64, "unsigned long long")+ , (BoolType, "int")+ , (FloatType, "float")+ , (DoubleType, "double")+ , (ComplexType FloatType, "complexOf_float")+ , (ComplexType DoubleType,"complexOf_double") ] , values = [ (ComplexType FloatType, \cx -> "complex_fun_float(" ++ showRe cx ++ "," ++ showIm cx ++ ")")+ , (ComplexType DoubleType, \cx -> "complex_fun_double(" ++ showRe cx ++ "," ++ showIm cx ++ ")") , (BoolType, \b -> if boolValue b then "1" else "0") ] ,- includes = ["\"feldspar_tic64x.h\"", "\"feldspar_array.h\"", "<c6x.h>", "<string.h>", "<math.h>"],+ includes = ["feldspar_tic64x.h", "feldspar_array.h", "<c6x.h>", "<string.h>", "<math.h>"], platformRules = tic64xRules ++ c99Rules ++ traceRules,+ varFloating = True, isRestrict = Restrict } @@ -112,168 +130,249 @@ showIm = showConstant . imagPartComplexValue showConstant :: Constant t -> String-showConstant (IntConst c _ _ _) = show c-showConstant (FloatConst c _ _) = show c ++ "f"+showConstant (DoubleConst c) = show c ++ "f"+showConstant (FloatConst c) = show c ++ "f"+showConstant c = show c -c99Rules :: [Rule]-c99Rules = [rule copy, rule c99]+arrayRules :: [Rule]+arrayRules = [rule copy] where- copy (Call "copy" [Out arg1, In arg2])- | isArray (typeof arg1) = [replaceWith $ Call "copyArray" [Out arg1,In arg2]]- | otherwise = [replaceWith $ arg1 := arg2]+ copy (ProcedureCall "copy" [ValueParameter arg1, ValueParameter arg2])+ | arg1 == arg2+ = [replaceWith Empty]++ | ConstExpr ArrayConst{..} <- arg2+ = [replaceWith $ Sequence $ initArray (Just arg1) (litI32 $ toInteger $ length arrayValues):zipWith (\i c -> Assign (ArrayElem arg1 (litI32 i)) (ConstExpr c)) [0..] arrayValues]++ | NativeArray{} <- typeof arg2+ , l@(ConstExpr (IntConst n _)) <- arrayLength arg2+ = [replaceWith $ Sequence $ initArray (Just arg1) l:map (\i -> Assign (ArrayElem arg1 (litI32 i)) (ArrayElem arg2 (litI32 i))) [0..(n-1)]]++ | not (isArray (typeof arg1))+ = [replaceWith $ Assign arg1 arg2]++ copy (ProcedureCall "copy" (dst@(ValueParameter arg1):ins'@(ValueParameter in1:ins)))+ | isArray (typeof arg1)+ = [replaceWith $ Sequence ([+ initArray (Just arg1) (foldr ePlus (litI32 0) aLens)+ , if arg1 == in1 then Empty else call "copyArray" [dst, ValueParameter in1]+ ] ++ flattenCopy dst ins argnLens arg1len)]+ where+ aLens@(arg1len:argnLens) = map (\(ValueParameter src) -> arrayLength src) ins'++ copy (ProcedureCall "copy" _) = error "Multiple scalar arguments to copy"+ copy _ = []- c99 (Fun _ "(!)" [arg1,arg2]) = [replaceWith $ arg1 :!: arg2]- c99 (Fun _ "getFst" [arg]) = [replaceWith $ arg :.: first]- c99 (Fun _ "getSnd" [arg]) = [replaceWith $ arg :.: second]- c99 (Fun t "(==)" [arg1, arg2]) = [replaceWith $ Binop t "==" [arg1, arg2]]- c99 (Fun t "(/=)" [arg1, arg2]) = [replaceWith $ Binop t "!=" [arg1, arg2]]- c99 (Fun t "(<)" [arg1, arg2]) = [replaceWith $ Binop t "<" [arg1, arg2]]- c99 (Fun t "(>)" [arg1, arg2]) = [replaceWith $ Binop t ">" [arg1, arg2]]- c99 (Fun t "(<=)" [arg1, arg2]) = [replaceWith $ Binop t "<=" [arg1, arg2]]- c99 (Fun t "(>=)" [arg1, arg2]) = [replaceWith $ Binop t ">=" [arg1, arg2]]- c99 (Fun t "not" [arg]) = [replaceWith $ Fun t "!" [arg]]- c99 (Fun t "(&&)" [arg1, arg2]) = [replaceWith $ Binop t "&&" [arg1, arg2]]- c99 (Fun t "(||)" [arg1, arg2]) = [replaceWith $ Binop t "||" [arg1, arg2]]- c99 (Fun t "quot" [arg1, arg2]) = [replaceWith $ Binop t "/" [arg1, arg2]]- c99 (Fun t "rem" [arg1, arg2]) = [replaceWith $ Binop t "%" [arg1, arg2]]- c99 (Fun t "(^)" [arg1, arg2]) = [replaceWith $ Fun t (extend "pow" t) [arg1, arg2]]- c99 (Fun t "abs" [arg]) = [replaceWith $ Fun t (extend "abs" t) [arg]]- c99 (Fun t "signum" [arg]) = [replaceWith $ Fun t (extend "signum" t) [arg]]- c99 (Fun t "(+)" [arg1, arg2]) = [replaceWith $ Binop t "+" [arg1, arg2]]- c99 (Fun t "(-)" [LitI _ 0, arg2]) = [replaceWith $ Fun t "-" [arg2]]- c99 (Fun t "(-)" [LitF 0, arg2]) = [replaceWith $ Fun t "-" [arg2]]- c99 (Fun t "(-)" [arg1, arg2]) = [replaceWith $ Binop t "-" [arg1, arg2]]- c99 (Fun t "(*)" [LitI _ (log2 -> Just n), arg2]) = [replaceWith $ Binop t "<<" [arg2, LitI I32 n]]- c99 (Fun t "(*)" [arg1, LitI _ (log2 -> Just n)]) = [replaceWith $ Binop t "<<" [arg1, LitI I32 n]]- c99 (Fun t "(*)" [arg1, arg2]) = [replaceWith $ Binop t "*" [arg1, arg2]]- c99 (Fun t "(/)" [arg1, arg2]) = [replaceWith $ Binop t "/" [arg1, arg2]]- c99 (Fun t@(Complex _) "exp" [arg]) = [replaceWith $ Fun t "cexpf" [arg]]- c99 (Fun t "exp" [arg]) = [replaceWith $ Fun t "expf" [arg]]- c99 (Fun t@(Complex _) "sqrt" [arg]) = [replaceWith $ Fun t "csqrtf" [arg]]- c99 (Fun t "sqrt" [arg]) = [replaceWith $ Fun t "sqrtf" [arg]]- c99 (Fun t@(Complex _) "log" [arg]) = [replaceWith $ Fun t "clogf" [arg]]- c99 (Fun t "log" [arg]) = [replaceWith $ Fun t "logf" [arg]]- c99 (Fun t@(Complex _) "(**)" [arg1, arg2]) = [replaceWith $ Fun t "cpowf" [arg1,arg2]]- c99 (Fun t "(**)" [arg1, arg2]) = [replaceWith $ Fun t "powf" [arg1,arg2]]- c99 (Fun t "logBase" [arg1, arg2]) = [replaceWith $ Fun t (extend "logBase" t) [arg1,arg2]]- c99 (Fun t@(Complex _) "sin" [arg]) = [replaceWith $ Fun t "csinf" [arg]]- c99 (Fun t "sin" [arg]) = [replaceWith $ Fun t "sinf" [arg]]- c99 (Fun t@(Complex _) "tan" [arg]) = [replaceWith $ Fun t "ctanf" [arg]]- c99 (Fun t "tan" [arg]) = [replaceWith $ Fun t "tanf" [arg]]- c99 (Fun t@(Complex _) "cos" [arg]) = [replaceWith $ Fun t "ccosf" [arg]]- c99 (Fun t "cos" [arg]) = [replaceWith $ Fun t "cosf" [arg]]- c99 (Fun t@(Complex _) "asin" [arg]) = [replaceWith $ Fun t "casinf" [arg]]- c99 (Fun t "asin" [arg]) = [replaceWith $ Fun t "asinf" [arg]]- c99 (Fun t@(Complex _) "atan" [arg]) = [replaceWith $ Fun t "catanf" [arg]]- c99 (Fun t "atan" [arg]) = [replaceWith $ Fun t "atanf" [arg]]- c99 (Fun t@(Complex _) "acos" [arg]) = [replaceWith $ Fun t "cacosf" [arg]]- c99 (Fun t "acos" [arg]) = [replaceWith $ Fun t "acosf" [arg]]- c99 (Fun t@(Complex _) "sinh" [arg]) = [replaceWith $ Fun t "csinhf" [arg]]- c99 (Fun t "sinh" [arg]) = [replaceWith $ Fun t "sinhf" [arg]]- c99 (Fun t@(Complex _) "tanh" [arg]) = [replaceWith $ Fun t "ctanhf" [arg]]- c99 (Fun t "tanh" [arg]) = [replaceWith $ Fun t "tanhf" [arg]]- c99 (Fun t@(Complex _) "cosh" [arg]) = [replaceWith $ Fun t "ccoshf" [arg]]- c99 (Fun t "cosh" [arg]) = [replaceWith $ Fun t "coshf" [arg]]- c99 (Fun t@(Complex _) "asinh" [arg]) = [replaceWith $ Fun t "casinhf" [arg]]- c99 (Fun t "asinh" [arg]) = [replaceWith $ Fun t "asinhf" [arg]]- c99 (Fun t@(Complex _) "atanh" [arg]) = [replaceWith $ Fun t "catanhf" [arg]]- c99 (Fun t "atanh" [arg]) = [replaceWith $ Fun t "atanhf" [arg]]- c99 (Fun t@(Complex _) "acosh" [arg]) = [replaceWith $ Fun t "cacoshf" [arg]]- c99 (Fun t "acosh" [arg]) = [replaceWith $ Fun t "acoshf" [arg]]- c99 (Fun t "(.&.)" [arg1, arg2]) = [replaceWith $ Binop t "&" [arg1, arg2]]- c99 (Fun t "(.|.)" [arg1, arg2]) = [replaceWith $ Binop t "|" [arg1, arg2]]- c99 (Fun t "xor" [arg1, arg2]) = [replaceWith $ Binop t "^" [arg1, arg2]]- c99 (Fun t "complement" [arg]) = [replaceWith $ Fun t "~" [arg]]- c99 (Fun t "bit" [arg]) = [replaceWith $ Binop t "<<" [LitI t 1, arg]]- c99 (Fun t "setBit" [arg1, arg2]) = [replaceWith $ Fun t (extend "setBit" t) [arg1, arg2]]- c99 (Fun t "clearBit" [arg1, arg2]) = [replaceWith $ Fun t (extend "clearBit" t) [arg1, arg2]]- c99 (Fun t "complementBit" [arg1, arg2]) = [replaceWith $ Fun t (extend "complementBit" t) [arg1, arg2]]- c99 (Fun t "testBit" [arg1, arg2]) = [replaceWith $ Fun t (extend "testBit" $ typeof arg1) [arg1, arg2]]- c99 (Fun t "shiftL" [arg1, arg2]) = [replaceWith $ Binop t "<<" [arg1, arg2]]- c99 (Fun t "shiftR" [arg1, arg2]) = [replaceWith $ Binop t ">>" [arg1, arg2]]- c99 (Fun t "rotateL" [arg1, arg2]) = [replaceWith $ Fun t (extend "rotateL" t) [arg1, arg2]]- c99 (Fun t "rotateR" [arg1, arg2]) = [replaceWith $ Fun t (extend "rotateR" t) [arg1, arg2]]- c99 (Fun t "reverseBits" [arg]) = [replaceWith $ Fun t (extend "reverseBits" t) [arg]]- c99 (Fun t "bitScan" [arg]) = [replaceWith $ Fun t (extend "bitScan" $ typeof arg) [arg]]- c99 (Fun t "bitCount" [arg]) = [replaceWith $ Fun t (extend "bitCount" $ typeof arg) [arg]]- c99 (Fun _ "bitSize" [intWidth . typeof -> Just n]) = [replaceWith $ LitI U32 n]- c99 (Fun _ "isSigned" [intSigned . typeof -> Just b]) = [replaceWith $ litB b]- c99 (Fun t "complex" [arg1, arg2]) = [replaceWith $ Fun t (extend "complex" $ typeof arg1) [arg1,arg2]]- c99 (Fun t "creal" [arg]) = [replaceWith $ Fun t "crealf" [arg]]- c99 (Fun t "cimag" [arg]) = [replaceWith $ Fun t "cimagf" [arg]]- c99 (Fun t "conjugate" [arg]) = [replaceWith $ Fun t "conjf" [arg]]- c99 (Fun t "magnitude" [arg]) = [replaceWith $ Fun t "cabsf" [arg]]- c99 (Fun t "phase" [arg]) = [replaceWith $ Fun t "cargf" [arg]]- c99 (Fun t "mkPolar" [arg1, arg2]) = [replaceWith $ Fun t (extend "mkPolar" $ typeof arg1) [arg1, arg2]]- c99 (Fun t "cis" [arg]) = [replaceWith $ Fun t (extend "cis" $ typeof arg) [arg]]- c99 (Fun t "f2i" [arg]) = [replaceWith $ Cast t $ Fun Floating "truncf" [arg]]- c99 (Fun (Complex t) "i2n" [arg]) = [replaceWith $ Fun (Complex t) (extend "complex" t) [Cast t arg, LitF 0]]- c99 (Fun t "i2n" [arg]) = [replaceWith $ Cast t arg]- c99 (Fun t "b2i" [arg]) = [replaceWith $ Cast t arg]- c99 (Fun t "round" [arg]) = [replaceWith $ Cast t $ Fun Floating "roundf" [arg]]- c99 (Fun t "ceiling" [arg]) = [replaceWith $ Cast t $ Fun Floating "ceilf" [arg]]- c99 (Fun t "floor" [arg]) = [replaceWith $ Cast t $ Fun Floating "floorf" [arg]]- c99 _ = [] +nativeArrayRules :: [Rule]+nativeArrayRules = [rule toNativeExpr, rule toNativeProg, rule toNativeVariable]+ where+ toNativeExpr :: Expression () -> [Action (Expression ())]+ toNativeExpr _ = []++ toNativeProg (Assign _ (FunctionCall (Function "initArray" _ _) [arr,_,_]))+ | native (typeof arr) = [replaceWith $ call "assert" [ValueParameter arr]]+ toNativeProg (ProcedureCall "freeArray" [ValueParameter arr])+ | native (typeof arr) = [replaceWith Empty]+ toNativeProg _ = []+++ toNativeVariable :: Variable () -> [Action (Variable ())]+ toNativeVariable v@Variable{..} | isArray varType+ = [replaceWith $ v { varType = nativeArray varType }]+ toNativeVariable _ = []++ nativeArray (Pointer (ArrayType sz t)) = NativeArray (fromSingleton sz) (nativeArray t) + nativeArray (ArrayType sz t) = NativeArray (fromSingleton sz) (nativeArray t)+ nativeArray (Pointer t) = Pointer (nativeArray t)+ nativeArray t = t++ native (NativeArray {}) = True+ native (Pointer t) = native t+ native _ = False++ fromSingleton r = if isSingleton r+ then Just $ upperBound r+ else Nothing++flattenCopy :: ActualParameter () -> [ActualParameter ()] -> [Expression ()] -> Expression () -> [Program ()]+flattenCopy _ [] [] _ = []+flattenCopy dst (ValueParameter t:ts) (l:ls) cLen = call "copyArrayPos" [dst, ValueParameter cLen, ValueParameter t]+ : flattenCopy dst ts ls (ePlus cLen l)++ePlus :: Expression () -> Expression () -> Expression ()+ePlus (ConstExpr (IntConst 0 _)) e = e+ePlus e (ConstExpr (IntConst 0 _)) = e+ePlus e1 e2 = binop (NumType Signed S32) "+" e1 e2++c99Rules :: [Rule]+c99Rules = [rule go]+ where+ go :: Expression () -> [Action (Expression ())]+ go (FunctionCall (Function "(!)" _ _) [arg1,arg2]) = [replaceWith $ ArrayElem arg1 arg2]+ go (FunctionCall (Function "getFst" _ _) [arg]) = [replaceWith $ StructField arg first]+ go (FunctionCall (Function "getSnd" _ _) [arg]) = [replaceWith $ StructField arg second]+ go (FunctionCall (Function "(==)" t _) [arg1, arg2]) = [replaceWith $ binop t "==" arg1 arg2]+ go (FunctionCall (Function "(/=)" t _) [arg1, arg2]) = [replaceWith $ binop t "!=" arg1 arg2]+ go (FunctionCall (Function "(<)" t _) [arg1, arg2]) = [replaceWith $ binop t "<" arg1 arg2]+ go (FunctionCall (Function "(>)" t _) [arg1, arg2]) = [replaceWith $ binop t ">" arg1 arg2]+ go (FunctionCall (Function "(<=)" t _) [arg1, arg2]) = [replaceWith $ binop t "<=" arg1 arg2]+ go (FunctionCall (Function "(>=)" t _) [arg1, arg2]) = [replaceWith $ binop t ">=" arg1 arg2]+ go (FunctionCall (Function "not" t _) [arg]) = [replaceWith $ fun t "!" [arg]]+ go (FunctionCall (Function "(&&)" t _) [arg1, arg2]) = [replaceWith $ binop t "&&" arg1 arg2]+ go (FunctionCall (Function "(||)" t _) [arg1, arg2]) = [replaceWith $ binop t "||" arg1 arg2]+ go (FunctionCall (Function "quot" t _) [arg1, arg2]) = [replaceWith $ binop t "/" arg1 arg2]+ go (FunctionCall (Function "rem" t _) [arg1, arg2]) = [replaceWith $ binop t "%" arg1 arg2]+ go (FunctionCall (Function "(^)" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "pow" t) [arg1, arg2]]+ go (FunctionCall (Function "abs" t _) [arg]) = [replaceWith $ fun t (extend c99 "abs" t) [arg]]+ go (FunctionCall (Function "signum" t _) [arg]) = [replaceWith $ fun t (extend c99 "signum" t) [arg]]+ go (FunctionCall (Function "(+)" t _) [arg1, arg2]) = [replaceWith $ binop t "+" arg1 arg2]+ go (FunctionCall (Function "(-)" t _) [ConstExpr (IntConst 0 _), arg2]) = [replaceWith $ fun t "-" [arg2]]+ go (FunctionCall (Function "(-)" t _) [ConstExpr (FloatConst 0), arg2]) = [replaceWith $ fun t "-" [arg2]]+ go (FunctionCall (Function "(-)" t _) [arg1, arg2]) = [replaceWith $ binop t "-" arg1 arg2]+ go (FunctionCall (Function "(*)" t _) [ConstExpr (IntConst (log2 -> Just n) _), arg2]) = [replaceWith $ binop t "<<" arg2 (litI32 n)]+ go (FunctionCall (Function "(*)" t _) [arg1, ConstExpr (IntConst (log2 -> Just n) _)]) = [replaceWith $ binop t "<<" arg1 (litI32 n)]+ go (FunctionCall (Function "(*)" t _) [arg1, arg2]) = [replaceWith $ binop t "*" arg1 arg2]+ go (FunctionCall (Function "(/)" t _) [arg1, arg2]) = [replaceWith $ binop t "/" arg1 arg2]+ go (FunctionCall (Function "div" t _) [arg1, arg2]) = [replaceWith $ StructField (fun div_t (div_f t) [arg1, arg2]) "quot"]+ where div_t = Alias (StructType "div_t" [("quot", t), ("rem", t)]) "div_t"+ div_f (NumType Signed S8) = "div"+ div_f (NumType Signed S16) = "div"+ div_f (NumType Signed S32) = "div"+ div_f (NumType Signed S40) = "ldiv"+ div_f (NumType Signed S64) = "lldiv"+ div_f typ = error $ "div not defined for " ++ show typ+ go (FunctionCall (Function "exp" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "cexpf" [arg]]+ go (FunctionCall (Function "exp" t _) [arg]) = [replaceWith $ fun t "expf" [arg]]+ go (FunctionCall (Function "sqrt" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "csqrtf" [arg]]+ go (FunctionCall (Function "sqrt" t _) [arg]) = [replaceWith $ fun t "sqrtf" [arg]]+ go (FunctionCall (Function "log" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "clogf" [arg]]+ go (FunctionCall (Function "log" t _) [arg]) = [replaceWith $ fun t "logf" [arg]]+ go (FunctionCall (Function "(**)" t@(ComplexType _) _) [arg1, arg2]) = [replaceWith $ fun t "cpowf" [arg1,arg2]]+ go (FunctionCall (Function "(**)" t _) [arg1, arg2]) = [replaceWith $ fun t "powf" [arg1,arg2]]+ go (FunctionCall (Function "logBase" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "logBase" t) [arg1,arg2]]+ go (FunctionCall (Function "sin" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "csinf" [arg]]+ go (FunctionCall (Function "sin" t _) [arg]) = [replaceWith $ fun t "sinf" [arg]]+ go (FunctionCall (Function "tan" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "ctanf" [arg]]+ go (FunctionCall (Function "tan" t _) [arg]) = [replaceWith $ fun t "tanf" [arg]]+ go (FunctionCall (Function "cos" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "ccosf" [arg]]+ go (FunctionCall (Function "cos" t _) [arg]) = [replaceWith $ fun t "cosf" [arg]]+ go (FunctionCall (Function "asin" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "casinf" [arg]]+ go (FunctionCall (Function "asin" t _) [arg]) = [replaceWith $ fun t "asinf" [arg]]+ go (FunctionCall (Function "atan" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "catanf" [arg]]+ go (FunctionCall (Function "atan" t _) [arg]) = [replaceWith $ fun t "atanf" [arg]]+ go (FunctionCall (Function "acos" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "cacosf" [arg]]+ go (FunctionCall (Function "acos" t _) [arg]) = [replaceWith $ fun t "acosf" [arg]]+ go (FunctionCall (Function "sinh" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "csinhf" [arg]]+ go (FunctionCall (Function "sinh" t _) [arg]) = [replaceWith $ fun t "sinhf" [arg]]+ go (FunctionCall (Function "tanh" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "ctanhf" [arg]]+ go (FunctionCall (Function "tanh" t _) [arg]) = [replaceWith $ fun t "tanhf" [arg]]+ go (FunctionCall (Function "cosh" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "ccoshf" [arg]]+ go (FunctionCall (Function "cosh" t _) [arg]) = [replaceWith $ fun t "coshf" [arg]]+ go (FunctionCall (Function "asinh" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "casinhf" [arg]]+ go (FunctionCall (Function "asinh" t _) [arg]) = [replaceWith $ fun t "asinhf" [arg]]+ go (FunctionCall (Function "atanh" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "catanhf" [arg]]+ go (FunctionCall (Function "atanh" t _) [arg]) = [replaceWith $ fun t "atanhf" [arg]]+ go (FunctionCall (Function "acosh" t@(ComplexType _) _) [arg]) = [replaceWith $ fun t "cacoshf" [arg]]+ go (FunctionCall (Function "acosh" t _) [arg]) = [replaceWith $ fun t "acoshf" [arg]]+ go (FunctionCall (Function "atan2" t@FloatType _) [arg1, arg2]) = [replaceWith $ fun t "atan2f" [arg1, arg2]]+ go (FunctionCall (Function "(.&.)" t _) [arg1, arg2]) = [replaceWith $ binop t "&" arg1 arg2]+ go (FunctionCall (Function "(.|.)" t _) [arg1, arg2]) = [replaceWith $ binop t "|" arg1 arg2]+ go (FunctionCall (Function "xor" t _) [arg1, arg2]) = [replaceWith $ binop t "^" arg1 arg2]+ go (FunctionCall (Function "complement" t _) [arg]) = [replaceWith $ fun t "~" [arg]]+ go (FunctionCall (Function "bit" t _) [arg]) = [replaceWith $ binop t "<<" (litI t 1) arg]+ go (FunctionCall (Function "setBit" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "setBit" t) [arg1, arg2]]+ go (FunctionCall (Function "clearBit" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "clearBit" t) [arg1, arg2]]+ go (FunctionCall (Function "complementBit" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "complementBit" t) [arg1, arg2]]+ go (FunctionCall (Function "testBit" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "testBit" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "shiftL" t _) [arg1, arg2]) = [replaceWith $ binop t "<<" arg1 arg2]+ go (FunctionCall (Function "shiftLU" t _) [arg1, arg2]) = [replaceWith $ binop t "<<" arg1 arg2]+ go (FunctionCall (Function "shiftR" t _) [arg1, arg2]) = [replaceWith $ binop t ">>" arg1 arg2]+ go (FunctionCall (Function "shiftRU" t _) [arg1, arg2]) = [replaceWith $ binop t ">>" arg1 arg2]+ go (FunctionCall (Function "rotateL" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "rotateL" t) [arg1, arg2]]+ go (FunctionCall (Function "rotateR" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "rotateR" t) [arg1, arg2]]+ go (FunctionCall (Function "reverseBits" t _) [arg]) = [replaceWith $ fun t (extend c99 "reverseBits" t) [arg]]+ go (FunctionCall (Function "bitScan" t _) [arg]) = [replaceWith $ fun t (extend c99 "bitScan" $ typeof arg) [arg]]+ go (FunctionCall (Function "bitCount" t _) [arg]) = [replaceWith $ fun t (extend c99 "bitCount" $ typeof arg) [arg]]+ go (FunctionCall (Function "bitSize" _ _) [intWidth . typeof -> Just n]) = [replaceWith $ litI (NumType Unsigned S32) n]+ go (FunctionCall (Function "isSigned" _ _) [intSigned . typeof -> Just b]) = [replaceWith $ litB b]+ go (FunctionCall (Function "complex" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "complex" $ typeof arg1) [arg1,arg2]]+ go (FunctionCall (Function "creal" t _) [arg]) = [replaceWith $ fun t "crealf" [arg]]+ go (FunctionCall (Function "cimag" t _) [arg]) = [replaceWith $ fun t "cimagf" [arg]]+ go (FunctionCall (Function "conjugate" t _) [arg]) = [replaceWith $ fun t "conjf" [arg]]+ go (FunctionCall (Function "magnitude" t _) [arg]) = [replaceWith $ fun t "cabsf" [arg]]+ go (FunctionCall (Function "phase" t _) [arg]) = [replaceWith $ fun t "cargf" [arg]]+ go (FunctionCall (Function "mkPolar" t _) [arg1, arg2]) = [replaceWith $ fun t (extend c99 "mkPolar" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "cis" t _) [arg]) = [replaceWith $ fun t (extend c99 "cis" $ typeof arg) [arg]]+ go (FunctionCall (Function "f2i" t _) [arg]) = [replaceWith $ Cast t $ fun FloatType "truncf" [arg]]+ go (FunctionCall (Function "i2n" (ComplexType t) _) [arg]) = [replaceWith $ fun (ComplexType t) (extend c99 "complex" t) [Cast t arg, litF 0]]+ go (FunctionCall (Function "i2n" t _) [arg]) = [replaceWith $ Cast t arg]+ go (FunctionCall (Function "b2i" t _) [arg]) = [replaceWith $ Cast t arg]+ go (FunctionCall (Function "round" t _) [arg]) = [replaceWith $ Cast t $ fun FloatType "roundf" [arg]]+ go (FunctionCall (Function "ceiling" t _) [arg]) = [replaceWith $ Cast t $ fun FloatType "ceilf" [arg]]+ go (FunctionCall (Function "floor" t _) [arg]) = [replaceWith $ Cast t $ fun FloatType "floorf" [arg]]+ go _ = []+ tic64xRules :: [Rule]-tic64xRules = [rule tic64x]+tic64xRules = [rule go] where- tic64x (Fun t "(==)" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "equal" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "(/=)" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t "!" [Fun t (extend "equal" $ typeof arg1) [arg1, arg2]]]- tic64x (Fun t "abs" [arg@(typeof -> Floating)]) = [replaceWith $ Fun t "_fabs" [arg]]- tic64x (Fun t "abs" [arg@(typeof -> I32)]) = [replaceWith $ Fun t "_abs" [arg]]- tic64x (Fun t "(+)" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "add" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "(-)" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "sub" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "(*)" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "mult" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "(/)" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "div" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "exp" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "exp" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "sqrt" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "sqrt" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "log" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "log" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "(**)" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "cpow" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t "logBase" [arg1@(typeof -> Complex _), arg2]) = [replaceWith $ Fun t (extend "logBase" $ typeof arg1) [arg1, arg2]]- tic64x (Fun t fn [arg@(typeof -> Complex _)])- | fn `elem` ["sin","tan","cos","asin","atan","acos","sinh","tanh","cosh","asinh","atanh","acosh","creal","cimag","conjugate","magnitude","phase"]- = [replaceWith $ Fun t (extend fn $ typeof arg) [arg]]- tic64x (Fun t "rotateL" [arg1@(typeof -> U32), arg2]) = [replaceWith $ Fun t "_rotl" [arg1, arg2]]- tic64x (Fun t "reverseBits" [arg@(typeof -> U32)]) = [replaceWith $ Fun t "_bitr" [arg]]- tic64x (Fun t "bitCount" [arg@(typeof -> U32)]) = [replaceWith $ Fun t "_dotpu4" [Fun t "_bitc4" [arg], LitI U32 0x01010101]]- tic64x (Fun t _ [arg@(typeof -> Complex _)]) = [replaceWith $ Fun t (extend "creal" $ typeof arg) [arg]]- tic64x _ = []+ go (FunctionCall (Function "(==)" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "equal" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "(/=)" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t "!" [fun t (extend tic64x "equal" $ typeof arg1) [arg1, arg2]]]+ go (FunctionCall (Function "abs" t _) [arg@(typeof -> FloatType)]) = [replaceWith $ fun t "_fabs" [arg]]+ go (FunctionCall (Function "abs" t _) [arg@(typeof -> (NumType Signed S32))]) = [replaceWith $ fun t "_abs" [arg]]+ go (FunctionCall (Function "(+)" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "add" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "(-)" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "sub" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "(*)" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "mult" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "(/)" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "div" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "exp" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "exp" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "sqrt" t _ ) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "sqrt" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "log" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "log" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "(**)" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "cpow" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function "logBase" t _) [arg1@(typeof -> ComplexType _), arg2]) = [replaceWith $ fun t (extend tic64x "logBase" $ typeof arg1) [arg1, arg2]]+ go (FunctionCall (Function fn t _) [arg@(typeof -> ComplexType _)])+ | fn `elem` ["sin","tan","cos","asin","atan","acos","sinh","tanh","cosh","asinh","atanh","acosh","creal","cimag","conjugate","magnitude","phase"]+ = [replaceWith $ fun t (extend tic64x fn $ typeof arg) [arg]]+ go (FunctionCall (Function "rotateL" t _) [arg1@(typeof -> (NumType Unsigned S32)), arg2]) = [replaceWith $ fun t "_rotl" [arg1, arg2]]+ go (FunctionCall (Function "reverseBits" t _) [arg@(typeof -> (NumType Unsigned S32))]) = [replaceWith $ fun t "_bitr" [arg]]+ go (FunctionCall (Function "bitCount" t _) [arg@(typeof -> (NumType Unsigned S32))]) = [replaceWith $ fun t "_dotpu4" [fun t "_bitc4" [arg], litI32 0x01010101]]+ go (FunctionCall (Function _ t _) [arg@(typeof -> ComplexType _)]) = [replaceWith $ fun t (extend tic64x "creal" $ typeof arg) [arg]]+ go _ = [] traceRules :: [Rule] traceRules = [rule trace] where- trace (Fun t "trace" [lab, val]) = [WithId acts]+ trace (FunctionCall (Function "trace" t _) [lab, val]) = [WithId acts] where acts i = [replaceWith trcVar, propagate decl, propagate trc, propagate frame] where- trcVar = Var t trcVarName+ v = Variable t trcVarName+ trcVar = varToExpr v trcVarName = "trc" ++ show i- defTrcVar = Def t trcVarName- decl (Bl defs prg) = [replaceWith $ Bl (defs ++ [defTrcVar]) prg]- trc :: Prog -> [Action (Repr Prog)]- trc instr = [replaceWith $ Seq [trcVar := val,trcCall,instr]]- trcCall = Call (extend' "trace" t) [In trcVar, In lab]- frame (ProcDf pname ins outs prg) = [replaceWith $ ProcDf pname ins outs prg']+ defTrcVar = Declaration v Nothing+ decl :: Block () -> [Action (Block ())]+ decl (Block defs prg) = [replaceWith $ Block (defs ++ [defTrcVar]) prg]+ trc :: Program () -> [Action (Program ())]+ trc instr = [replaceWith $ Sequence [Assign trcVar val,trcCall,instr]]+ trcCall = call (extend' "trace" t) [ValueParameter trcVar, ValueParameter lab]+ frame (Proc pname ins outs (Just prg)) = [replaceWith $ Proc pname ins outs prg'] where- prg' = case prg of- Seq (Call "traceStart" [] : _) -> prg- Block _ (Seq (Call "traceStart" [] : _)) -> prg- _ -> Seq [Call "traceStart" [], prg, Call "traceEnd" []]+ prg' = Just $ case prg of+ Block _ (Sequence (ProcedureCall "traceStart" [] : _)) -> prg+ Block ds ps -> Block ds (Sequence [call "traceStart" [], ps, call "traceEnd" []]) trace _ = [] -extend :: String -> Type -> String-extend s t = s ++ "_fun_" ++ show t+extend :: Platform -> String -> Type -> String+extend Platform{..} s t = s ++ "_fun_" ++ fromMaybe (show t) (lookup t types) extend' :: String -> Type -> String extend' s t = s ++ "_" ++ show t log2 :: Integer -> Maybe Integer log2 n- | n == 2 Prelude.^ l = Just l- | otherwise = Nothing+ | n == 2 Prelude.^ l = Just l+ | otherwise = Nothing where- l = toInteger $ length $ takeWhile (<=n) $ map (2 Prelude.^) [1..]+ l = toInteger $ length $ takeWhile (<n) $ iterate (*2) 1 first, second :: String first = "member1"
− lib/Feldspar/Compiler/Backend/C/Plugin/BlockProgramHandler.hs
@@ -1,78 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler where--import Feldspar.Transformation---- ===========================================================================--- == Type definition generator plugin--- ===========================================================================--data BlockProgramHandler = BlockProgramHandler--instance Default [Declaration ()] where- def = []--instance Combine [Declaration ()] where- combine a b = a ++ b--instance Transformation BlockProgramHandler where- type From BlockProgramHandler = ()- type To BlockProgramHandler = ()- type Down BlockProgramHandler = ()- type Up BlockProgramHandler = [Declaration ()]- type State BlockProgramHandler = ()--instance Transformable BlockProgramHandler Block where- transform t s d b = tr- { result = (result tr)- { locals = locals (result tr) ++ up tr- }- , up = []- }- where- tr = defaultTransform t s d b--instance Transformable BlockProgramHandler Program where- transform t s d p =- case result tr of- BlockProgram b _ -> Result (blockBody b) () (locals b ++ up tr)- _ -> tr- where- tr = defaultTransform t s d p---instance Plugin BlockProgramHandler where- type ExternalInfo BlockProgramHandler = ()- executePlugin BlockProgramHandler _ procedure = - result $ transform BlockProgramHandler ({-state-}) () procedure
− lib/Feldspar/Compiler/Backend/C/Plugin/Locator.hs
@@ -1,232 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.------ Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:------ * Redistributions of source code must retain the above copyright notice,--- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.------ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE--- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Backend.C.Plugin.Locator where--import Feldspar.Transformation-import Feldspar.Compiler.Backend.C.CodeGeneration-import Feldspar.Compiler.Backend.C.Plugin.PrettyPrint----- ===========================================================================--- == GetPrg plugin--- ===========================================================================---instance Default Bool where- def = False--instance Default (Program DebugToCSemanticInfo) where- def = Empty ((0,0),(0,0)) ((0,0),(0,0))--instance Combine Bool where- combine l1 l2 = l1 || l2--instance Combine (Program DebugToCSemanticInfo) where- combine Empty{} p2 = p2- combine p1 _ = p1----------------------------------------------------------- GetPrg plugin for ParLoop--------------------------------------------------------data GetPrgParLoop = GetPrgParLoop--instance Transformation GetPrgParLoop where- type From GetPrgParLoop = DebugToCSemanticInfo- type To GetPrgParLoop = DebugToCSemanticInfo- type Down GetPrgParLoop = (Int, Int) - type Up GetPrgParLoop = (Bool, Program DebugToCSemanticInfo)- type State GetPrgParLoop = ()---instance Plugin GetPrgParLoop where- type ExternalInfo GetPrgParLoop = (Int, Int)- executePlugin GetPrgParLoop (line, col) procedure =- result $ transform GetPrgParLoop () (line, col) procedure--getPrgParLoop :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)-getPrgParLoop (line, col) procedure = up res where- res = transform GetPrgParLoop () (line, col) procedure --instance Transformable GetPrgParLoop Program where- transform t () (line, col) pl@(ParLoop _ _ _ prog inf1 _) = Result pl () info where- info = case contains (line, col) inf1 of- True -> infoCr where- res = transform t () (line, col) prog- infoCr = if fst $ up res then up res else (True, pl)- _ -> def- transform t () (line, col) pr = defaultTransform t () (line, col) pr----------------------------------------------------------- GetPrg plugin for Assign--------------------------------------------------------data GetPrgAssign = GetPrgAssign--instance Transformation GetPrgAssign where- type From GetPrgAssign = DebugToCSemanticInfo- type To GetPrgAssign = DebugToCSemanticInfo- type Down GetPrgAssign = (Int, Int) - type Up GetPrgAssign = (Bool, Program DebugToCSemanticInfo)- type State GetPrgAssign = ()---instance Plugin GetPrgAssign where- type ExternalInfo GetPrgAssign = (Int, Int)- executePlugin GetPrgAssign (line, col) procedure =- result $ transform GetPrgAssign () (line, col) procedure--getPrgAssign :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)-getPrgAssign (line, col) procedure = up res where- res = transform GetPrgAssign () (line, col) procedure --instance Transformable GetPrgAssign Program where- transform _ () (line, col) assign@(Assign _ _ inf1 _) = Result assign () info where- info = if contains (line, col) inf1 then (True, assign) else def- transform t () (line, col) pr = defaultTransform t () (line, col) pr------------------------------------------------------------ GetPrg plugin for Branch--------------------------------------------------------data GetPrgBranch = GetPrgBranch--instance Transformation GetPrgBranch where- type From GetPrgBranch = DebugToCSemanticInfo- type To GetPrgBranch = DebugToCSemanticInfo- type Down GetPrgBranch = (Int, Int) - type Up GetPrgBranch = (Bool, Program DebugToCSemanticInfo)- type State GetPrgBranch = ()---instance Plugin GetPrgBranch where- type ExternalInfo GetPrgBranch = (Int, Int)- executePlugin GetPrgBranch (line, col) procedure =- result $ transform GetPrgBranch () (line, col) procedure--getPrgBranch :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)-getPrgBranch (line, col) procedure = up res where- res = transform GetPrgBranch () (line, col) procedure --instance Transformable GetPrgBranch Program where- transform t () (line, col) br@(Branch _ prog1 prog2 inf1 _) = Result br () info where- info = case contains (line, col) inf1 of- True -> infoCr where- res1 = transform t () (line, col) prog1- res2 = transform t () (line, col) prog2- res = combine (up res1) (up res2)- infoCr = if fst res then res else (True,br)- _ -> def-- transform t () (line, col) pr = defaultTransform t () (line, col) pr----------------------------------------------------------- GetPrg plugin for ProcedureCall--------------------------------------------------------data GetPrgProcCall = GetPrgProcCall--instance Transformation GetPrgProcCall where- type From GetPrgProcCall = DebugToCSemanticInfo- type To GetPrgProcCall = DebugToCSemanticInfo- type Down GetPrgProcCall = (Int, Int) - type Up GetPrgProcCall = (Bool, Program DebugToCSemanticInfo)- type State GetPrgProcCall = ()---instance Plugin GetPrgProcCall where- type ExternalInfo GetPrgProcCall = (Int, Int)- executePlugin GetPrgProcCall (line, col) procedure =- result $ transform GetPrgProcCall () (line, col) procedure--getPrgProcCall :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)-getPrgProcCall (line, col) procedure = up res where- res = transform GetPrgProcCall () (line, col) procedure --instance Transformable GetPrgProcCall Program where- transform _ () (line, col) pc@(ProcedureCall _ _ inf1 _) = Result pc () info where- info = if contains (line,col) inf1 then (True,pc) else def- transform t () (line, col) pr = defaultTransform t () (line, col) pr----------------------------------------------------------- GetPrg plugin for SeqLoop--------------------------------------------------------data GetPrgSeqLoop = GetPrgSeqLoop--instance Transformation GetPrgSeqLoop where- type From GetPrgSeqLoop = DebugToCSemanticInfo- type To GetPrgSeqLoop = DebugToCSemanticInfo- type Down GetPrgSeqLoop = (Int, Int) - type Up GetPrgSeqLoop = (Bool, Program DebugToCSemanticInfo)- type State GetPrgSeqLoop = ()---instance Plugin GetPrgSeqLoop where- type ExternalInfo GetPrgSeqLoop = (Int, Int)- executePlugin GetPrgSeqLoop (line, col) procedure =- result $ transform GetPrgSeqLoop () (line, col) procedure--getPrgSeqLoop :: (Int, Int) -> Module DebugToCSemanticInfo -> (Bool, Program DebugToCSemanticInfo)-getPrgSeqLoop (line, col) procedure = up res where- res = transform GetPrgSeqLoop () (line, col) procedure--instance Transformable GetPrgSeqLoop Program where- transform t () (line, col) sl@(SeqLoop _ _ prog inf1 _) = Result sl () info where- info = case contains (line, col) inf1 of- True -> infoCr where- res = transform t () (line, col) prog- infoCr = if fst $ up res then up res else (True, sl)- _ -> def- transform t () (line, col) pr = defaultTransform t () (line, col) pr----------------------------------------------------------- Helper functions----------------------------------------------------contains :: (Ord a, Ord b) => (a,b) -> ((a,b),(a,b)) -> Bool-contains (line, col) ((bl, bc), (el, ec)) = (line == bl && bc <= col) || (bl < line && line < el) || (line == el && col <= ec)--myShow :: Program DebugToCSemanticInfo -> String-myShow (Assign l r inf1 _) = "Assign \n" ++ ind show l ++ "\n=\n" ++ ind show r ++ "\n" ++ show inf1 ++ "\n"-myShow (Sequence progs inf1 _) = "Sequence\n" ++ ind (listprint myShow "\n") progs ++ "\n" ++ show inf1 ++ "\n"-myShow (Branch _ tb eb inf1 _) = "Branch\n" ++ ind myShowB tb ++ "\nelse\n" ++ ind myShowB eb ++ "\n" ++ show inf1 ++ "\n"-myShow (ParLoop count bound step block inf1 _)- = "ParLoop\n count: " ++ show count ++ "\n bound: " ++ show bound ++ "\n step: " ++ show step ++ "\n" ++ ind myShowB block ++ "\n" ++ show inf1 ++ "\n"-myShow x = show x--myShowB :: Block DebugToCSemanticInfo -> String-myShowB (Block ls prg inf) = "Block\n" ++ ind show ls ++"\n" ++ ind myShow prg ++ show inf-
− lib/Feldspar/Compiler/Backend/C/Plugin/PrettyPrint.hs
@@ -1,714 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Backend.C.Plugin.PrettyPrint where--import Feldspar.Transformation-import Feldspar.Compiler.Backend.C.CodeGeneration-import Feldspar.Compiler.Backend.C.Options--import qualified Data.List as List (find, intercalate)-import qualified Control.Monad.State as StateMonad (get, put, runState)---- ===========================================================================--- == DebugToC plugin--- ===========================================================================--data DebugToC = DebugToC--data DebugToCSemanticInfo--instance Annotation DebugToCSemanticInfo Module where- type Label DebugToCSemanticInfo Module = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Entity where- type Label DebugToCSemanticInfo Entity = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Struct where- type Label DebugToCSemanticInfo Struct = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo ProcDef where- type Label DebugToCSemanticInfo ProcDef = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo ProcDecl where- type Label DebugToCSemanticInfo ProcDecl = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo StructMember where- type Label DebugToCSemanticInfo StructMember = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Block where- type Label DebugToCSemanticInfo Block = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Program where- type Label DebugToCSemanticInfo Program = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Empty where- type Label DebugToCSemanticInfo Empty = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Assign where- type Label DebugToCSemanticInfo Assign = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo ProcedureCall where- type Label DebugToCSemanticInfo ProcedureCall = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Spawn where- type Label DebugToCSemanticInfo Spawn = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Run where- type Label DebugToCSemanticInfo Run = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Sequence where- type Label DebugToCSemanticInfo Sequence = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Branch where- type Label DebugToCSemanticInfo Branch = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo SeqLoop where- type Label DebugToCSemanticInfo SeqLoop = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo ParLoop where- type Label DebugToCSemanticInfo ParLoop = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo ActualParameter where- type Label DebugToCSemanticInfo ActualParameter = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Declaration where- type Label DebugToCSemanticInfo Declaration = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Expression where- type Label DebugToCSemanticInfo Expression = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo FunctionCall where- type Label DebugToCSemanticInfo FunctionCall = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo SizeOf where- type Label DebugToCSemanticInfo SizeOf = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo ArrayElem where- type Label DebugToCSemanticInfo ArrayElem = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo StructField where- type Label DebugToCSemanticInfo StructField = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Constant where- type Label DebugToCSemanticInfo Constant = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo IntConst where- type Label DebugToCSemanticInfo IntConst = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo FloatConst where- type Label DebugToCSemanticInfo FloatConst = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo BoolConst where- type Label DebugToCSemanticInfo BoolConst = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo ArrayConst where- type Label DebugToCSemanticInfo ArrayConst = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo ComplexConst where- type Label DebugToCSemanticInfo ComplexConst = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Variable where- type Label DebugToCSemanticInfo Variable = ((Int, Int), (Int, Int))--instance Annotation DebugToCSemanticInfo Cast where- type Label DebugToCSemanticInfo Cast = ((Int, Int), (Int, Int))- -instance Annotation DebugToCSemanticInfo Comment where- type Label DebugToCSemanticInfo Comment = ((Int, Int), (Int, Int))---instance Transformation DebugToC where- type From DebugToC = ()- type To DebugToC = DebugToCSemanticInfo- type Down DebugToC = (Options, Place, Int) -- Platform, Place and Indentation- type Up DebugToC = String- type State DebugToC = (Int, Int)--instance Plugin DebugToC where- type ExternalInfo DebugToC = ((Options, Place), Int)- executePlugin DebugToC ((options, place), line) procedure =- result $ transform DebugToC (line, 0) (options, place, 0) procedure--compToC :: ((Options, Place), Int) -> Module () -> (String, (Int, Int))-compToC ((options, place), line) procedure = (up res, state res) where- res = transform DebugToC (line, 0) (options, place, 0) procedure--compToCWithInfos :: ((Options, Place), Int) -> Module () -> (Module DebugToCSemanticInfo, (String, (Int, Int)))-compToCWithInfos ((options, place), line) procedure = (result res, (up res, state res)) where- res = transform DebugToC (line, 0) (options, place, 0) procedure--instance Transformable DebugToC Variable where- transform _ (line, col) (options, place, _) x@(Variable vname typ role _) = Result (Variable vname typ role newInf) (snd newInf) cRep- where- (newInf, (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code $ toC options place x- (_, nl, nc) <- StateMonad.get- return ((line, col), (nl, nc))--instance Transformable1 DebugToC [] Constant where- transform1 t pos down l = transform1' t pos down l ", " 0--instance Transformable DebugToC Constant where- transform t pos down cnst@(IntConst c _ _ _) = transformConst t pos down cnst (show c)-- transform t pos down cnst@(FloatConst c _ _) = transformConst t pos down cnst (show c ++ "f")-- transform t pos down cnst@(BoolConst False _ _) = transformConst t pos down cnst "0"-- transform t pos down cnst@(BoolConst True _ _) = transformConst t pos down cnst "1"-- transform t (line, col) (options, place, indent) cnst@(ComplexConst real im _ _)- = case List.find (\(t',_) -> t' == typeof cnst) $ values $ platform options of- Just (_,f) -> - Result (ComplexConst (result newReal) (result newIm) newInf newInf) (snd newInf) cRep - where- ((newReal, newIm, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- nr <- complexTransform t (options, place, indent) real- ni <- complexTransform t (options, place, indent) im- code $ f cnst- (_, nl, nc) <- StateMonad.get- return (nr, ni, ((line,col),(nl,nc)))- Nothing -> - Result (ComplexConst (result newReal) (result newIm) newInf newInf) (snd newInf) cRep- where- ((newReal, newIm, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code "complex("- nr <- monadicTransform' t (options, place, indent) real- code ","- ni <- monadicTransform' t (options, place, indent) im- code ")"- (_, nl, nc) <- StateMonad.get- return (nr, ni, ((line,col),(nl,nc)))--instance Transformable DebugToC ActualParameter where- transform t pos down act@(In (VarExpr (Variable _ StructType{} _ _) _) _) =- transformActParam t pos down act AddressNeed_pl- transform t pos down act@(In (VarExpr (Variable _ ArrayType{} _ _) _) _) =- transformActParam t pos down act AddressNeed_pl- transform t pos down act@In{} = transformActParam t pos down act FunctionCallIn_pl- transform t pos down act@Out{} = transformActParam t pos down act AddressNeed_pl- transform t pos down act@TypeParameter{} = transformActParam t pos down act MainParameter_pl- transform t pos down act@FunParameter{} = transformActParam t pos down act FunctionCallIn_pl--instance Transformable1 DebugToC [] Expression where- transform1 t pos down l = transform1' t pos down l ", " 0--instance Transformable DebugToC Expression where- transform t (line, col) (options, place, indent) (VarExpr val _) = Result (VarExpr (result newVal) newInf) (snd newInf) cRep- where- ((newVal, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- nv <- monadicTransform' t (options, place, indent) val- (_, nl, nc) <- StateMonad.get- return (nv, ((line,col),(nl,nc)))-- transform t (line, col) (options, place, indent) e@(ArrayElem n index _ _) = Result (ArrayElem (result newName) (result newIndex) newInf newInf) (snd newInf) cRep - where- ((newName, newIndex, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- let prefix = case (place, typeof e) of- (AddressNeed_pl, _) -> "&"- (_, ArrayType _ _) -> "&" -- TODO the call site should set the place to AddressNeed_pl for Arrays- _ -> ""- code $ prefix ++ "at(" ++ showType options Value Declaration_pl (typeof e) NoRestrict ++ ","- nn <- monadicTransform' t (options, AddressNeed_pl, indent) n- code ","- ni <- monadicTransform' t (options, ValueNeed_pl, indent) index- code ")"- (_, nl, nc) <- StateMonad.get- return (nn, ni, ((line,col),(nl,nc)))-- transform t pos down expr@(StructField _ field _ _) = transformExpr pos down ('.' : field) ValueNeed_pl- where- transformExpr (line, col) (options, place, indent) str paramType = Result (newExpr expr) (snd newInf) cRep- where- newExpr (StructField _ s _ _ ) = StructField (result newTarget) s newInf newInf- getExpr (StructField e _ _ _ ) = e- prefix = case (place, typeof expr) of- (AddressNeed_pl, _) -> "&"- (_, ArrayType _ _) -> "&"- _ -> ""- ((newTarget, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code prefix- nt <- monadicTransform' t (options, paramType, indent) (getExpr expr)- code str- (_, nl, nc) <- StateMonad.get- return (nt, ((line,col),(nl,nc)))--- transform t (line, col) (options, place, indent) (ConstExpr val _) = Result (ConstExpr (result newVal) newInf) (snd newInf) cRep- where- ((newVal, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- nv <- monadicTransform' t (options, place, indent) val- (_, nl, nc) <- StateMonad.get- return (nv, ((line,col),(nl,nc)))-- transform t pos down fc@(FunctionCall f [_,_] _ _)- | funName f == "!" = transformFuncCall t pos down fc "at(" "," ")"-- transform t pos down fc@(FunctionCall f [_,_] _ _)- | funMode f == Infix = transformFuncCall t pos down fc "(" (" " ++ funName f ++ " ") ")"-- transform t (line, col) (options, _, indent) (FunctionCall f paramlist _ _) =- Result (FunctionCall f (result1 newParamlist) newInf newInf) (snd newInf) cRep - where- ((newParamlist, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code $ funName f ++ "("- npl <- monadicListTransform' t (options, FunctionCallIn_pl, indent) paramlist- code ")"- (_, nl, nc) <- StateMonad.get- return (npl, ((line,col),(nl,nc)))-- transform t (line, col) (options, place, indent) (Cast typ e _ _) = Result (Cast typ (result newExp) newInf newInf) (snd newInf) cRep - where- ((newExp, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code $ concat ["((", toC options place typ, ")("]- ne <- monadicTransform' t (options, place, indent) e- code "))"- (_, nl, nc) <- StateMonad.get- return (ne, ((line,col),(nl,nc)))-- transform _ (line, col) (options, place, _) (SizeOf (Left typ) _ _) = Result (SizeOf (Left typ) newInf newInf) (snd newInf) cRep - where- (newInf, (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code ("sizeof(" ++ toC options place typ ++ ")")- (_, nl, nc) <- StateMonad.get- return ((line, col), (nl, nc))-- transform t (line, col) (options, place, indent) (SizeOf (Right e) _ _) = Result (SizeOf (Right (result newExp)) newInf newInf) (newLine, newCol) cRep - where- ((newExp, newInf), (cRep, newLine, newCol)) = flip StateMonad.runState (defaultState line col) $ do- code "sizeof"- ne <- monadicTransform' t (options, place, indent) e- code ")"- (_, nl, nc) <- StateMonad.get- return (ne, ((line,col),(nl,nc)))--instance Transformable1 DebugToC [] Entity where- transform1 t pos down l = transform1' t pos down l "" 0--instance Transformable DebugToC Module where- transform t (line, col) (options, place, indent) (Module defList _) = Result (Module (result1 newDefList) newInf) (snd newInf) cRep - where- ((newDefList, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- ndl <- monadicListTransform' t (options, place, indent) defList- (_, nl, nc) <- StateMonad.get- return (ndl, ((line,col),(nl,nc)))--instance Transformable1 DebugToC [] Variable where- transform1 t pos down l = transform1' t pos down l ", " 0--instance Transformable1 DebugToC [] StructMember where- transform1 _ (line, col) _ [] = Result1 [] (line, col) ""- transform1 t (line, col) (options, place, indent) (x:xs) = Result1 (result newX : result1 newXs) (state1 newXs) cRep where- ((newX, newXs), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- nx <- monadicTransform' t (options, place, indent) x- nxs <- monadicListTransform' t (options, place, indent) xs- return (nx, nxs)---instance Transformable DebugToC Entity where- transform t (line, col) (options, place, indent) (StructDef n members _ _) = Result (StructDef n (result1 newMembers) newInf newInf) (snd newInf) cRep- where- ((newMembers, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code $ n ++ " {\n"- (crep, cl, cc) <- StateMonad.get- StateMonad.put (crep, cl, cc + addIndent indent)- nms <- monadicListTransform' t (options, place, addIndent indent) members- indenter indent- code "};\n"- (crep, cl, _) <- StateMonad.get- StateMonad.put (crep, cl, indent)- return (nms, ((line,col),(cl,indent)))-- transform _ (line, col) (options, place, indent) (TypeDef typ n _) = Result (TypeDef typ n newInf) (snd newInf) cRep- where- (newInf, (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code $ unwords [ "typedef"- , showType options Value place typ NoRestrict- , n- ]- code ";\n"- (crep, cl, _) <- StateMonad.get- StateMonad.put (crep, cl, indent)- return ((line, col), (cl, indent))-- transform t (line, col) (options, place, indent) (ProcDef n inp outp body _ _) =- Result (ProcDef n (result1 newInParam) (result1 newOutParam) (result newBody) newInf newInf) (snd newInf) cRep- where- ((newInParam, newOutParam, newBody, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- code $ "void " ++ n ++ "("- ninp <- monadicListTransform' t (options, MainParameter_pl, indent) inp- let str- | null inp || null outp = ""- | otherwise = ", "- code str- noutp <- monadicListTransform' t (options, MainParameter_pl, indent) outp- code ")\n"- indenter indent- code "{\n"- (crep, al, _) <- StateMonad.get- StateMonad.put (crep, al, addIndent indent)- nb <- monadicTransform' t (options, Declaration_pl, addIndent indent) body- indenter indent- code "}\n"- (_, nl, _) <- StateMonad.get- return (ninp, noutp, nb, ((line,col),(nl,indent)))-- transform t (line, col) (options, _, indent) (ProcDecl n inp outp _ _) =- Result (ProcDecl n (result1 newInParam) (result1 newOutParam) newInf newInf) (snd newInf) cRep- where- ((newInParam, newOutParam, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- code $ "void " ++ n ++ "("- ninp <- monadicListTransform' t (options, MainParameter_pl, indent) inp- let str- | null inp || null outp = ""- | otherwise = ", "- code str- noutp <- monadicListTransform' t (options, MainParameter_pl, indent) outp- code ");\n"- (_, nl, _) <- StateMonad.get- return (ninp, noutp, ((line,col),(nl,indent)))--displayComment :: Int -> [String] -> String-displayComment indent = unlines . map (putIndent indent ++) . (["/*"] ++) . (++ [" */"]) . map (" * " ++)--displayMemInfo :: String -> [Type] -> String-displayMemInfo n [] = n ++ ": none"-displayMemInfo n info = n ++ ": " ++ List.intercalate ", " (map displayType info)--displayType :: Type -> String-displayType (Alias t _) = displayType t-displayType (ArrayType (LiteralLen n) (ArrayType (LiteralLen m) t)) =- unwords [displayType t, concat ["array(", show n, "x", show m, ")"]]-displayType (ArrayType (LiteralLen n) t) = unwords [displayType t, concat ["array(", show n, ")"]]-displayType (ArrayType UndefinedLen t) = unwords [displayType t, "array"]-displayType (IVarType t) = unwords ["ivar(", displayType t, ")"]-displayType VoidType = "void"-displayType BoolType = "Boolean"-displayType BitType = "bit"-displayType FloatType = "float"-displayType (NumType signed size) = unwords [sg signed, sz size ++ "-bit", "integer"]- where- sg Signed = "signed"- sg Unsigned = "unsigned"- sz S8 = "8"- sz S16 = "16"- sz S32 = "32"- sz S40 = "40"- sz S64 = "64"-displayType (ComplexType t) = unwords ["complex", displayType t]-displayType (UserType s) = s-displayType (StructType _) = "struct"--instance Transformable DebugToC StructMember where- transform _ (line, col) (options, place, _) dsm@(StructMember str typ _) = Result (StructMember str typ newInf) (snd newInf) cRep - where- (newInf, (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- let t = case structMemberType dsm of- ArrayType{} -> showVariable options place Value (structMemberType dsm) (structMemberName dsm) ++ ";"- _ -> toC options place (structMemberType dsm) ++ " " ++ structMemberName dsm ++ ";"- code $ t ++ "\n"- (_, nl, nc) <- StateMonad.get- return ((line, col), (nl, nc))--instance Transformable1 DebugToC [] Declaration where- transform1 _ (line, col) _ [] = Result1 [] (line, col) ""- transform1 t (line, col) (options, place, indent) (x:xs) = Result1 (result newX : result1 newXs) (state1 newXs) ((putIndent indent ++ up newX ++ ";\n" ) ++ up1 newXs) where- newX = transform t (line, col) (options, place, indent) x- (line2, _) = state newX- newSt = (line2 + 1, indent) - newXs = transform1 t newSt (options, place, indent) xs--instance Transformable DebugToC Block where- transform t (line, col) (options, place, indent) (Block locs body _) = Result (Block (result1 newLocs) (result newBody) newInf) (snd newInf) cRep- where- ((newLocs, newBody, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- nlocs <- monadicListTransform' t (options, Declaration_pl, indent) locs- let str = case up1 newLocs of - "" -> ""- _ -> "\n"- code str- nbody <- monadicTransform' t (options, place, indent) body- (_, nl, _) <- StateMonad.get- return (nlocs, nbody, ((line,col),(nl,indent)))--instance Transformable DebugToC Declaration where- transform t (line, col) (options, _, indent) (Declaration dv Nothing _) = Result (Declaration (result newDeclVar) Nothing newInf) (snd newInf) cRep- where- ((newDeclVar, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- ndv <- monadicTransform' t (options, Declaration_pl, indent) dv- case varType dv of- (ArrayType _ _) -> code " = {0}"- _ -> code ""- (_, nl, nc) <- StateMonad.get- return (ndv, ((line,col),(nl,nc)))-- transform t (line, col) (options, _, indent) (Declaration dv (Just e) _) = Result (Declaration (result newDeclVar) (Just (result newExpr)) newInf) (snd newInf) cRep - where- ((newDeclVar, newExpr, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- ndv <- monadicTransform' t (options, Declaration_pl, indent) dv- code " = "- ne <- monadicTransform' t (options, ValueNeed_pl, indent) e- (_, nl, nc) <- StateMonad.get- return (ndv, ne, ((line,col),(nl,nc)))--instance Transformable1 DebugToC [] ActualParameter where- transform1 t pos down l = transform1' t pos down l ", " 0--instance Transformable1 DebugToC [] Program where- transform1 t pos down l = transform1' t pos down l "" 0---instance Transformable DebugToC Program where- transform _ (line, col) _ (Empty _ _) = Result (Empty newInf newInf) newSt cRep where - newSt = (line, col)- newInf = ((line, col), newSt)- cRep = ""-- transform _ (line, col) (_, _, indent) (Comment True comment _ _) = Result (Comment True comment newInf newInf) (snd newInf) cRep - where- (newInf, (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- code $ "/* " ++ comment ++ " */\n"- (_, nl, nc) <- StateMonad.get- return ((line, col), (nl, nc))-- transform _ (line, col) (_, _, indent) (Comment False comment _ _) = Result (Comment False comment newInf newInf) (snd newInf) cRep - where - (newInf, (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- code $ "// " ++ comment ++ "\n"- (_, nl, nc) <- StateMonad.get- return ((line, col), (nl, nc))-- transform t (line, col) (options, _, indent) (Assign lh rh _ _) = Result (Assign (result newLhs) (result newRhs) newInf newInf) (snd newInf) cRep- where- ((newLhs, newRhs, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- nlhs <- monadicTransform' t (options, ValueNeed_pl, indent) lh- code " = "- nrhs <- monadicTransform' t (options, ValueNeed_pl, indent) rh- code ";\n"- (_, nl, _) <- StateMonad.get- return (nlhs, nrhs, ((line,col),(nl,indent)))-- transform t (line, col) (options, place, indent) (ProcedureCall n param _ _) = Result (ProcedureCall n (result1 newParam) newInf newInf) (snd newInf) cRep - where- ((newParam, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- code $ n ++ "("- np <- monadicListTransform' t (options, place, indent) param- code ");\n"- (_, nl, _) <- StateMonad.get- return (np, ((line,col),(nl,indent)))-- transform t (line, col) (options, place, indent) (Sequence prog _ _) = Result (Sequence (result1 newProg) newInf newInf) (snd newInf) cRep - where- ((newProg, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- np <- monadicListTransform' t (options, place, indent) prog- return (np, ((line,col),state1 newProg))-- transform t (line, col) (options, place, indent) (Branch con tPrg ePrg _ _) = Result (Branch (result newCon) (result newTPrg) (result newEPrg) newInf newInf) (snd newInf) cRep - where - ((newCon, newTPrg, newEPrg, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- code "if("- ncon <- monadicTransform' t (options, ValueNeed_pl, indent) con- code ")\n" - indenter indent- code "{\n"- ntPrg <- monadicTransform' t (options, place, addIndent indent) tPrg- indenter indent- code "}\n" - indenter indent - code "else\n" - indenter indent - code "{\n"- nePrg <- monadicTransform' t (options, place, addIndent indent) ePrg- indenter indent - code "}\n"- (_, nl, nc) <- StateMonad.get- return (ncon, ntPrg, nePrg, ((line,col),(nl,nc)))-- transform t (line, col) (options, place, indent) (SeqLoop con conPrg blockPrg _ _) = Result (SeqLoop (result newCon) (result newConPrg) (result newBlockPrg) newInf newInf) (snd newInf) cRep - where- ((newCon, newConPrg, newBlockPrg, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- code "{\n"- ncp <- monadicTransform' t (options, place, addIndent indent) conPrg- indenter $ addIndent indent- code "while("- ncon <- monadicTransform' t (options, ValueNeed_pl, addIndent indent) con- code ")\n" - indenter $ addIndent indent- code "{\n"- nbp <- monadicTransform' t (options, place, addIndent $ addIndent indent) blockPrg- monadicTransform' t (options, place, addIndent $ addIndent indent) (blockBody conPrg)- indenter $ addIndent indent- code "}\n" - indenter indent - code "}\n"- (_, nl, nc) <- StateMonad.get- return (ncon, ncp, nbp, ((line,col),(nl,nc)))-- transform t (line, col) (options, place, indent) (ParLoop count bound step prog _ _) = Result (ParLoop (result newCount) (result newBound) step (result newProg) newInf newInf) (snd newInf) cRep - where- ((newCount, newBound, newProg, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent- code "for("- _ <- monadicTransform' t (options, Declaration_pl, addIndent indent) count- code " = 0; "- loopVariable <- monadicTransform' t (options, ValueNeed_pl, addIndent indent) count- code " < "- nb <- monadicTransform' t (options, ValueNeed_pl, addIndent indent) bound- code $ "; " ++ up loopVariable ++ " += " ++ show step ++ ")\n" - indenter indent- code "{\n"- np <- monadicTransform' t (options, place, addIndent indent) prog- indenter indent- code "}\n" - (_, nl, nc) <- StateMonad.get- return (loopVariable, nb, np, ((line,col),(nl,nc)))-- transform t (line, col) (options, place, indent) (BlockProgram prog _) = Result (BlockProgram (result newProg) newInf) (snd newInf) cRep - where- ((newProg, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- indenter indent - code "{\n"- np <- monadicTransform' t (options, place, addIndent indent) prog- indenter indent - code "}\n"- (_, nl, nc) <- StateMonad.get- return (np, ((line,col),(nl,nc)))--putIndent :: Int -> String-putIndent = concat . flip replicate " "--addIndent :: Int -> Int-addIndent indent = indent + 4--transform1' _ (line, col) _ [] _ _ = Result1 [] (line, col) ""-transform1' t (line, col) (options, place, indent) (x:[]) _ _ = Result1 [result newX] (state newX) (up newX) where- newX = transform t (line, col) (options, place, indent) x-transform1' t (line, col) (options, place, indent) (x:xs) str num = Result1 (result newX : result1 newXs) (state1 newXs) (up newX ++ str ++ up1 newXs) where- newX = transform t (line, col) (options, place, indent) x- (line2, col2) = state newX- newSt = (line2 + num, col2 + length str) - newXs = transform1 t newSt (options, place, indent) xs--transformConst _ (line, col) (options, _, _) (cnst :: Constant ()) str = Result (newConst cnst) (line, newCol) cRep - where- newConst (IntConst c t _ _) = IntConst c t newInf newInf- newConst (FloatConst c _ _) = FloatConst c newInf newInf- newConst (BoolConst c _ _) = BoolConst c newInf newInf- newInf = ((line, col), (line, newCol))- (cRep, _, newCol) = snd $ flip StateMonad.runState (defaultState line col) $ do- let s = case List.find (\(t',_) -> t' == typeof cnst) $ values $ platform options of- Just (_,f) -> f cnst- Nothing -> str- code s--transformActParam _ (line, col) (options, _, _) (TypeParameter typ mode _) _ = Result newParam (snd newInf) cRep - where- newParam = TypeParameter typ mode newInf- place Auto = MainParameter_pl- place Scalar = Declaration_pl- (newInf, (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code $ showType options Value (place mode) typ NoRestrict- (_, nl, nc) <- StateMonad.get- return ((line,col),(nl,nc))--transformActParam _ (line, col) _ (FunParameter n addr _) _ = Result newParam (snd newInf) cRep - where- newParam = FunParameter n addr newInf- (newInf, (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- let addrOp- | addr = "&"- | otherwise = ""- code $ addrOp ++ n- (_, nl, nc) <- StateMonad.get- return ((line, col), (nl, nc))--transformActParam t (line, col) (options, _, indent) act paramType = Result (newActParam act) (snd newInf) cRep - where- newActParam Out{} = Out (result newParam) newInf- newActParam In{} = In (result newParam) newInf- getParam (In param _) = param- getParam (Out param _) = param- ((newParam, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- np <- monadicTransform' t (options, paramType, indent) (getParam act)- (_, nl, nc) <- StateMonad.get- return (np, ((line,col),(nl,nc)))--transformFuncCall t (line, col) (options, place, indent)- (FunctionCall f [a, b] _ _) str1 str2 str3 =- Result (FunctionCall f [result newA, result newB] newInf newInf) (snd newInf) cRep- where- ((newA, newB, newInf), (cRep, _, _)) = flip StateMonad.runState (defaultState line col) $ do- code str1- na <- monadicTransform' t (options, place, indent) a- code str2- nb <- monadicTransform' t (options, place, indent) b- code str3- (_, nl, nc) <- StateMonad.get- return (na, nb, ((line,col),(nl,nc)))--code s = do- (str, line, col) <- StateMonad.get- let numEOF = length (filter (=='\n') s)- StateMonad.put (str++s,line + numEOF, (if numEOF == 0 then col else 0) + length (takeWhile (/='\n') $ reverse s))--indenter n = do- (str, line, col) <- StateMonad.get- StateMonad.put (str ++ concat (replicate n " "), line, col)--monadicTransform' t down d = do- (_, line, col) <- StateMonad.get- let res = transform t (line, col) down d- code $ up res- return res--complexTransform t down d = do- (_, line, col) <- StateMonad.get- return $ transform t (line, col) down d--monadicListTransform' t down l = do- (_, line, col) <- StateMonad.get- let resList = transform1 t (line, col) down l- code $ up1 resList- return resList--defaultState :: Int -> Int -> (String, Int, Int)-defaultState line col = ("", line, col)
lib/Feldspar/Compiler/Backend/C/Plugin/Rule.hs view
@@ -26,6 +26,7 @@ -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- +{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-}@@ -56,7 +57,13 @@ type ExternalInfo RulePlugin = Options executePlugin _ externalInfo = result . transform RulePlugin 0 externalInfo -instance (DefaultTransformable RulePlugin t, Typeable1 t) => Transformable RulePlugin t where+instance ( DefaultTransformable RulePlugin t+#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 708+ , Typeable t+#else+ , Typeable1 t+#endif+ ) => Transformable RulePlugin t where transform t s d orig = recurse { result = x'', up = pr1 ++ pr2 ++ pr3, state = newID2 } where recurse = defaultTransform t s d orig
− lib/Feldspar/Compiler/Backend/C/Plugin/TypeCorrector.hs
@@ -1,199 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Backend.C.Plugin.TypeCorrector where--import qualified Data.Map as Map-import Feldspar.Transformation-import Feldspar.Compiler.Backend.C.CodeGeneration-import Feldspar.Compiler.Error---- ===========================================================================--- == Type corrector plugin--- ===========================================================================--- TODO: IS THIS STILL NEEDED? --typeCorrectorError :: String -> a-typeCorrectorError = handleError "PluginArch/TypeCorrector" InternalError--type TypeCatalog = Map.Map String Type--instance Default TypeCatalog where- def = Map.empty---- first collect types of global variables-data GlobalCollector = GlobalCollector-instance Transformation GlobalCollector where- type From GlobalCollector = ()- type To GlobalCollector = ()- type Down GlobalCollector = Bool -- variable is global- type Up GlobalCollector = ()- type State GlobalCollector = TypeCatalog---instance Transformable GlobalCollector Entity where- transform t s _ = defaultTransform t s False--instance Transformable GlobalCollector Variable where- transform _ s d v@(Variable name typ _ ()) = Result v s' () where- s'- | d = Map.insert name typ s- | otherwise = s--data TypeCheckDown = TypeCheckDown- { globals :: TypeCatalog- , inDeclaration :: Bool- }--inDecl :: TypeCheckDown -> Bool -> TypeCheckDown-inDecl d b = d {inDeclaration = b}--instance Default [String] where- def = []-instance Combine [String] where- combine = (++)---- get globals as state collect types of variables in a procedure, then corrert types-data TypeCheck = TypeCheck-instance Transformation TypeCheck where- type From TypeCheck = ()- type To TypeCheck = ()- type Down TypeCheck = TypeCheckDown -- globals variable's type, in a declaration- type Up TypeCheck = [String] -- errors- type State TypeCheck = TypeCatalog -- local variable's types- -instance Transformable TypeCheck Entity where- transform t _ d p@ProcDef{} = defaultTransform t s' d' p where- s' = def -- start with an empty local variable type catalog- d' = inDecl d True --input parameters are declarations (block will correct where it isn't good)- transform _ s _ p = Result p s def -- just definitions, not implementation, not need check/correct- -instance Transformable TypeCheck Block where- transform t s d b = tr- { result = (result tr)- { blockBody = mkSeq (err (up tr)) $ blockBody $ result tr- }- , state = s -- forget locals- , up = []- }- where- tr = defaultTransform t s (inDecl d False) b -- we are'n in declaration (correct the procedure's change)- mkSeq (Empty _ _) x = x- mkSeq p (Sequence ps _ _) = Sequence (p:ps) () ()- mkSeq p p2 = Sequence [p, p2] () ()- err [] = Empty () ()- err x = Comment True (listprint id "\n " $ uniq x) () ()- uniq [] = []- uniq (x:xs) = x : uniq (filter (/= x) xs)--instance Transformable TypeCheck Declaration where- transform t s d (Declaration v i inf) = Result (Declaration (result tr1) (result1 tr2) $ convert inf) (state1 tr2) (combine (up tr1) (up1 tr2)) where- tr1 = transform t s (inDecl d True) v- tr2 = transform1 t (state tr1) d i--instance Transformable TypeCheck Program where- transform t s d (ParLoop v b i p inf1 inf2) = Result (ParLoop (result tr1) (result tr2) i (result tr3) (convert inf1) $ convert inf2) s' (foldl combine (up tr1) [up tr2, up tr3]) where- tr1 = transform t s (inDecl d True) v -- loop variable is an undeclared local- tr2 = transform t (state tr1) d b- tr3 = transform t (state tr2) d p- s' = s -- forget loop variable (no other new var can be here, other news deleted at block)- transform t s d p = defaultTransform t s d p--instance Transformable TypeCheck Variable where- transform _ s d v@(Variable name typ _ ()) - | inDeclaration d = Result v (Map.insert name typ s) def- | otherwise = Result v s u' where- u' = case Map.lookup name allVar of- Just typ2- | typ == typ2 -> []- | otherwise -> ["Inconsistent types: " ++ name ++ " (actual type: " ++show typ ++ ", declared type: " ++ show typ2 ++ ")"]- Nothing -> ["Undeclared variable: " ++ name]- allVar :: TypeCatalog- allVar = Map.unionWith const (globals d) s--data TypeCorrector = TypeCorrector-instance Transformation TypeCorrector where- type From TypeCorrector = ()- type To TypeCorrector = ()- type Down TypeCorrector = TypeCatalog -- global variable's type, in a declaration- type Up TypeCorrector = ()- type State TypeCorrector = TypeCatalog -- local variable's types--instance Transformable TypeCorrector Entity where- transform t _ d p@ProcDef{} = defaultTransform t (state tr) d p where- tr = defaultTransform t def d p -- start with an empty local variable type catalog- transform _ s _ p = Result p s def -- just definitions, not implementation, not need check/correct--instance Transformable TypeCorrector Variable where- transform _ ls gs v@(Variable name typ _ ()) = Result v' (Map.insert name typ' ls) def where- v' = v {varType = typ'}- typ' = case Map.lookup name allVar of- Just typ2- | typ == typ2 -> typ2- | otherwise -> select typ typ2- Nothing -> typ- allVar = Map.unionWith const gs ls--select :: Type -> Type -> Type-select act decl- | ok = typ- | otherwise = decl- where- (ok,typ) = select' act decl- select' (ComplexType t1) (ComplexType t2) = (o, ComplexType t) where- (o,t) = select' t1 t2- select' (ArrayType l1 t1) (ArrayType l2 t2) = (o && o2, ArrayType l t) where- (o,t) = select' t1 t2- (o2,l) = select'' l1 l2- select'' UndefinedLen x = (True, x)- select'' x UndefinedLen = (True, x)- select'' (LiteralLen a) (LiteralLen b) = (a==b, LiteralLen b)- select' (StructType t1) (StructType t2) = (o, StructType t) where- (o,t) = select'' t1 t2- select'' [] [] = (True, [])- select'' [] _ = (False, undefined)- select'' _ [] = (False, undefined)- select'' ((a,st1):ts1) ((b,st2):ts2) = ( a==b && oo && ooo, (a,tt):tts) where- (oo,tt) = select' st1 st2- (ooo,tts) = select'' ts1 ts2- select' t1 t2- | t1 == t2 = (True, t1)- | otherwise = (False, undefined)--instance Plugin TypeCorrector where- type ExternalInfo TypeCorrector = Bool- executePlugin TypeCorrector showErr procedure = - result $ transform TypeCorrector def gs x where- gs = state $ transform GlobalCollector def False procedure- x - | showErr = result $ transform TypeCheck def (TypeCheckDown gs False) procedure- | otherwise = procedure
− lib/Feldspar/Compiler/Backend/C/Plugin/TypeDefinitionGenerator.hs
@@ -1,87 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator where--import Data.List-import Feldspar.Transformation-import Feldspar.Compiler.Backend.C.CodeGeneration-import Feldspar.Compiler.Backend.C.Options-import Feldspar.Compiler.Error---- ===========================================================================--- == Type definition generator plugin--- ===========================================================================--typeDefGenError :: ErrorClass -> String -> a-typeDefGenError = handleError "PluginArch/TypeDefinitionGenerator"--data TypeDefinitionGenerator = TypeDefinitionGenerator--getTypes :: Options -> Type -> [Entity ()]-getTypes options typ = {-trace ("DEBUG: "show typ) $-} case typ of- StructType members -> concatMap (\(_,t) -> getTypes options t) members- ++ [StructDef {- structName = toC options Declaration_pl (StructType members),- structMembers = map (\(n,t) -> StructMember n t ()) members,- structLabel = (),- definitionLabel = ()- }]- ArrayType _ baseType -> getTypes options baseType- _ -> []- -- XXX complexType?--instance Transformation TypeDefinitionGenerator where- type From TypeDefinitionGenerator = ()- type To TypeDefinitionGenerator = ()- type Down TypeDefinitionGenerator = Options- type Up TypeDefinitionGenerator = ()- type State TypeDefinitionGenerator = [Entity ()]--instance Transformable TypeDefinitionGenerator Module where- transform selfpointer origState fromAbove origModule = defaultTransformationResult {- result = (result defaultTransformationResult) {- entities = nub (state defaultTransformationResult)- ++ entities (result defaultTransformationResult)- }- } where- defaultTransformationResult = defaultTransform selfpointer origState fromAbove origModule--instance Transformable TypeDefinitionGenerator Variable where- transform selfpointer origState fromAbove origVariable = defaultTransformationResult {- state = state defaultTransformationResult ++ getTypes fromAbove (varType origVariable)- } where- defaultTransformationResult = defaultTransform selfpointer origState fromAbove origVariable--instance Plugin TypeDefinitionGenerator where- type ExternalInfo TypeDefinitionGenerator = Options- executePlugin TypeDefinitionGenerator externalInfo procedure = result- $ transform TypeDefinitionGenerator [{-state-}] externalInfo procedure
− lib/Feldspar/Compiler/Backend/C/Plugin/VariableRoleAssigner.hs
@@ -1,76 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner where--import Feldspar.Transformation--data VariableRoleAssigner = VariableRoleAssigner--data Parameters = Parameters- { inParametersVRA :: [String]- , outParametersVRA :: [String]- }--instance Transformation VariableRoleAssigner where- type From VariableRoleAssigner = ()- type To VariableRoleAssigner = ()- type Down VariableRoleAssigner = Parameters- type Up VariableRoleAssigner = ()- type State VariableRoleAssigner = ()--instance Transformable VariableRoleAssigner Variable where- transform _ _ d v = Result v' () () where- v' = v { varRole = if (varName v `elem` outParametersVRA d) ||- (isComposite v && (varName v `elem` inParametersVRA d))- then Pointer else Value- , varLabel = ()- }--instance Transformable VariableRoleAssigner Entity where- transform t s _ p@(ProcDef _ i o _ _ _) = defaultTransform t s d' p where- d' = Parameters- { inParametersVRA = map varName i- , outParametersVRA = map varName o- }- transform t s d p = defaultTransform t s d p--instance Plugin VariableRoleAssigner where- type ExternalInfo VariableRoleAssigner = ()- executePlugin self@VariableRoleAssigner _ procedure = - result $ transform self ({-state-}) (Parameters [] []) procedure--isComposite :: Variable () -> Bool-isComposite v = case varType v of- ArrayType{} -> True- StructType{} -> True- _ -> False-
+ lib/Feldspar/Compiler/CallConv.hs view
@@ -0,0 +1,65 @@+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}++-- | Type rewriting for Feldspar programs+module Feldspar.Compiler.CallConv+ ( rewriteType+ , buildHaskellType+ , buildCType+ )+ where+++import Language.Haskell.TH++import System.Plugins.MultiStage++import Foreign.Ptr (Ptr)++import Feldspar (Syntactic(..))++-- | Normalize the type (expand type synonyms and type families)+rewriteType :: Type -> Q Type+rewriteType t = applyTF ''Internal t >>= expandTF++haskellCC :: CallConv+haskellCC = CallConv { arg = return+ , res = appT (conT ''IO) . return+ }++feldsparCC :: CallConv+feldsparCC = CallConv { arg = ref . rep . return+ , res = toIO . appT (conT ''Ptr) . rep . return+ }+ where+ ref = appT (conT ''Ref)+ rep = appT (conT ''Rep)+ toIO t = appT (appT arrowT t) (appT (conT ''IO) (tupleT 0))++-- | Construct the corresponding Haskell type of a foreign Feldspar+-- function+--+-- > prog1 :: Data Index -> Vector1 Index+-- >+-- > sigD (mkName "h_prog1") $ loadFunType 'prog1 >>= rewriteType >>= buildHaskellType+--+-- becomes+--+-- > h_prog1 :: Index -> IO [Index]+--+buildHaskellType :: Type -> Q Type+buildHaskellType = buildType haskellCC++-- | Construct the corresponding C type of a compiled Feldspar function+--+-- > sigD (mkName "c_prog1_fun") $ loadFunType 'prog1 >>= rewriteType+-- >>= buildCType+--+-- becomes+--+-- > c_prog1_fun :: Word32 -> Ptr (SA Word32) -> IO ()+--+buildCType :: Type -> Q Type+buildCType = buildType feldsparCC+
lib/Feldspar/Compiler/Compiler.hs view
@@ -1,11 +1,11 @@ -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved.--- +-- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, +--+-- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the@@ -13,10 +13,10 @@ -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission.--- +-- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR@@ -26,138 +26,93 @@ -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ExistentialQuantification #-} module Feldspar.Compiler.Compiler where -import System.FilePath-import Data.Typeable as DT-import Control.Arrow+import Data.List (partition)+import Data.Maybe (fromMaybe) import Control.Applicative import Feldspar.Transformation-import qualified Feldspar.NameExtractor as NameExtractor+import Feldspar.Core.Constructs (SyntacticFeld)+import Feldspar.Core.Interpretation (defaultFeldOpts) import Feldspar.Compiler.Backend.C.Library import Feldspar.Compiler.Backend.C.Options import Feldspar.Compiler.Backend.C.Platforms import Feldspar.Compiler.Backend.C.Plugin.Rule-import Feldspar.Compiler.Backend.C.Plugin.TypeDefinitionGenerator-import Feldspar.Compiler.Backend.C.Plugin.VariableRoleAssigner-import Feldspar.Compiler.Backend.C.Plugin.BlockProgramHandler-import Feldspar.Compiler.Backend.C.Plugin.TypeCorrector-import Feldspar.Compiler.Backend.C.Plugin.PrettyPrint+import Feldspar.Compiler.Backend.C.CodeGeneration import Feldspar.Compiler.Imperative.FromCore-import Feldspar.Compiler.Imperative.Plugin.ConstantFolding-import Feldspar.Compiler.Imperative.Plugin.Free import Feldspar.Compiler.Imperative.Plugin.IVars-import Feldspar.Compiler.Imperative.Plugin.Naming-import Feldspar.Compiler.Imperative.Plugin.Unroll -data SomeCompilable = forall a internal . Compilable a internal => SomeCompilable a- deriving (DT.Typeable)--type Position = (Int, Int)+data SplitModuleDescriptor = SplitModuleDescriptor+ { smdSource :: Module ()+ , smdHeader :: Module ()+ } -data SplitModuleDescriptor = SplitModuleDescriptor {- smdSource :: Module (),- smdHeader :: Module ()-}+data SplitCompToCCoreResult = SplitCompToCCoreResult+ { sctccrSource :: CompToCCoreResult ()+ , sctccrHeader :: CompToCCoreResult ()+ } -data CompToCCoreResult = CompToCCoreResult {+data CompToCCoreResult t = CompToCCoreResult { sourceCode :: String,- endPosition :: Position,- debugModule :: Module DebugToCSemanticInfo-}--data SplitCompToCCoreResult = SplitCompToCCoreResult {- sctccrSource :: CompToCCoreResult,- sctccrHeader :: CompToCCoreResult+ debugModule :: Module t } -data IncludesNeeded = IncludesNeeded | NoIncludesNeeded { incneedLineNum :: Int }- moduleSplitter :: Module () -> SplitModuleDescriptor moduleSplitter m = SplitModuleDescriptor {- smdHeader = Module (filter belongsToHeader (entities m) ++ createProcDecls (entities m)) (moduleLabel m),- smdSource = Module (filter (not . belongsToHeader) $ entities m) (moduleLabel m)+ smdHeader = Module (hdr ++ createProcDecls (entities m)),+ smdSource = Module body } where+ (hdr, body) = partition belongsToHeader (entities m) belongsToHeader :: Entity () -> Bool- belongsToHeader StructDef{} = True- belongsToHeader ProcDecl{} = True- belongsToHeader _ = False+ belongsToHeader StructDef{} = True+ belongsToHeader Proc{..} | Nothing <- procBody = True+ belongsToHeader _ = False+ -- TODO These only belongs in the header iff the types are used in a+ -- function interface createProcDecls :: [Entity ()] -> [Entity ()]- createProcDecls = foldr ((++) . convertProcDefToProcDecl) []- convertProcDefToProcDecl :: Entity () -> [Entity ()]- convertProcDefToProcDecl e = case e of- ProcDef n inparams outparams _ label1 label2 -> [ProcDecl n inparams outparams label1 label2]- _ -> []--separateAndCompileToCCore :: (Compilable t internal)- => (Module ()- -> [Module ()])- -> CompilationMode -> t -> IncludesNeeded- -> NameExtractor.OriginalFunctionSignature -> Options- -> [(CompToCCoreResult, Module ())]-separateAndCompileToCCore- moduleSeparator- compMode prg needed- functionSignature coreOptions =- pack <$> separatedModules- where- pack = compToCWithInfo &&& id-- separatedModules =- moduleSeparator $- executePluginChain' compMode prg functionSignature coreOptions-- compToCWithInfo = moduleToCCore needed coreOptions+ createProcDecls = concatMap defToDecl+ defToDecl :: Entity () -> [Entity ()]+ defToDecl (Proc n inp outp _) = [Proc n inp outp Nothing]+ defToDecl _ = [] -moduleToCCore- :: IncludesNeeded -> Options -> Module ()- -> CompToCCoreResult-moduleToCCore needed opts mdl =- CompToCCoreResult {- sourceCode = incls ++ moduleSrc- , endPosition = endPos- , debugModule = dbgModule- }+moduleToCCore :: Options -> Module () -> CompToCCoreResult ()+moduleToCCore opts mdl = CompToCCoreResult { sourceCode = incls ++ res+ , debugModule = mdl+ } where- (incls, lineNum) = genInclude needed+ res = compToCWithInfos opts mdl+ incls = genIncludeLines opts Nothing - (dbgModule, (moduleSrc, endPos)) =- compToCWithInfos ((opts,Declaration_pl), lineNum) mdl - genInclude IncludesNeeded = genIncludeLines opts Nothing- genInclude (NoIncludesNeeded ln) = ("", ln)- -- | Compiler core -- This functionality should not be duplicated. Instead, everything should call this and only do a trivial interface adaptation. compileToCCore- :: (Compilable t internal) => CompilationMode -> t -> Maybe String -> IncludesNeeded- -> NameExtractor.OriginalFunctionSignature -> Options- -> SplitCompToCCoreResult-compileToCCore compMode prg _ includesNeeded- funSig coreOptions =- createSplit $ fst <$> separateAndCompileToCCore headerAndSource- compMode prg includesNeeded funSig coreOptions- where- headerAndSource modules = [header, source]- where (SplitModuleDescriptor header source) = moduleSplitter modules+ :: SyntacticFeld c => String -> Options -> c -> SplitCompToCCoreResult+compileToCCore funSig coreOptions prg =+ createSplit $ moduleToCCore coreOptions <$> separatedModules+ where+ separatedModules = moduleSeparator+ $ executePluginChain funSig coreOptions prg - createSplit [header, source] = SplitCompToCCoreResult header source+ moduleSeparator modules = [header, source]+ where (SplitModuleDescriptor header source) = moduleSplitter modules -genIncludeLinesCore :: [String] -> (String, Int)-genIncludeLinesCore [] = ("", 1)-genIncludeLinesCore (x:xs) = ("#include " ++ x ++ "\n" ++ str, linenum + 1) where- (str, linenum) = genIncludeLinesCore xs+ createSplit [header, source] = SplitCompToCCoreResult header source -genIncludeLines :: Options -> Maybe String -> (String, Int)-genIncludeLines coreOptions mainHeader = (str ++ "\n\n", linenum + 2) where- (str, linenum) = genIncludeLinesCore $ includes (platform coreOptions) ++ mainHeaderCore- mainHeaderCore = case mainHeader of- Nothing -> []- Just filename -> ["\"" ++ takeFileName filename ++ ".h\""]+genIncludeLines :: Options -> Maybe String -> String+genIncludeLines opts mainHeader = concatMap include incs ++ "\n\n"+ where+ include [] = ""+ include fname@('<':_) = "#include " ++ fname ++ "\n"+ include fname = "#include \"" ++ fname ++ "\"\n"+ incs = includes (platform opts) ++ [fromMaybe "" mainHeader] -- | Predefined options @@ -168,12 +123,18 @@ , unroll = NoUnroll , debug = NoDebug , memoryInfoVisible = True+ , printHeader = False , rules = []+ , frontendOpts = defaultFeldOpts+ , nestSize = 2 } c99PlatformOptions :: Options c99PlatformOptions = defaultOptions +c99OpenMpPlatformOptions :: Options+c99OpenMpPlatformOptions = defaultOptions { platform = c99OpenMp }+ tic64xPlatformOptions :: Options tic64xPlatformOptions = defaultOptions { platform = tic64x } @@ -191,58 +152,19 @@ pluginChain :: ExternalInfoCollection -> Module () -> Module () pluginChain externalInfo = executePlugin RulePlugin (ruleExternalInfo externalInfo)- . executePlugin TypeDefinitionGenerator (typeDefinitionGeneratorExternalInfo externalInfo)- . executePlugin ConstantFolding ()- . executePlugin UnrollPlugin (unrollExternalInfo externalInfo)- . executePlugin Precompilation (precompilationExternalInfo externalInfo) . executePlugin RulePlugin (primitivesExternalInfo externalInfo)- . executePlugin Free () . executePlugin IVarPlugin ()- . executePlugin VariableRoleAssigner (variableRoleAssignerExternalInfo externalInfo)- . executePlugin TypeCorrector (typeCorrectorExternalInfo externalInfo)- . executePlugin BlockProgramHandler () -data ExternalInfoCollection = ExternalInfoCollection {- precompilationExternalInfo :: ExternalInfo Precompilation- , unrollExternalInfo :: ExternalInfo UnrollPlugin- , primitivesExternalInfo :: ExternalInfo RulePlugin- , ruleExternalInfo :: ExternalInfo RulePlugin- , typeDefinitionGeneratorExternalInfo :: ExternalInfo TypeDefinitionGenerator- , variableRoleAssignerExternalInfo :: ExternalInfo VariableRoleAssigner- , typeCorrectorExternalInfo :: ExternalInfo TypeCorrector-}--executePluginChain' :: (Compilable c internal)- => CompilationMode -> c -> NameExtractor.OriginalFunctionSignature- -> Options -> Module ()-executePluginChain' compMode prg originalFunctionSignatureParam opt =- pluginChain ExternalInfoCollection {- precompilationExternalInfo = PrecompilationExternalInfo {- originalFunctionSignature = fixedOriginalFunctionSignature- , inputParametersDescriptor = buildInParamDescriptor prg- , numberOfFunctionArguments = numArgs prg- , compilationMode = compMode- }- , unrollExternalInfo = unroll opt- , primitivesExternalInfo = opt{ rules = platformRules $ platform opt }- , ruleExternalInfo = opt- , typeDefinitionGeneratorExternalInfo = opt- , variableRoleAssignerExternalInfo = ()- , typeCorrectorExternalInfo = False- } $ fromCore "PLACEHOLDER" prg- where- ofn = NameExtractor.originalFunctionName- fixedOriginalFunctionSignature = originalFunctionSignatureParam {- NameExtractor.originalFunctionName =- fixFunctionName $ ofn originalFunctionSignatureParam+data ExternalInfoCollection = ExternalInfoCollection+ { primitivesExternalInfo :: ExternalInfo RulePlugin+ , ruleExternalInfo :: ExternalInfo RulePlugin } -executePluginChain :: (Compilable c internal)- => CompilationMode- -> c- -> NameExtractor.OriginalFunctionSignature- -> Options- -> SplitModuleDescriptor-executePluginChain cm f sig opts =- moduleSplitter $ executePluginChain' cm f sig opts+executePluginChain :: SyntacticFeld c+ => String -> Options -> c -> Module ()+executePluginChain originalFunctionName opt prg =+ pluginChain ExternalInfoCollection+ { primitivesExternalInfo = opt{ rules = platformRules $ platform opt }+ , ruleExternalInfo = opt+ } $ fromCore opt (encodeFunctionName originalFunctionName) prg
lib/Feldspar/Compiler/Frontend/Interactive/Interface.hs view
@@ -1,3 +1,7 @@+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE FlexibleContexts #-}+ -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved.@@ -28,48 +32,31 @@ module Feldspar.Compiler.Frontend.Interactive.Interface where +import Feldspar.Core.Constructs (SyntacticFeld) import Feldspar.Compiler.Compiler import Feldspar.Compiler.Imperative.FromCore import Feldspar.Compiler.Backend.C.Options-import qualified Feldspar.NameExtractor as NameExtractor import Feldspar.Compiler.Backend.C.Library-import Feldspar.Compiler.Imperative.Representation-import Feldspar.Compiler.Backend.C.Plugin.PrettyPrint-import Feldspar.Compiler.Backend.C.Plugin.Locator+import Feldspar.Compiler.Imperative.Representation (Module) import Data.Char+import Control.Monad (when)+import System.FilePath (takeFileName) -- ================================================================================================ -- == Interactive compilation -- ================================================================================================ -data PrgType = ForType | AssignType | IfType--forPrg = ForType-ifPrg = IfType-assignPrg = AssignType--getProgram :: (Int, Int) -> PrgType -> Module DebugToCSemanticInfo -> IO ()-getProgram (line, col) prgtype prg = res where- res = if find then putStrLn $ myShow code- else putStrLn "Not found appropriate code part!"- (find, code) = case prgtype of- ForType -> getPrgParLoop (line, col) prg- AssignType -> getPrgAssign (line, col) prg- IfType -> getPrgBranch (line, col) prg---compile :: (Compilable t internal) => t -> FilePath -> String -> Options -> IO ()+compile :: (SyntacticFeld t) => t -> FilePath -> String -> Options -> IO () compile prg fileName functionName opts = do- writeFile cfile $ unlines [ "#include \"" ++ hfile ++ "\""+ writeFile cfile $ unlines [ "#include \"" ++ takeFileName hfile ++ "\"" , sourceCode $ sctccrSource compilationResult ] writeFile hfile $ withIncludeGuard $ sourceCode $ sctccrHeader compilationResult where hfile = makeHFileName fileName cfile = makeCFileName fileName- compilationResult = compileToCCore Interactive prg (Just fileName) IncludesNeeded- (NameExtractor.OriginalFunctionSignature functionName []) opts+ compilationResult = compileToCCore functionName opts prg withIncludeGuard code = unlines [ "#ifndef " ++ guardName , "#define " ++ guardName@@ -84,19 +71,25 @@ toBeChanged = "./\\" -icompile :: (Compilable t internal) => t -> IO ()-icompile prg = icompile' prg "test" defaultOptions+icompile :: (SyntacticFeld t) => t -> IO ()+icompile = icompileWith defaultOptions -icompile' :: (Compilable t internal) => t -> String -> Options -> IO ()-icompile' prg functionName opts = do- putStrLn "=============== Header ================"- putStrLn $ sourceCode $ sctccrHeader compilationResult- putStrLn "=============== Source ================"- putStrLn $ sourceCode $ sctccrSource compilationResult- where- compilationResult = compileToCCore Interactive prg Nothing IncludesNeeded- (NameExtractor.OriginalFunctionSignature functionName []) opts+icompileWith :: (SyntacticFeld t) => Options -> t -> IO ()+icompileWith opts = icompile' opts "test" -icompileWithInfos :: (Compilable t internal) => t -> String -> Options -> SplitCompToCCoreResult-icompileWithInfos prg functionName = compileToCCore Interactive prg Nothing IncludesNeeded- (NameExtractor.OriginalFunctionSignature functionName [])+icompile' :: (SyntacticFeld t) => Options -> String -> t -> IO ()+icompile' opts functionName prg = do+ let res = compileToCCore functionName opts prg+ when (printHeader opts) $ do+ putStrLn "=============== Header ================"+ putStrLn $ sourceCode $ sctccrHeader res+ putStrLn "=============== Source ================"+ putStrLn $ sourceCode $ sctccrSource res++-- | Get the generated core for a program.+getCore :: (SyntacticFeld t) => t -> Module ()+getCore = getCore' defaultOptions++-- | Print the generated core for a program.+printCore :: (SyntacticFeld t) => t -> IO ()+printCore prog = print $ getCore' defaultOptions prog
lib/Feldspar/Compiler/Imperative/FromCore.hs view
@@ -1,5 +1,3 @@-{-# LANGUAGE ConstraintKinds #-}- -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved.@@ -30,15 +28,18 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-}+{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-} module Feldspar.Compiler.Imperative.FromCore where +import Data.List (nub)+import Data.Typeable+ import Control.Monad.RWS import Language.Syntactic@@ -48,14 +49,26 @@ import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs+import Feldspar.Core.Constructs.Literal import Feldspar.Core.Constructs.Binding import Feldspar.Core.Frontend -import Feldspar.Compiler.Imperative.Representation (Module)-import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Range (upperBound)++import qualified Feldspar.Compiler.Imperative.Representation as Rep (Variable(..), Type(..))+import Feldspar.Compiler.Imperative.Representation+ ( ActualParameter(..)+ , Block(..)+ , Declaration(..)+ , Entity(..)+ , Expression(..)+ , Module(..)+ , Program(..)+ )+import Feldspar.Compiler.Imperative.Frontend import Feldspar.Compiler.Imperative.FromCore.Interpretation import Feldspar.Compiler.Imperative.FromCore.Array ()-import Feldspar.Compiler.Imperative.FromCore.Binding ()+import Feldspar.Compiler.Imperative.FromCore.Binding (compileBind) import Feldspar.Compiler.Imperative.FromCore.Condition () import Feldspar.Compiler.Imperative.FromCore.ConditionM () import Feldspar.Compiler.Imperative.FromCore.Error ()@@ -70,63 +83,86 @@ import Feldspar.Compiler.Imperative.FromCore.Primitive () import Feldspar.Compiler.Imperative.FromCore.Save () import Feldspar.Compiler.Imperative.FromCore.SizeProp ()+import Feldspar.Compiler.Imperative.FromCore.Switch () import Feldspar.Compiler.Imperative.FromCore.SourceInfo () import Feldspar.Compiler.Imperative.FromCore.Tuple () -instance Compile FeldDomain FeldDomain+import Feldspar.Compiler.Backend.C.Options (Options(..))++instance Compile FeldDom FeldDom where compileProgSym (C' a) = compileProgSym a compileExprSym (C' a) = compileExprSym a -instance Compile Empty FeldDomain+instance Compile Empty dom where compileProgSym _ = error "Can't compile Empty" compileExprSym _ = error "Can't compile Empty" -compileProgTop :: (Compile dom dom, Project (CLambda Type) dom) =>- String -> [Var] -> ASTF (Decor Info dom) a -> Mod-compileProgTop funname args (lam :$ body)+compileProgTop :: ( Compile dom dom+ , Project (CLambda Type) dom+ , Project Let dom+ , Project (Literal :|| Type) dom+ , ConstrainedBy dom Typeable+ ) =>+ Options -> String -> [(VarId, ASTB (Decor Info dom) Type)] ->+ ASTF (Decor Info dom) a -> CodeWriter (Rep.Variable ())+compileProgTop opt funname bs (lam :$ body) | Just (SubConstr2 (Lambda v)) <- prjLambda lam- = let ta = argType $ infoType $ getInfo lam- sa = defaultSize ta- var = mkVariable (compileTypeRep ta sa) v- in compileProgTop funname (var:args) body-compileProgTop funname args a = Mod defs+ = do+ let ta = argType $ infoType $ getInfo lam+ sa = fst $ infoSize $ getInfo lam+ typ = compileTypeRep ta sa+ arg | Rep.StructType{} <- typ = mkPointer typ v+ | otherwise = mkVariable typ v+ tell $ mempty {params=[arg]}+ withAlias v (varToExpr arg) $+ compileProgTop opt funname bs body+compileProgTop opt funname bs (lt :$ e :$ (lam :$ body))+ | Just (SubConstr2 (Lambda v)) <- prjLambda lam+ , Just Let <- prj lt+ , Just (C' Literal{}) <- prjF e -- Input on form let x = n in e+ , [ProcedureCall "copy" [ValueParameter (VarExpr vr), ValueParameter (ConstExpr c)]] <- bd+ , freshName Prelude.== vName vr -- Ensure that compiled result is on form x = n+ = do tellDef [ValueDef var c]+ withAlias v (varToExpr var) $+ compileProgTop opt funname bs body where- ins = reverse args- info = getInfo a- outType = compileTypeRep (infoType info) (infoSize info)- outParam = Pointer outType "out"- outLoc = Ptr outType "out"- results = snd $ evalRWS (compileProg outLoc a) initReader initState- Bl ds p = block results- defs = def results ++ [ProcDf funname ins [outParam] (Block ds p)]--class SyntacticFeld a => Compilable a internal | a -> internal-instance SyntacticFeld a => Compilable a ()- -- TODO This class should be replaced by (Syntactic a FeldDomainAll) (or a- -- similar alias) everywhere. The second parameter is not needed.--fromCore :: SyntacticFeld a => String -> a -> Module ()-fromCore funname- = fromInterface- . compileProgTop funname []- . reifyFeld N32+ info = getInfo e+ outType = case compileTypeRep (infoType info) (infoSize info) of+ Rep.ArrayType rs t -> Rep.NativeArray (Just $ upperBound rs) t+ t -> t+ var@(Rep.Variable _ freshName) = case prjLambda lam of+ Just (SubConstr2 (Lambda v)) -> mkVariable outType v+ bd = sequenceProgs $ blockBody $ block $ snd $+ evalRWS (compileProg (Just $ varToExpr var) e) (initReader opt) initState+compileProgTop opt funname bs e@(lt :$ _ :$ _)+ | Just Let <- prj lt+ , (bs', body) <- collectLetBinders e+ = compileProgTop opt funname (reverse bs' ++ bs) body+compileProgTop _ _ bs a = do+ let+ info = getInfo a+ outType = Rep.Pointer $ compileTypeRep (infoType info) (infoSize info)+ outParam = Rep.Variable outType "out"+ outLoc = varToExpr outParam+ mapM_ compileBind (reverse bs)+ compileProg (Just outLoc) a+ return outParam --- | Create a list where each element represents the number of variables needed--- to as arguments-buildInParamDescriptor :: SyntacticFeld a => a -> [Int]-buildInParamDescriptor = go . reifyFeld N32+fromCore :: SyntacticFeld a => Options -> String -> a -> Module ()+fromCore opt funname prog = Module defs where- go :: (Project (CLambda Type) dom) => ASTF (Decor info dom) a -> [Int]- go (lam :$ body)- | Just (SubConstr2 (Lambda _)) <- prjLambda lam- = 1 : go body- -- TODO the 1 above is valid as long as we represent tuples as structs- -- When we convert a struct to a set of variables the 1 has to replaced- -- with an implementation that calculates the apropriate value.- go _ = []--numArgs :: SyntacticFeld a => a -> Int-numArgs = length . buildInParamDescriptor+ (outParam,results) = evalRWS (compileProgTop opt funname [] ast) (initReader opt) initState+ ast = reifyFeld (frontendOpts opt) N32 prog+ decls = decl results+ ins = params results+ post = epilogue results+ Block ds p = block results+ paramTypes = getTypes opt $ Declaration outParam Nothing:map (`Declaration` Nothing) ins+ defs = nub (def results ++ paramTypes)+ ++ [Proc funname ins [outParam] $ Just (Block (ds ++ decls) (Sequence (p:post)))] +-- | Get the generated core for a program.+getCore' :: SyntacticFeld a => Options -> a -> Module ()+getCore' opts = fromCore opts "test"
lib/Feldspar/Compiler/Imperative/FromCore/Array.hs view
@@ -28,6 +28,7 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-}+{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-}@@ -35,7 +36,10 @@ module Feldspar.Compiler.Imperative.FromCore.Array where +import Data.Typeable +import Control.Applicative+ import Language.Syntactic import Language.Syntactic.Constructs.Binding import Language.Syntactic.Constructs.Binding.HigherOrder@@ -43,11 +47,17 @@ import Feldspar.Core.Types as Core import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Array+import Feldspar.Core.Constructs.Tuple import Feldspar.Core.Constructs.Binding import Feldspar.Core.Constructs.Literal -import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Compiler.Imperative.Frontend+import qualified Feldspar.Compiler.Imperative.Representation as Rep (Type(..))+import Feldspar.Compiler.Imperative.Representation (Expression(..), Program(..),+ Block(..), Size(..),+ Signedness(..), typeof) import Feldspar.Compiler.Imperative.FromCore.Interpretation+import Feldspar.Compiler.Imperative.FromCore.Binding (compileBind) @@ -55,6 +65,11 @@ , Project (CLambda Type) dom , Project (Literal :|| Type) dom , Project (Variable :|| Type) dom+ , Project Let dom+ , Project (Array :|| Type) dom+ , Project (Tuple :|| Type) dom+ , ConstrainedBy dom Typeable+ , AlphaEq dom dom (Decor Info dom) [(VarId, VarId)] ) => Compile (Array :|| Type) dom where@@ -62,47 +77,103 @@ | Just (SubConstr2 (Lambda v)) <- prjLambda lam = do let ta = argType $ infoType $ getInfo lam- let sa = defaultSize ta- let ix@(Var _ name) = mkVar (compileTypeRep ta sa) v- len' <- mkLength len- (_, Bl ds body) <- confiscateBlock $ compileProg (loc :!: ix) ixf+ let sa = fst $ infoSize $ getInfo lam+ let ix = mkVar (compileTypeRep ta sa) v+ len' <- mkLength len (infoType $ getInfo len) sa+ (_, b) <- confiscateBlock $ compileProg (ArrayElem <$> loc <*> pure ix) ixf tellProg [initArray loc len']- tellProg [For name len' 1 (Block ds body)]+ tellProg [for True (lName ix) len' (litI32 1) b] - compileProgSym (C' Sequential) _ loc (len :* st :* (lam1 :$ (lam2 :$ step)) :* Nil)+ compileProgSym (C' Sequential) _ loc (len :* init' :* (lam1 :$ lt1) :* Nil) | Just (SubConstr2 (Lambda v)) <- prjLambda lam1+ , (bs1, lam2 :$ l) <- collectLetBinders lt1 , Just (SubConstr2 (Lambda s)) <- prjLambda lam2+ , (bs, tup :$ a :$ b) <- collectLetBinders l+ , Just (C' Tup2) <- prjF tup+ , not $ null bs+ , (e, ASTB step) <- last bs+ , Just (C' (Variable t1)) <- prjF a+ , Just (C' (Variable t2)) <- prjF b+ , t1 == e+ , t2 == e = do+ blocks <- mapM (confiscateBlock . compileBind) (bs1 ++ init bs)+ let tix = argType $ infoType $ getInfo lam1+ six = fst $ infoSize $ getInfo lam1+ tst = infoType $ getInfo step+ sst = infoSize $ getInfo step+ (dss, lets) = unzip $ map (\(_, Block ds (Sequence body)) -> (ds, body)) blocks+ let ix = mkVar (compileTypeRep tix six) v+ len' <- mkLength len (infoType $ getInfo len) six+ st1 <- freshVar "st" tst sst+ let st = mkRef (compileTypeRep tst sst) s+ declareAlias st+ (_, Block ds (Sequence body)) <- confiscateBlock $ withAlias s st $ compileProg (ArrayElem <$> loc <*> pure ix) step+ withAlias s st $ compileProg (Just st1) init'+ tellProg [ Assign st st1+ , initArray loc len']+ tellProg [toProg $ Block (concat dss ++ ds) $+ for False (lName ix) len' (litI32 1) $+ toBlock $ Sequence (concat lets ++ body ++ maybe [] (\arr -> [Assign st (ArrayElem arr ix)]) loc)]++ compileProgSym (C' Sequential) _ loc (len :* st :* (lam1 :$ lt1) :* Nil)+ | Just (SubConstr2 (Lambda v)) <- prjLambda lam1+ , (bs1, lam2 :$ step) <- collectLetBinders lt1+ , Just (SubConstr2 (Lambda s)) <- prjLambda lam2+ = do+ blocks <- mapM (confiscateBlock . compileBind) bs1 let t = argType $ infoType $ getInfo lam1- let sz = defaultSize t- let ta' = argType $ infoType $ getInfo lam2- let sa' = defaultSize ta'+ let sz = fst $ infoSize $ getInfo lam1 let tr' = resType $ infoType $ getInfo lam2- let sr' = defaultSize tr'- let ix@(Var _ name) = mkVar (compileTypeRep t sz) v- let stv = mkVar (compileTypeRep ta' sa') s- len' <- mkLength len- tmp <- freshVar "seq" tr' sr'- initSt <- compileExpr st- (_, Bl ds (Seq body)) <- confiscateBlock $ compileProg tmp step+ let sr' = snd $ infoSize $ getInfo lam2+ let ix = mkVar (compileTypeRep t sz) v+ (dss, lets) = unzip $ map (\(_, Block ds (Sequence body)) -> (ds, body)) blocks+ len' <- mkLength len (infoType $ getInfo len) sz+ tmp <- freshVar "seq" tr' sr'+ (_, Block ds (Sequence body)) <- confiscateBlock $ withAlias s (StructField tmp "member2") $ compileProg (Just tmp) step tellProg [initArray loc len']- tellProg [Block (ds ++ [toIni stv initSt]) $- For name len' 1 $- Seq (body ++- [assignProg (loc :!: ix) (tmp :.: "member1")- ,assignProg stv (tmp :.: "member2")+ compileProg (Just $ StructField tmp "member2") st+ tellProg [toProg $ Block (concat dss ++ ds) $+ for False (lName ix) len' (litI32 1) $+ toBlock $ Sequence (concat lets ++ body +++ [copyProg (ArrayElem <$> loc <*> pure ix) [StructField tmp "member1"] ])]- where toIni (Var ty str) = Init ty str + -- TODO: This optimization contains a bug+ -- The result array is initialized to length l, when it should be 2*l+ -- It is easy enough to fix by multiplying the length with 2 like this:+ --+ -- > tellprog [initArray loc $ binop (Rep.NumType Unsigned S32) "*" len (litI32 2)]+ --+ -- However, in many cases the resulting length expression could be+ -- optimized further if the calculation had been performed in the core+ -- language instead of the imperative langauge.+ --+ --+ -- -- loc = parallel l f ++ parallel l g ==> for l (\i -> loc[i] = f i; loc[i+l] = g i)+ -- compileProgSym (C' Append) _ loc ((arr1 :$ l1 :$ (lam1 :$ body1)) :* (arr2 :$ l2 :$ (lam2 :$ body2)) :* Nil)+ -- | Just (C' Parallel) <- prjF arr1+ -- , Just (C' Parallel) <- prjF arr2+ -- , Just (SubConstr2 (Lambda v1)) <- prjLambda lam1+ -- , Just (SubConstr2 (Lambda v2)) <- prjLambda lam2+ -- , alphaEq l1 l2+ -- = do+ -- let t = argType $ infoType $ getInfo lam1+ -- sz = fst $ infoSize $ getInfo lam1+ -- ix1 = mkVar (compileTypeRep t sz) v1+ -- ix2 = mkVar (compileTypeRep t sz) v2+ -- len <- mkLength l1 (infoType $ getInfo l1) sz+ -- (_, Block ds1 (Sequence b1)) <- confiscateBlock $ withAlias v1 ix1 $ compileProg (ArrayElem <$> loc <*> pure ix1) body1+ -- (_, Block ds2 (Sequence b2)) <- confiscateBlock $ withAlias v2 ix1 $ compileProg (ArrayElem <$> loc <*> pure ix2) body2+ -- tellProg [initArray loc len]+ -- assign (Just ix2) len+ -- tellProg [for True (lName ix1) len (litI32 1) (Block (ds1++ds2) (Sequence $ b1 ++ b2 ++ [copyProg (Just ix2) [binop (Rep.NumType Unsigned S32) "+" ix2 (litI32 1)]]))]+ compileProgSym (C' Append) _ loc (a :* b :* Nil) = do a' <- compileExpr a b' <- compileExpr b- let aLen = arrayLength a'- let bLen = arrayLength b'- tellProg [initArray loc $ Binop U32 "+" [aLen, bLen]]- tellProg [copyProg loc a']- tellProg [copyProgPos loc aLen b']+ tellProg [copyProg loc [a', b']] -- TODO: Optimize by writing to directly to 'loc' instead of 'a'' and 'b''! -- But take care of array initialization: -- compiling 'a' and 'b' might do initialization itself...@@ -110,24 +181,32 @@ compileProgSym (C' SetIx) _ loc (arr :* i :* a :* Nil) = do compileProg loc arr i' <- compileExpr i- compileProg (loc :!: i') a+ compileProg (ArrayElem <$> loc <*> pure i') a + compileProgSym (C' GetIx) _ (Just loc) (arr :* i :* Nil) = do+ a' <- compileExpr arr+ i' <- compileExpr i+ let el = ArrayElem a' i'+ tellProg $ if isArray $ typeof el+ then [Assign loc el]+ else [copyProg (Just loc) [el]]+ compileProgSym (C' SetLength) _ loc (len :* arr :* Nil) = do len' <- compileExpr len- tellProg [setLength loc len'] compileProg loc arr+ tellProg [setLength loc len'] -- TODO Optimize by using copyProgLen (compare to 0.4) compileProgSym a info loc args = compileExprLoc a info loc args - compileExprSym (C' GetLength) info (a :* Nil) = do+ compileExprSym (C' GetLength) _ (a :* Nil) = do aExpr <- compileExpr a- return $ Fun (compileTypeRep (infoType info) (infoSize info)) "getLength" [aExpr]+ return $ arrayLength aExpr compileExprSym (C' GetIx) _ (arr :* i :* Nil) = do a' <- compileExpr arr i' <- compileExpr i- return $ a' :!: i'+ return $ ArrayElem a' i' compileExprSym a info args = compileProgFresh a info args
lib/Feldspar/Compiler/Imperative/FromCore/Binding.hs view
@@ -47,6 +47,7 @@ import Feldspar.Compiler.Imperative.FromCore.Interpretation +import Feldspar.Compiler.Imperative.Representation (Expression(..)) instance Compile (Core.Variable :|| Type) dom@@ -61,23 +62,34 @@ where compileProgSym = error "Can only compile top-level Lambda" -instance (Compile dom dom, Project (CLambda Type) dom) => Compile (Let :|| Type) dom+instance (Compile dom dom, Project (CLambda Type) dom) => Compile Let dom where- compileProgSym (C' Let) _ loc (a :* (lam :$ body) :* Nil)+ compileProgSym Let _ loc (a :* (lam :$ body) :* Nil) | Just (SubConstr2 (Lambda v)) <- prjLambda lam- = compileLet a (getInfo lam) v >> compileProg loc body+ = do e <- compileLet a (getInfo lam) v+ withAlias v e $ compileProg loc body - compileExprSym (C' Let) _ (a :* (lam :$ body) :* Nil)+ compileExprSym Let _ (a :* (lam :$ body) :* Nil) | Just (SubConstr2 (Lambda v)) <- prjLambda lam- = compileLet a (getInfo lam) v >> compileExpr body+ = do e <- compileLet a (getInfo lam) v+ withAlias v e $ compileExpr body compileLet :: Compile dom dom- => ASTF (Decor Info dom) a -> Info (a -> b) -> VarId -> CodeWriter ()+ => ASTF (Decor Info dom) a -> Info (a -> b) -> VarId -> CodeWriter (Expression ()) compileLet a info v = do let ta = argType $ infoType info- sa = defaultSize ta+ sa = infoSize $ getInfo a var = mkVar (compileTypeRep ta sa) v declare var- compileProg var a+ compileProg (Just var) a+ return var +compileBind :: Compile dom dom+ => (VarId, ASTB (Decor Info dom) Type) -> CodeWriter ()+compileBind (v, ASTB e)+ = do+ let info = getInfo e+ var = mkVar (compileTypeRep (infoType info) (infoSize info)) v+ declare var+ compileProg (Just var) e
lib/Feldspar/Compiler/Imperative/FromCore/Condition.hs view
@@ -40,16 +40,12 @@ import Feldspar.Core.Types as Core import Feldspar.Core.Constructs.Condition -import Feldspar.Compiler.Imperative.Frontend import Feldspar.Compiler.Imperative.FromCore.Interpretation instance Compile dom dom => Compile (Condition :|| Core.Type) dom where- compileProgSym (C' Condition) _ loc (cond :* tHEN :* eLSE :* Nil) = do- condExpr <- compileExpr cond- (_, Bl tds thenProg) <- confiscateBlock $ compileProg loc tHEN- (_, Bl eds elseProg) <- confiscateBlock $ compileProg loc eLSE- tellProg [If condExpr (Block tds thenProg) (Block eds elseProg)]+ compileProgSym (C' Condition) _ loc (cond :* tHEN :* eLSE :* Nil) =+ mkBranch loc cond tHEN $ Just eLSE
lib/Feldspar/Compiler/Imperative/FromCore/ConditionM.hs view
@@ -39,16 +39,12 @@ import Feldspar.Core.Constructs.ConditionM -import Feldspar.Compiler.Imperative.Frontend import Feldspar.Compiler.Imperative.FromCore.Interpretation instance Compile dom dom => Compile (ConditionM m) dom where- compileProgSym ConditionM _ loc (cond :* tHEN :* eLSE :* Nil) = do- condExpr <- compileExpr cond- (_, Bl tds thenProg) <- confiscateBlock $ compileProg loc tHEN- (_, Bl eds elseProg) <- confiscateBlock $ compileProg loc eLSE- tellProg [If condExpr (Block tds thenProg) (Block eds elseProg)]+ compileProgSym ConditionM _ loc (cond :* tHEN :* eLSE :* Nil) =+ mkBranch loc cond tHEN $ Just eLSE
lib/Feldspar/Compiler/Imperative/FromCore/Error.hs view
@@ -44,7 +44,9 @@ import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Error -import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Compiler.Imperative.Frontend+import Feldspar.Compiler.Imperative.Representation (Program(..),+ ActualParameter(..)) import Feldspar.Compiler.Imperative.FromCore.Interpretation @@ -65,6 +67,6 @@ => ASTF (Decor Info dom) a -> String -> CodeWriter () compileAssert cond msg = do condExpr <- compileExpr cond- tellProg [Call "assert" [In condExpr]]- when (length msg > 0) $ tellProg [Comment $ "{" ++ msg ++ "}"]+ tellProg [call "assert" [ValueParameter condExpr]]+ unless (null msg) $ tellProg [Comment False $ "{" ++ msg ++ "}"]
lib/Feldspar/Compiler/Imperative/FromCore/FFI.hs view
@@ -40,12 +40,12 @@ import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.FFI -import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Compiler.Imperative.Frontend import Feldspar.Compiler.Imperative.FromCore.Interpretation instance (Compile dom dom) => Compile (FFI :|| Type) dom where compileExprSym (C' (ForeignImport name _)) info args = do argExprs <- sequence $ listArgs compileExpr args- return $ Fun (compileTypeRep (infoType info) (infoSize info)) name argExprs+ return $ fun (compileTypeRep (infoType info) (infoSize info)) name argExprs
lib/Feldspar/Compiler/Imperative/FromCore/Future.hs view
@@ -1,11 +1,11 @@ -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved.--- +-- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, +--+-- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the@@ -13,10 +13,10 @@ -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission.--- +-- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR@@ -36,40 +36,46 @@ import Language.Syntactic -import Feldspar.Core.Types (Type)+import Control.Monad.RWS (ask)++import Feldspar.Core.Types (Type,defaultSize) import Feldspar.Core.Constructs.Future+import Feldspar.Core.Interpretation -import Feldspar.Compiler.Imperative.Frontend hiding (Type)-import qualified Feldspar.Compiler.Imperative.Frontend as Front+import qualified Feldspar.Compiler.Imperative.Representation as Rep (Type(..))+import Feldspar.Compiler.Imperative.Representation (Entity(..), Block(..),Expression(..), fv)+import Feldspar.Compiler.Imperative.Frontend import Feldspar.Compiler.Imperative.FromCore.Interpretation-import Feldspar.Compiler.Imperative.Plugin.CollectFreeVars-import Feldspar.Transformation (transform, Result(..)) -import Data.Map (elems)+import Data.Map (assocs) instance Compile dom dom => Compile (FUTURE :|| Type) dom where compileExprSym = compileProgFresh - compileProgSym (C' MkFuture) _ loc (p :* Nil) = do+ compileProgSym (C' MkFuture) info (Just loc) (p :* Nil) = do+ env <- ask+ let args = [case lookup v (alias env) of+ Nothing -> mkVariable (compileTypeRep t (defaultSize t)) v+ Just (VarExpr e) -> e+ | (v,SomeType t) <- assocs $ infoVars info+ ] ++ fv loc -- Task core:- (_, Bl ds t) <- confiscateBlock $ do+ ((_, ws), Block ds bl) <- confiscateBigBlock $ do p' <- compileExprVar p tellProg [iVarPut loc p']- let b = Block ds t- let vs = elems $ up $ transform Collect () () $ Front.fromInterface b funId <- freshId let coreName = "task_core" ++ show funId- tellDef [ProcDf coreName vs [] b]+ tellDef [Proc coreName args [] $ Just (Block (decl ws ++ ds) bl)] -- Task: let taskName = "task" ++ show funId- let runTask = run coreName vs- tellDef [ProcDf taskName [] [Front.Variable Void "params"] runTask]+ let runTask = Just $ toBlock $ run coreName args+ tellDef [Proc taskName [] [mkNamedRef "params" Rep.VoidType (-1)] runTask] -- Spawn:- tellProg [iVarInit loc]- tellProg [spawn taskName vs]+ tellProg [iVarInit (AddrOf loc)]+ tellProg [spawn taskName args] compileProgSym (C' Await) _ loc (a :* Nil) = do fut <- compileExprVar a -- compileExpr a- tellProg [iVarGet loc fut]+ tellProg [iVarGet l fut | Just l <- [loc]]
lib/Feldspar/Compiler/Imperative/FromCore/Interpretation.hs view
@@ -39,55 +39,77 @@ import Control.Arrow import Control.Monad.RWS+import Control.Applicative +import Data.Char (toLower)+import Data.List (intercalate)+import Data.Maybe (isJust, fromJust)+ import Language.Syntactic.Syntax hiding (result) import Language.Syntactic.Traversal import Language.Syntactic.Constraint import Language.Syntactic.Constructs.Binding (VarId) -import Feldspar.Range-import Feldspar.Core.Types hiding (Type)+import Feldspar.Range (upperBound, isSingleton)+import Feldspar.Core.Types hiding (Type, ArrayType, BoolType, FloatType, DoubleType,+ ComplexType, IVarType, Signedness, Size) import Feldspar.Core.Interpretation import qualified Feldspar.Core.Types as Core import qualified Feldspar.Core.Constructs.Binding as Core import qualified Feldspar.Core.Constructs.Literal as Core import Feldspar.Compiler.Imperative.Frontend-import Feldspar.Compiler.Imperative.Representation (typeof)+import Feldspar.Compiler.Imperative.Representation (typeof, Block(..),+ Type(..), Signedness(..),+ Size(..), Variable(..),+ Expression(..),+ Declaration(..),+ Program(..), Pattern(..),+ Entity(..), StructMember(..)) +import Feldspar.Compiler.Backend.C.Options (Options(..), Platform(..))+ -- | Code generation monad type CodeWriter = RWS Readers Writers States -data Readers = Readers { alias :: [(VarId, Expr)] -- ^ variable aliasing+data Readers = Readers { alias :: [(VarId, Expression ())] -- ^ variable aliasing , sourceInfo :: SourceInfo -- ^ Surrounding source info+ , backendOpts :: Options -- ^ Options for the backend. } -initReader :: Readers+initReader :: Options -> Readers initReader = Readers [] "" -data Writers = Writers { block :: Block -- ^ collects code within one block- , def :: [Ent] -- ^ collects top level definitions+data Writers = Writers { block :: Block () -- ^ collects code within one block+ , def :: [Entity ()] -- ^ collects top level definitions+ , decl :: [Declaration ()] -- ^ collects top level variable declarations+ , params :: [Variable ()] -- ^ collects top level parameters+ , epilogue :: [Program ()] -- ^ collects postlude code (freeing memory, etc) } instance Monoid Writers where mempty = Writers { block = mempty , def = mempty+ , decl = mempty+ , params = mempty+ , epilogue = mempty }- mappend a b = Writers { block = mappend (block a) (block b)- , def = mappend (def a) (def b)+ mappend a b = Writers { block = mappend (block a) (block b)+ , def = mappend (def a) (def b)+ , decl = mappend (decl a) (decl b)+ , params = mappend (params a) (params b)+ , epilogue = mappend (epilogue a) (epilogue b) } -type Task = [Prog]--data States = States { fresh :: Integer -- ^ The first fresh variable id+data States = States { fresh :: VarId -- ^ The first fresh variable id } initState :: States initState = States 0 -- | Where to place the program result-type Location = Expr+type Location = Maybe (Expression ()) -- | A minimal complete instance has to define either 'compileProgSym' or -- 'compileExprSym'.@@ -105,7 +127,7 @@ :: sub a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a- -> CodeWriter Expr+ -> CodeWriter (Expression ()) compileExprSym = compileProgFresh instance (Compile sub1 dom, Compile sub2 dom) =>@@ -137,99 +159,105 @@ => sub a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a- -> CodeWriter Expr+ -> CodeWriter (Expression ()) compileProgFresh a info args = do loc <- freshVar "e" (infoType info) (infoSize info)- compileProgSym a info loc args+ compileProgSym a info (Just loc) args return loc +compileDecor :: Info a -> CodeWriter b -> CodeWriter b+compileDecor info action = do+ let src = infoSource info+ aboveSrc <- asks sourceInfo+ unless (null src || src==aboveSrc) $ tellProg [Comment True src]+ local (\env -> env{sourceInfo=src}) action+ compileProgDecor :: Compile dom dom => Location -> Decor Info dom a -> Args (AST (Decor Info dom)) a -> CodeWriter ()-compileProgDecor result (Decor info a) args = do- let src = infoSource info- aboveSrc <- asks sourceInfo- unless (null src || src==aboveSrc) $ tellProg [BComment src]- local (\env -> env {sourceInfo = src}) $ compileProgSym a info result args+compileProgDecor result (Decor info a) args =+ compileDecor info $ compileProgSym a info result args compileExprDecor :: Compile dom dom => Decor Info dom a -> Args (AST (Decor Info dom)) a- -> CodeWriter Expr-compileExprDecor (Decor info a) args = do- let src = infoSource info- aboveSrc <- asks sourceInfo- unless (null src || src==aboveSrc) $ tellProg [BComment src]- local (\env -> env {sourceInfo = src}) $ compileExprSym a info args+ -> CodeWriter (Expression ())+compileExprDecor (Decor info a) args =+ compileDecor info $ compileExprSym a info args compileProg :: Compile dom dom => Location -> ASTF (Decor Info dom) a -> CodeWriter () compileProg result = simpleMatch (compileProgDecor result) -compileExpr :: Compile dom dom => ASTF (Decor Info dom) a -> CodeWriter Expr+compileExpr :: Compile dom dom => ASTF (Decor Info dom) a -> CodeWriter (Expression ()) compileExpr = simpleMatch compileExprDecor -- Compile an expression and make sure that the result is stored in a variable-compileExprVar :: Compile dom dom => ASTF (Decor Info dom) a -> CodeWriter Expr+compileExprVar :: Compile dom dom => ASTF (Decor Info dom) a -> CodeWriter (Expression ()) compileExprVar e = do e' <- compileExpr e case e' of- Var _ _ -> return e'- Ptr _ _ -> return e'- _ -> do+ VarExpr{} -> return e'+ _ -> do varId <- freshId- let loc = Var (typeof e') ('e' : show varId)+ let loc = varToExpr $ mkNamedVar "e" (typeof e') varId declare loc- assign loc e'+ assign (Just loc) e' return loc -------------------------------------------------------------------------------- -- * Utility functions -------------------------------------------------------------------------------- -compileNumType :: Signedness a -> BitWidth n -> Type-compileNumType U N8 = U8-compileNumType S N8 = I8-compileNumType U N16 = U16-compileNumType S N16 = I16-compileNumType U N32 = U32-compileNumType S N32 = I32-compileNumType U N64 = U64-compileNumType S N64 = I64-compileNumType U NNative = U32 -- TODO-compileNumType S NNative = I32 -- TODO+compileNumType :: Core.Signedness a -> BitWidth n -> Type+compileNumType U N8 = NumType Unsigned S8+compileNumType S N8 = NumType Signed S8+compileNumType U N16 = NumType Unsigned S16+compileNumType S N16 = NumType Signed S16+compileNumType U N32 = NumType Unsigned S32+compileNumType S N32 = NumType Signed S32+compileNumType U N64 = NumType Unsigned S64+compileNumType S N64 = NumType Signed S64+compileNumType U NNative = NumType Unsigned S32 -- TODO+compileNumType S NNative = NumType Signed S32 -- TODO -compileTypeRep :: TypeRep a -> Size a -> Type-compileTypeRep UnitType _ = Void-compileTypeRep BoolType _ = Boolean+mkStructType :: [(String, Type)] -> Type+mkStructType trs = StructType n trs+ where+ n = intercalate "_" $ "s" : map (encodeType . snd) trs++compileTypeRep :: TypeRep a -> Core.Size a -> Type+compileTypeRep UnitType _ = VoidType+compileTypeRep Core.BoolType _ = BoolType compileTypeRep (IntType s n) _ = compileNumType s n-compileTypeRep FloatType _ = Floating-compileTypeRep (ComplexType t) _ = Complex (compileTypeRep t (defaultSize t))-compileTypeRep (Tup2Type a b) (sa,sb) = Struct+compileTypeRep Core.FloatType _ = FloatType+compileTypeRep Core.DoubleType _ = DoubleType+compileTypeRep (Core.ComplexType t) _ = ComplexType (compileTypeRep t (defaultSize t))+compileTypeRep (Tup2Type a b) (sa,sb) = mkStructType [ ("member1", compileTypeRep a sa) , ("member2", compileTypeRep b sb) ]-compileTypeRep (Tup3Type a b c) (sa,sb,sc) = Struct+compileTypeRep (Tup3Type a b c) (sa,sb,sc) = mkStructType [ ("member1", compileTypeRep a sa) , ("member2", compileTypeRep b sb) , ("member3", compileTypeRep c sc) ]-compileTypeRep (Tup4Type a b c d) (sa,sb,sc,sd) = Struct+compileTypeRep (Tup4Type a b c d) (sa,sb,sc,sd) = mkStructType [ ("member1", compileTypeRep a sa) , ("member2", compileTypeRep b sb) , ("member3", compileTypeRep c sc) , ("member4", compileTypeRep d sd) ]-compileTypeRep (Tup5Type a b c d e) (sa,sb,sc,sd,se) = Struct+compileTypeRep (Tup5Type a b c d e) (sa,sb,sc,sd,se) = mkStructType [ ("member1", compileTypeRep a sa) , ("member2", compileTypeRep b sb) , ("member3", compileTypeRep c sc) , ("member4", compileTypeRep d sd) , ("member5", compileTypeRep e se) ]-compileTypeRep (Tup6Type a b c d e f) (sa,sb,sc,sd,se,sf) = Struct+compileTypeRep (Tup6Type a b c d e f) (sa,sb,sc,sd,se,sf) = mkStructType [ ("member1", compileTypeRep a sa) , ("member2", compileTypeRep b sb) , ("member3", compileTypeRep c sc)@@ -237,7 +265,7 @@ , ("member5", compileTypeRep e se) , ("member6", compileTypeRep f sf) ]-compileTypeRep (Tup7Type a b c d e f g) (sa,sb,sc,sd,se,sf,sg) = Struct+compileTypeRep (Tup7Type a b c d e f g) (sa,sb,sc,sd,se,sf,sg) = mkStructType [ ("member1", compileTypeRep a sa) , ("member2", compileTypeRep b sb) , ("member3", compileTypeRep c sc)@@ -248,76 +276,204 @@ ] compileTypeRep (MutType a) _ = compileTypeRep a (defaultSize a) compileTypeRep (RefType a) _ = compileTypeRep a (defaultSize a)-compileTypeRep (ArrayType a) (rs :> es) = if unboundedLength- then Array $ compileTypeRep a es- else SizedArray (fromEnum $ upperBound rs) $ compileTypeRep a es- where- unboundedLength- = upperBound rs > fromIntegral (maxBound :: Int)- -- This ensures that `fromEnum` succeeds- || upperBound rs == maxBound- -- This `maxBound` might be smaller than `maxBound :: Int`-compileTypeRep (MArrType a) _ = Array (compileTypeRep a (defaultSize a))+compileTypeRep (Core.ArrayType a) (rs :> es) = ArrayType rs $ compileTypeRep a es+compileTypeRep (MArrType a) (rs :> es) = ArrayType rs $ compileTypeRep a es compileTypeRep (ParType a) _ = compileTypeRep a (defaultSize a)-compileTypeRep (IVarType a) _ = IVar $ compileTypeRep a $ defaultSize a-compileTypeRep (FunType _ b) sz = compileTypeRep b sz-compileTypeRep (FValType a) sz = IVar $ compileTypeRep a sz+compileTypeRep (Core.IVarType a) _ = IVarType $ compileTypeRep a $ defaultSize a+compileTypeRep (FunType _ b) (_, sz) = compileTypeRep b sz+compileTypeRep (FValType a) sz = IVarType $ compileTypeRep a sz compileTypeRep typ _ = error $ "compileTypeRep: missing " ++ show typ -- TODO -mkVarName :: VarId -> String-mkVarName v = 'v' : show v+-- | Construct a variable.+mkVar :: Type -> VarId -> Expression ()+mkVar t i = varToExpr $ mkNamedVar "v" t i -mkVar :: Type -> VarId -> Expr-mkVar t = Var t . mkVarName+-- | Construct a named variable.+mkNamedVar :: String -> Type -> VarId -> Variable ()+mkNamedVar base t i = Variable t $ base ++ if i < 0 then "" else show i -mkVariable :: Type -> VarId -> Var-mkVariable t = Variable t . mkVarName+-- | Construct a named pointer.+mkNamedRef :: String -> Type -> VarId -> Variable ()+mkNamedRef base t i = Variable (Pointer t) $ base ++ if i < 0 then "" else show i -freshId :: CodeWriter Integer+-- | Construct a pointer.+mkRef :: Type -> VarId -> Expression ()+mkRef t i = varToExpr $ mkNamedRef "v" t i++mkVariable :: Type -> VarId -> Variable ()+mkVariable = mkNamedVar "v"++mkPointer :: Type -> VarId -> Variable ()+mkPointer = mkNamedRef "v"++freshId :: CodeWriter VarId freshId = do s <- get let v = fresh s put (s {fresh = v + 1}) return v -freshVar :: String -> TypeRep a -> Size a -> CodeWriter Expr -- TODO take just info instead of TypeRep and Size?-freshVar base t size = do- v <- freshId- let var =Var (compileTypeRep t size) $ base ++ show v- declare var- return var+freshVar :: String -> TypeRep a -> Core.Size a -> CodeWriter (Expression ()) -- TODO take just info instead of TypeRep and Size?+freshVar base t sz = do+ v <- varToExpr . mkNamedVar base (compileTypeRep t sz) <$> freshId+ declare v+ return v -declare :: Expr -> CodeWriter ()-declare (Var t n) = tellDecl [Def t n]-declare (Ptr t n) = tellDecl [Def t n]+freshAlias :: Expression () -> CodeWriter (Expression ())+freshAlias e = do i <- freshId+ let vexp = varToExpr $ mkNamedVar "e" (typeof e) i+ declareAlias vexp+ return vexp++declare :: Expression () -> CodeWriter ()+declare (VarExpr v@(Variable{})) = tellDeclWith True [Declaration v Nothing] declare expr = error $ "declare: cannot declare expression: " ++ show expr -tellDef :: [Ent] -> CodeWriter ()+declareAlias :: Expression () -> CodeWriter ()+declareAlias (VarExpr v@(Variable{})) = tellDeclWith False [Declaration v Nothing]+declareAlias expr = error $ "declareAlias: cannot declare expression: " ++ show expr++initialize :: Expression () -> Expression () -> CodeWriter ()+initialize (VarExpr v@(Variable{})) e = tellDeclWith True [Declaration v (Just e)]+initialize expr _ = error $ "initialize: cannot declare expression: " ++ show expr++tellDef :: [Entity ()] -> CodeWriter () tellDef es = tell $ mempty {def = es} -tellProg :: [Prog] -> CodeWriter ()-tellProg ps = tell $ mempty {block = Bl [] $ Seq ps}+tellProg :: [Program ()] -> CodeWriter ()+tellProg [BlockProgram b@(Block [] _)] = tell $ mempty {block = b}+tellProg ps = tell $ mempty {block = toBlock $ Sequence ps} -tellDecl :: [Def] -> CodeWriter ()-tellDecl ds = tell $ mempty {block = Bl ds $ Seq []}+tellDeclWith :: Bool -> [Declaration ()] -> CodeWriter ()+tellDeclWith free ds = do+ rs <- ask+ let frees | free = freeArrays ds ++ freeIVars ds+ | otherwise = []+ opts = backendOpts rs+ defs = getTypes opts ds+ code | varFloating $ platform opts = mempty {decl=ds, epilogue = frees, def = defs}+ | otherwise = mempty {block = Block ds Empty,+ epilogue = frees, def = defs}+ tell code -assign :: Location -> Expr -> CodeWriter ()-assign lhs rhs = if isArray $ typeof lhs- then- tellProg [ initArray lhs $ arrayLength rhs- , copyProg lhs rhs]- else- tellProg [copyProg lhs rhs]+encodeType :: Type -> String+encodeType = go+ where+ go VoidType = "void"+ go BoolType = "bool"+ go BitType = "bit"+ go FloatType = "float"+ go DoubleType = "double"+ go (NumType s w) = map toLower (show s) ++ show w+ go (ComplexType t) = "complex" ++ go t+ go (Pointer t) = "ptr_" ++ go t+ go (UserType t) = t+ go (Alias _ s) = s+ go (IVarType t) = go t+ go (NativeArray _ t) = go t+ go (StructType n _) = n+ go (ArrayType l t) = intercalate "_" ["arr", go t, if isSingleton l+ then show (upperBound l)+ else "UD"+ ] +getTypes :: Options -> [Declaration ()] -> [Entity ()]+getTypes _ defs = concatMap mkDef comps+ where+ comps = filter isComposite' $ map (typeof . dVar) defs+ -- There are other composite types that are not flagged as such by this+ -- version of isComposite, so keep it private.+ isComposite' :: Type -> Bool+ isComposite' (StructType {}) = True+ isComposite' (Pointer t) = isComposite' t+ isComposite' e = isArray e+ mkDef (StructType n members)+ = concatMap (mkDef . snd) members+ ++ [StructDef n (map (uncurry StructMember) members)]+ mkDef (ArrayType _ typ) = mkDef typ+ mkDef (Pointer typ) = mkDef typ+ mkDef _ = []++assign :: Location -> Expression () -> CodeWriter ()+assign (Just tgt) src = tellProg [if tgt == src then Empty else copyProg (Just tgt) [src]]+assign _ _ = return ()++shallowAssign :: Location -> Expression () -> CodeWriter ()+shallowAssign (Just dst) src | dst /= src = tellProg [Assign dst src]+shallowAssign loc src = return ()++freshAliasInit :: Expression () -> CodeWriter (Expression ())+freshAliasInit e = do vexp <- freshAlias e+ tellProg [Assign vexp e]+ return vexp++shallowCopyWithRefSwap :: Expression () -> Expression () -> CodeWriter ()+shallowCopyWithRefSwap dst src + | dst /= src+ = case filter (hasReference . snd) $ flattenStructs $ typeof dst of+ [] -> tellProg [Assign dst src]+ arrs -> do temps <- sequence [freshAliasInit $ accF dst | (accF,t) <- arrs]+ tellProg [Assign dst src]+ tellProg [Assign (accF src) tmp | (tmp, (accF,t)) <- zip temps arrs]+ | otherwise = return ()++shallowCopyReferences :: Expression () -> Expression () -> CodeWriter ()+shallowCopyReferences dst src = tellProg [Assign (accF dst) (accF src) | (accF, t) <- flattenStructs $ typeof dst, hasReference t]++{- + This function implements double buffering of state for nonmutable seqential loops (forLoop and whileLoop).+ The intention is to generate the minimal amount of copying (especially deep array copies) while also avoiding+ frequent references to data that can not be allocated in registers.++ The state of the loop is implemented by two variables so that the loop body reads from one and writes to+ the other. At the end of the body, the contents of the second (write) variable is shallow copied to the + first (read) variable. In order to avoid inadvertent sharing of data referenced by pointers in the variables + (array buffers, for instance), the pointers in the state are swapped rather than just copied so that the end + up in the variable written to. Finally the read variable is shallow copied to the result location.++ There are some simplifying cases:+ - When the target lvalue loc is a variable, and thus cheap to access, it is reused as the read state variable+ - When the type of the state is scalar, so that assignment is atomic, only one state variable is used and it + is both read and written to in the loop body, eliminating the shallow copy in the loop body.++ The strategy implemented a compromise between different design constraints:+ - Avoid deep copying of arrays (that is what the double buffering is for)+ - Avoid shallow copying if possible+ - Avoid memory leaks of arrays and lvars+-}++mkDoubleBufferState :: Expression () -> VarId -> CodeWriter (Expression (), Expression ())+mkDoubleBufferState loc stvar+ = do stvar1 <- if isVarExpr loc || containsNativeArray (typeof loc) + then return loc+ else do vexp <- freshAlias loc+ shallowCopyReferences vexp loc+ return vexp+ stvar2 <- if isComposite $ typeof loc + then do let vexp2 = mkVar (typeof loc) stvar + declare vexp2+ return vexp2+ else return stvar1+ return (stvar1,stvar2)++ -- | Like 'listen', but also prevents the program from being written in the -- monad.-confiscateBlock :: CodeWriter a -> CodeWriter (a, Block)+confiscateBlock :: CodeWriter a -> CodeWriter (a, Block ()) confiscateBlock m = liftM (second block) $ censor (\rec -> rec {block = mempty}) $ listen m -withAlias :: VarId -> Expr -> CodeWriter a -> CodeWriter a+-- | Like 'listen', but also catches writer things and prevents the program+-- from being written in the monad.+confiscateBigBlock :: CodeWriter a -> CodeWriter ((a, Writers), Block ())+confiscateBigBlock m+ = liftM (\c -> (c, block $ snd c))+ $ censor (\rec -> rec {block = mempty, decl = mempty, epilogue = mempty})+ $ listen m++withAlias :: VarId -> Expression () -> CodeWriter a -> CodeWriter a withAlias v0 expr = local (\e -> e {alias = (v0,expr) : alias e}) @@ -332,11 +488,25 @@ , Project (Core.Variable :|| Core.Type) dom , Compile dom dom )- => ASTF (Decor Info dom) a -> CodeWriter Expr-mkLength a | isVariableOrLiteral a = compileExpr a- | otherwise = do- let lentyp = IntType U N32- lenvar <- freshVar "len" lentyp (defaultSize lentyp)- compileProg lenvar a- return lenvar+ => ASTF (Decor Info dom) a -> TypeRep a -> Core.Size a -> CodeWriter (Expression ())+mkLength a t sz + | isVariableOrLiteral a = compileExpr a+ | otherwise = do+ lenvar <- freshVar "len" t sz+ compileProg (Just lenvar) a+ return lenvar +mkBranch :: (Compile dom dom)+ => Location -> ASTF (Decor Info dom) Bool -> ASTF (Decor Info dom) a -> Maybe (ASTF (Decor Info dom) a) -> CodeWriter ()+mkBranch loc c th el = do+ ce <- compileExpr c+ (_, tb) <- confiscateBlock $ compileProg loc th+ (_, eb) <- if isJust el then confiscateBlock $ compileProg loc (fromJust el) else return (undefined, toBlock Empty)+ tellProg [Switch ce [(Pat (litB True), tb), (Pat (litB False), eb)]]+++isComposite :: Type -> Bool+isComposite ArrayType{} = True+isComposite NativeArray{} = True+isComposite StructType{} = True+isComposite _ = False
lib/Feldspar/Compiler/Imperative/FromCore/Literal.hs view
@@ -32,120 +32,102 @@ {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -module Feldspar.Compiler.Imperative.FromCore.Literal where+module Feldspar.Compiler.Imperative.FromCore.Literal+ (literal)+ where -import Control.Monad.RWS import Data.Complex-import GHC.Float (float2Double) import Language.Syntactic import Feldspar.Core.Types as Core-import Feldspar.Core.Interpretation+import Feldspar.Core.Interpretation (Info(..)) import Feldspar.Core.Constructs.Literal -import Feldspar.Range (upperBound)- import Feldspar.Compiler.Imperative.Frontend+import Feldspar.Compiler.Imperative.Representation (Expression(..),Constant(..))+import qualified Feldspar.Compiler.Imperative.Representation as Rep (Type(..),+ Signedness(..),+ Size(..)) import Feldspar.Compiler.Imperative.FromCore.Interpretation instance Compile (Literal :|| Core.Type) dom where compileExprSym (C' (Literal a)) info Nil = literal (infoType info) (infoSize info) a - compileProgSym (C' (Literal a)) info loc Nil = literalLoc loc (infoType info) (infoSize info) a+ compileProgSym (C' (Literal a)) info loc Nil = case loc of+ Just l -> literalLoc l (infoType info) (infoSize info) a+ Nothing -> return () -literal :: TypeRep a -> Size a -> a -> CodeWriter Expr-literal UnitType _ () = return $ LitI I32 0-literal BoolType _ a = return $ boolToExpr a-literal trep@IntType{} sz a = return $ LitI (compileTypeRep trep sz) (toInteger a)-literal FloatType _ a = return $ LitF $ float2Double a-literal (ComplexType t) _ (r:+i) = do re <- literal t (defaultSize t) r- ie <- literal t (defaultSize t) i- return $ LitC re ie+literal :: TypeRep a -> Size a -> a -> CodeWriter (Expression ())+literal t@UnitType sz a = return (ConstExpr $ literalConst t sz a)+literal t@BoolType sz a = return (ConstExpr $ literalConst t sz a)+literal t@IntType{} sz a = return (ConstExpr $ literalConst t sz a)+literal t@FloatType sz a = return (ConstExpr $ literalConst t sz a)+literal t@DoubleType sz a = return (ConstExpr $ literalConst t sz a)+literal t@ComplexType{} sz a = return (ConstExpr $ literalConst t sz a)+literal t@ArrayType{} sz a = return (ConstExpr $ literalConst t sz a) literal t s a = do loc <- freshVar "x" t s literalLoc loc t s a return loc -literalLoc :: Location -> TypeRep a -> Size a -> a -> CodeWriter ()-literalLoc loc (ArrayType t) (rs :> es) e- = do- tellProg [initArray loc $ LitI I32 $ toInteger $ upperBound rs]- zipWithM_ (writeElement t es) (map (LitI I32) [0..]) e- where writeElement :: TypeRep a -> Size a -> Expr -> a -> CodeWriter ()- writeElement ty sz ix x = do- expr <- literal ty sz x- assign (loc :!: ix) expr+literalConst :: TypeRep a -> Size a -> a -> Constant ()+literalConst UnitType _ () = IntConst 0 (Rep.NumType Rep.Unsigned Rep.S32)+literalConst BoolType _ a = BoolConst a+literalConst trep@IntType{} sz a = IntConst (toInteger a) (compileTypeRep trep sz)+literalConst FloatType _ a = FloatConst a+literalConst DoubleType _ a = DoubleConst a+literalConst (ArrayType t) _ a = ArrayConst $ map (literalConst t (defaultSize t)) a+literalConst (ComplexType t) _ (r:+i) = ComplexConst re ie+ where re = literalConst t (defaultSize t) r+ ie = literalConst t (defaultSize t) i +literalLoc :: Expression () -> TypeRep a -> Size a -> a -> CodeWriter ()+literalLoc loc arr@ArrayType{} sz e+ = tellProg [copyProg (Just loc) [ConstExpr $ literalConst arr sz e]]+ literalLoc loc (Tup2Type ta tb) (sa,sb) (a,b) =- do aExpr <- literal ta sa a- bExpr <- literal tb sb b- assign (loc :.: "member1") aExpr- assign (loc :.: "member2") bExpr+ do literalLoc (StructField loc "member1") ta sa a+ literalLoc (StructField loc "member2") tb sb b literalLoc loc (Tup3Type ta tb tc) (sa,sb,sc) (a,b,c) =- do aExpr <- literal ta sa a- bExpr <- literal tb sb b- cExpr <- literal tc sc c- assign (loc :.: "member1") aExpr- assign (loc :.: "member2") bExpr- assign (loc :.: "member3") cExpr+ do literalLoc (StructField loc "member1") ta sa a+ literalLoc (StructField loc "member2") tb sb b+ literalLoc (StructField loc "member3") tc sc c literalLoc loc (Tup4Type ta tb tc td) (sa,sb,sc,sd) (a,b,c,d) =- do aExpr <- literal ta sa a- bExpr <- literal tb sb b- cExpr <- literal tc sc c- dExpr <- literal td sd d- assign (loc :.: "member1") aExpr- assign (loc :.: "member2") bExpr- assign (loc :.: "member3") cExpr- assign (loc :.: "member4") dExpr+ do literalLoc (StructField loc "member1") ta sa a+ literalLoc (StructField loc "member2") tb sb b+ literalLoc (StructField loc "member3") tc sc c+ literalLoc (StructField loc "member4") td sd d literalLoc loc (Tup5Type ta tb tc td te) (sa,sb,sc,sd,se) (a,b,c,d,e) =- do aExpr <- literal ta sa a- bExpr <- literal tb sb b- cExpr <- literal tc sc c- dExpr <- literal td sd d- eExpr <- literal te se e- assign (loc :.: "member1") aExpr- assign (loc :.: "member2") bExpr- assign (loc :.: "member3") cExpr- assign (loc :.: "member4") dExpr- assign (loc :.: "member5") eExpr+ do literalLoc (StructField loc "member1") ta sa a+ literalLoc (StructField loc "member2") tb sb b+ literalLoc (StructField loc "member3") tc sc c+ literalLoc (StructField loc "member4") td sd d+ literalLoc (StructField loc "member5") te se e literalLoc loc (Tup6Type ta tb tc td te tf) (sa,sb,sc,sd,se,sf) (a,b,c,d,e,f) =- do aExpr <- literal ta sa a- bExpr <- literal tb sb b- cExpr <- literal tc sc c- dExpr <- literal td sd d- eExpr <- literal te se e- fExpr <- literal tf sf f- assign (loc :.: "member1") aExpr- assign (loc :.: "member2") bExpr- assign (loc :.: "member3") cExpr- assign (loc :.: "member4") dExpr- assign (loc :.: "member5") eExpr- assign (loc :.: "member6") fExpr+ do literalLoc (StructField loc "member1") ta sa a+ literalLoc (StructField loc "member2") tb sb b+ literalLoc (StructField loc "member3") tc sc c+ literalLoc (StructField loc "member4") td sd d+ literalLoc (StructField loc "member5") te se e+ literalLoc (StructField loc "member6") tf sf f literalLoc loc (Tup7Type ta tb tc td te tf tg) (sa,sb,sc,sd,se,sf,sg) (a,b,c,d,e,f,g) =- do aExpr <- literal ta sa a- bExpr <- literal tb sb b- cExpr <- literal tc sc c- dExpr <- literal td sd d- eExpr <- literal te se e- fExpr <- literal tf sf f- gExpr <- literal tg sg g- assign (loc :.: "member1") aExpr- assign (loc :.: "member2") bExpr- assign (loc :.: "member3") cExpr- assign (loc :.: "member4") dExpr- assign (loc :.: "member5") eExpr- assign (loc :.: "member6") fExpr- assign (loc :.: "member7") gExpr+ do literalLoc (StructField loc "member1") ta sa a+ literalLoc (StructField loc "member2") tb sb b+ literalLoc (StructField loc "member3") tc sc c+ literalLoc (StructField loc "member4") td sd d+ literalLoc (StructField loc "member5") te se e+ literalLoc (StructField loc "member6") tf sf f+ literalLoc (StructField loc "member7") tg sg g literalLoc loc t sz a = do rhs <- literal t sz a- assign loc rhs+ assign (Just loc) rhs
lib/Feldspar/Compiler/Imperative/FromCore/Loop.hs view
@@ -28,12 +28,14 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-}+{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module Feldspar.Compiler.Imperative.FromCore.Loop where +import Data.Typeable (Typeable(..)) import Prelude hiding (init) @@ -48,41 +50,54 @@ import Feldspar.Core.Constructs.Literal import qualified Feldspar.Core.Constructs.Loop as Core -import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Compiler.Imperative.Frontend+import Feldspar.Compiler.Imperative.Representation (Program(..), Block(..),+ typeof) import Feldspar.Compiler.Imperative.FromCore.Interpretation+import Feldspar.Compiler.Imperative.FromCore.Binding (compileBind) instance ( Compile dom dom , Project (CLambda Type) dom , Project (Literal :|| Type) dom , Project (Variable :|| Type) dom+ , Project Let dom+ , ConstrainedBy dom Typeable ) => Compile (Loop :|| Type) dom where- compileProgSym (C' ForLoop) _ loc (len :* init :* (lam1 :$ (lam2 :$ ixf)) :* Nil)+ compileProgSym (C' ForLoop) _ (Just loc) (len :* init :* (lam1 :$ lt1) :* Nil) | Just (SubConstr2 (Lambda ix)) <- prjLambda lam1+ , (bs1, lam2 :$ ixf) <- collectLetBinders lt1 , Just (SubConstr2 (Lambda st)) <- prjLambda lam2 = do+ blocks <- mapM (confiscateBlock . compileBind) bs1 let info1 = getInfo lam1- info2 = getInfo lam2- let (Var _ name) = mkVar (compileTypeRep (infoType info1) (infoSize info1)) ix- let stvar = mkVar (compileTypeRep (infoType info2) (infoSize info2)) st- len' <- mkLength len- compileProg loc init- (_, Bl ds body) <- withAlias st loc $ confiscateBlock $ compileProg stvar ixf >> assign loc stvar- declare stvar- tellProg [For name len' 1 (Block ds body)]+ sz = fst $ infoSize info1+ (dss, lets) = unzip $ map (\(_, Block ds (Sequence body)) -> (ds, body)) blocks+ let ix' = mkVar (compileTypeRep (infoType info1) (infoSize info1)) ix+ len' <- mkLength len (infoType $ getInfo len) sz+ (lstate, stvar) <- mkDoubleBufferState loc st+ compileProg (Just lstate) init+ (_, Block ds body) <- withAlias st lstate $ confiscateBlock + $ compileProg (Just stvar) ixf >> (shallowCopyWithRefSwap lstate stvar)+ tellProg [toProg $ Block (concat dss ++ ds) (for False (lName ix') len' (litI32 1) (toBlock $ Sequence $ concat lets ++ [body]))]+ shallowAssign (Just loc) lstate - compileProgSym (C' WhileLoop) _ loc (init :* (lam1 :$ cond) :* (lam2 :$ body) :* Nil)+ compileProgSym (C' WhileLoop) _ (Just loc) (init :* (lam1 :$ cond) :* (lam2 :$ body) :* Nil) | Just (SubConstr2 (Lambda cv)) <- prjLambda lam1 , Just (SubConstr2 (Lambda cb)) <- prjLambda lam2 = do let info2 = getInfo lam2+ info1 = getInfo lam1 let stvar = mkVar (compileTypeRep (infoType info2) (infoSize info2)) cb- compileProg loc init- cond' <- withAlias cv loc $ compileExpr cond- (_, Bl ds body') <- withAlias cb loc $ confiscateBlock $ compileProg stvar body >> assign loc stvar- declare stvar- tellProg [While Skip cond' (Block ds body')]+ condv = mkVar (compileTypeRep (infoType info1) (infoSize info1)) cv+ (lstate,stvar) <- mkDoubleBufferState loc cb+ compileProg (Just lstate) init+ (_, cond') <- confiscateBlock $ withAlias cv lstate $ compileProg (Just condv) cond+ (_, body') <- withAlias cb lstate $ confiscateBlock $ compileProg (Just stvar) body >> shallowCopyWithRefSwap lstate stvar+ declare condv+ tellProg [while cond' condv body']+ shallowAssign (Just loc) lstate instance ( Compile dom dom , Project (CLambda Type) dom@@ -95,16 +110,18 @@ | Just (SubConstr2 (Lambda v)) <- prjLambda lam = do let ta = argType $ infoType $ getInfo lam- let sa = defaultSize ta- let (Var _ name) = mkVar (compileTypeRep ta sa) v- len' <- mkLength len- (_, Bl _ body) <- confiscateBlock $ compileProg loc ixf- tellProg [For name len' 1 body]+ let sa = fst $ infoSize $ getInfo lam+ let ix = mkVar (compileTypeRep ta sa) v+ len' <- mkLength len (infoType $ getInfo len) sa+ (_, Block ds body) <- confiscateBlock $ compileProg loc ixf+ tellProg [toProg $ Block ds (for False (lName ix) len' (litI32 1) (toBlock body))] -- TODO Missing While compileProgSym Core.While _ loc (cond :* step :* Nil) = do- cond' <- compileExpr cond- (_, Bl _ step') <- confiscateBlock $ compileProg loc step- tellProg [While Skip cond' step']+ let info1 = getInfo cond+ condv <- freshVar "cond" (infoType info1) (infoSize info1)+ (_, cond') <- confiscateBlock $ compileProg (Just condv) cond+ (_, step') <- confiscateBlock $ compileProg loc step+ tellProg [while cond' condv step']
lib/Feldspar/Compiler/Imperative/FromCore/Mutable.hs view
@@ -35,6 +35,7 @@ module Feldspar.Compiler.Imperative.FromCore.Mutable where +import Control.Applicative import Language.Syntactic import Language.Syntactic.Constructs.Binding@@ -47,41 +48,38 @@ import Feldspar.Core.Constructs.MutableArray import Feldspar.Core.Constructs.MutableReference -import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Compiler.Imperative.Frontend import Feldspar.Compiler.Imperative.FromCore.Interpretation--+import qualified Feldspar.Compiler.Imperative.Representation as Rep (Type(..),+ Size(..),+ Signedness(..))+import Feldspar.Compiler.Imperative.Representation (Expression(..),+ Program(..)) -instance (Compile dom dom, Project (CLambda Type) dom) => Compile (MONAD Mut) dom+instance ( Compile dom dom+ , Project (CLambda Type) dom+ )+ => Compile (MONAD Mut) dom where compileProgSym Bind _ loc (ma :* (lam :$ body) :* Nil) | Just (SubConstr2 (Lambda v)) <- prjLambda lam = do- e <- compileExpr ma- withAlias v e $ compileProg loc body--{- TODO reenable this implementation! The case above inlines too much if v is used more than once in the body- compileProgSym Bind _ loc (ma :* (Symbol (Decor info lam) :$ body) :* Nil)- | Just (Lambda v) <- prjCtx typeCtx lam- = do- let var = mkVar (compileTypeRep $ argType $ infoType info) v- withDecl var $ do- compileProg var ma- compileProg loc body--}+ let info = getInfo ma+ var = mkVar (compileTypeRep (infoType info) (infoSize info)) v+ declare var+ compileProg (Just var) ma+ compileProg loc body compileProgSym Then _ loc (ma :* mb :* Nil) = do- compileExpr ma+ compileProg Nothing ma compileProg loc mb compileProgSym Return info loc (a :* Nil) | MutType UnitType <- infoType info = return () | otherwise = compileProg loc a - compileProgSym When _ loc (c :* action :* Nil) = do- c' <- compileExpr c- (_, Bl ds body) <- confiscateBlock $ compileProg loc action- tellProg [If c' (Block ds body) Skip]+ compileProgSym When _ loc (c :* action :* Nil) =+ mkBranch loc c action Nothing instance (Compile dom dom, Project (CLambda Type) dom) => Compile Mutable dom where@@ -95,7 +93,14 @@ compileProgSym GetRef _ loc (r :* Nil) = compileProg loc r compileProgSym SetRef _ _ (r :* a :* Nil) = do var <- compileExpr r- compileProg var a+ compileProg (Just var) a+ compileProgSym ModRef _ _ (r :* (lam :$ body) :* Nil)+ | Just (SubConstr2 (Lambda v)) <- prjLambda lam+ = do+ var <- compileExpr r+ withAlias v var $ compileProg (Just var) body+ -- Since the modifier function is pure it is safe to alias+ -- v with var here compileExprSym GetRef _ (r :* Nil) = compileExpr r compileExprSym feat info args = compileProgFresh feat info args@@ -107,28 +112,29 @@ tellProg [initArray loc l] compileProgSym NewArr _ loc (len :* a :* Nil) = do- let ix = Var U32 "i"+ nId <- freshId+ let ix = varToExpr $ mkNamedVar "i" (Rep.NumType Rep.Unsigned Rep.S32) nId a' <- compileExpr a l <- compileExpr len tellProg [initArray loc l]- tellProg [For "i" l 1 (Seq [assignProg (loc :!: ix) a'])]+ tellProg [for False "i" l (litI32 1) $ toBlock (Sequence [copyProg (ArrayElem <$> loc <*> pure ix) [a']])] compileProgSym GetArr _ loc (arr :* i :* Nil) = do arr' <- compileExpr arr i' <- compileExpr i- assign loc (arr' :!: i')+ assign loc (ArrayElem arr' i') compileProgSym SetArr _ _ (arr :* i :* a :* Nil) = do arr' <- compileExpr arr i' <- compileExpr i a' <- compileExpr a- assign (arr' :!: i') a'+ assign (Just $ ArrayElem arr' i') a' compileProgSym a info loc args = compileExprLoc a info loc args - compileExprSym ArrLength info (arr :* Nil) = do+ compileExprSym ArrLength _ (arr :* Nil) = do a' <- compileExpr arr- return $ Fun (compileTypeRep (infoType info) (infoSize info)) "getLength" [a']+ return $ arrayLength a' compileExprSym a info args = compileProgFresh a info args
lib/Feldspar/Compiler/Imperative/FromCore/MutableToPure.hs view
@@ -28,6 +28,7 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-}@@ -43,9 +44,11 @@ import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Binding+import Feldspar.Core.Constructs.Mutable+import Feldspar.Core.Constructs.MutableArray import Feldspar.Core.Constructs.MutableToPure -import Feldspar.Compiler.Imperative.Frontend hiding (Type,Variable)+import Feldspar.Compiler.Imperative.Frontend import Feldspar.Compiler.Imperative.FromCore.Interpretation @@ -53,6 +56,8 @@ instance ( Compile dom dom , Project (CLambda Type) dom , Project (Variable :|| Type) dom+ , Project (MONAD Mut) dom+ , Project MutableArray dom ) => Compile MutableToPure dom where@@ -63,20 +68,50 @@ e <- compileExpr marr withAlias v1 e $ do b <- compileExpr body- tellProg [copyProg loc b]+ tellProg [copyProg loc [b]] compileProgSym WithArray _ loc (marr :* (lam :$ body) :* Nil) | Just (SubConstr2 (Lambda v)) <- prjLambda lam = do let ta = argType $ infoType $ getInfo lam- let sa = defaultSize ta+ let sa = fst $ infoSize $ getInfo lam let var = mkVar (compileTypeRep ta sa) v declare var- compileProg var marr+ compileProg (Just var) marr e <- compileExpr body- tellProg [copyProg loc e]+ tellProg [copyProg loc [e]] + compileProgSym RunMutableArray _ (Just loc) ((bnd :$ (na :$ l) :$ (lam :$ body)) :* Nil)+ | Just (SubConstr2 (Lambda v)) <- prjLambda lam+ , Just Bind <- prjMonad monadProxy bnd+ , Just NewArr_ <- prj na+ , (ret :$ rv) <- chaseBind body+ , Just Return <- prjMonad monadProxy ret+ , Just (C' (Variable r)) <- prjF rv+ , v == r+ = do+ len <- compileExpr l+ tellProg [setLength (Just loc) len]+ withAlias v loc $ compileProg (Just loc) body+ compileProgSym RunMutableArray _ loc (marr :* Nil) = compileProg loc marr++-- | Chase down the right-spine of `Bind` and `Then` constructs and return+-- the last term+chaseBind :: ( Project (MONAD Mut) dom+ , Project (CLambda Type) dom+ )+ => AST dom a -> AST dom a+chaseBind (bnd :$ _ :$ (lam :$ body))+ | Just Bind <- prjMonad monadProxy bnd+ , Just (SubConstr2 (Lambda _)) <- prjLambda lam+ = chaseBind body++chaseBind (thn :$ _ :$ body)+ | Just Then <- prjMonad monadProxy thn+ = chaseBind body++chaseBind a = a {- NOTES:
lib/Feldspar/Compiler/Imperative/FromCore/NoInline.hs view
@@ -35,31 +35,33 @@ module Feldspar.Compiler.Imperative.FromCore.NoInline where -import Data.Map (elems)+import Data.Map (assocs) import Data.List (partition) import Language.Syntactic -import Feldspar.Core.Types (Type)+import Feldspar.Core.Types (Type,defaultSize)+import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.NoInline-import Feldspar.Transformation (transform, Result(..))+import Feldspar.Compiler.Imperative.Representation (Variable(..),+ ActualParameter(..),+ Entity(..), typeof) import Feldspar.Compiler.Imperative.FromCore.Interpretation-import Feldspar.Compiler.Imperative.Frontend hiding (Type,Variable)-import Feldspar.Compiler.Imperative.Plugin.CollectFreeVars-import qualified Feldspar.Compiler.Imperative.Frontend as Front+import Feldspar.Compiler.Imperative.Frontend instance Compile dom dom => Compile (NoInline :|| Type) dom where compileExprSym = compileProgFresh - compileProgSym (C' NoInline) _ loc (p :* Nil) = do- (_, Bl ds t) <- confiscateBlock $ compileProg loc p- let b = Block ds t- let vs = elems $ up $ transform Collect () () $ Front.fromInterface b- let isInParam v = Front.vName v /= Front.lName loc- let (ins,outs) = partition isInParam vs+ compileProgSym (C' NoInline) info (Just loc) (p :* Nil) = do+ let args = [mkVariable (compileTypeRep t (defaultSize t)) v+ | (v,SomeType t) <- assocs $ infoVars info+ ]+ (_, b) <- confiscateBlock $ compileProg (Just loc) p+ let isInParam v = vName v /= lName loc+ let (ins,outs) = partition isInParam args funId <- freshId let funname = "noinline" ++ show funId- tellDef [ProcDf funname ins outs b]- let ins' = map (\v -> Front.In $ Front.Var (vType v) (Front.vName v)) ins- tellProg [Call funname $ ins' ++ [Out loc]]+ tellDef [Proc funname ins outs $ Just b]+ let ins' = map (\v -> ValueParameter $ varToExpr $ Variable (typeof v) (vName v)) ins+ tellProg [call funname $ ins' ++ [ValueParameter loc]]
lib/Feldspar/Compiler/Imperative/FromCore/Par.hs view
@@ -34,24 +34,26 @@ module Feldspar.Compiler.Imperative.FromCore.Par where +import Control.Monad.RWS (ask)+ import Language.Syntactic import Language.Syntactic.Constructs.Monad-import Language.Syntactic.Constructs.Binding+import Language.Syntactic.Constructs.Binding hiding (Variable) import Language.Syntactic.Constructs.Binding.HigherOrder import Feldspar.Core.Types import Feldspar.Core.Interpretation-import Feldspar.Core.Constructs.Binding+import Feldspar.Core.Constructs.Binding hiding (Variable) import Feldspar.Core.Constructs.Par -import Feldspar.Compiler.Imperative.Frontend hiding (Type,Variable)+import Feldspar.Compiler.Imperative.Frontend+import Feldspar.Compiler.Imperative.Representation (Block(..), Program(..),+ Entity(..), typeof,+ Expression(..), fv) import Feldspar.Compiler.Imperative.FromCore.Interpretation-import Feldspar.Compiler.Imperative.Plugin.CollectFreeVars-import qualified Feldspar.Compiler.Imperative.Frontend as Front import qualified Feldspar.Compiler.Imperative.Representation as AIR-import Feldspar.Transformation (transform, Result(..)) -import Data.Map (elems)+import Data.Map (assocs) instance ( Compile dom dom , Project (CLambda Type) dom@@ -66,7 +68,7 @@ let info = getInfo ma let var = mkVar (compileTypeRep (infoType info) (infoSize info)) v declare var- tellProg [iVarInit var]+ tellProg [iVarInit (AddrOf var)] compileProg loc body compileProgSym Bind _ loc (ma :* (lam :$ body) :* Nil)@@ -76,17 +78,15 @@ withAlias v e $ compileProg loc body compileProgSym Then _ loc (ma :* mb :* Nil) = do- compileExpr ma+ compileProg Nothing ma compileProg loc mb compileProgSym Return info loc (a :* Nil) | ParType UnitType <- infoType info = return () | otherwise = compileProg loc a - compileProgSym When _ loc (c :* action :* Nil) = do- c' <- compileExpr c- (_, Bl ds body) <- confiscateBlock $ compileProg loc action- tellProg [If c' (Block ds body) Skip]+ compileProgSym When _ loc (c :* action :* Nil) =+ mkBranch loc c action Nothing instance ( Compile dom dom , Project (Variable :|| Type) dom@@ -99,34 +99,38 @@ compileProgSym ParGet _ loc (r :* Nil) = do iv <- compileExpr r- tellProg [iVarGet loc iv]+ tellProg [iVarGet l iv | Just l <- [loc]] compileProgSym ParPut _ _ (r :* a :* Nil) = do iv <- compileExpr r val <- compileExpr a i <- freshId- let var = Var (AIR.typeof val) $ "msg" ++ show i+ let var = varToExpr $ mkNamedVar "msg" (typeof val) i declare var- assign var val+ assign (Just var) val tellProg [iVarPut iv var] - compileProgSym ParFork _ loc (p :* Nil) = do+ compileProgSym ParFork info loc (p :* Nil) = do+ env <- ask+ let args = [case lookup v (alias env) of+ Nothing -> mkVariable (compileTypeRep t (defaultSize t)) v+ Just (VarExpr e) -> e+ | (v,SomeType t) <- assocs $ infoVars info+ ] ++ maybe [] fv loc -- Task core:- (_, Bl ds t) <- confiscateBlock $ compileProg loc p- let b = Block ds t- let vs = elems $ up $ transform Collect () () $ Front.fromInterface b+ ((_, ws), Block ds b) <- confiscateBigBlock $ compileProg loc p funId <- freshId let coreName = "task_core" ++ show funId- tellDef [ProcDf coreName vs [] b]+ tellDef [Proc coreName args [] $ Just (Block (decl ws ++ ds) b)] -- Task: let taskName = "task" ++ show funId- let runTask = run coreName vs- tellDef [ProcDf taskName [] [Front.Variable Void "params"] runTask]+ let runTask = Just $ toBlock $ run coreName args+ tellDef [Proc taskName [] [mkNamedRef "params" AIR.VoidType (-1)] runTask] -- Spawn:- tellProg [spawn taskName vs]+ tellProg [spawn taskName args] compileProgSym ParYield _ _ Nil = return () compileProgSym ParNew _ _ Nil = return () -+ compileProgSym a info loc args = compileExprLoc a info loc args
lib/Feldspar/Compiler/Imperative/FromCore/Primitive.hs view
@@ -50,9 +50,11 @@ import Feldspar.Core.Constructs.Logic import Feldspar.Core.Constructs.Num import Feldspar.Core.Constructs.Ord+import Feldspar.Core.Constructs.RealFloat import Feldspar.Core.Constructs.Trace -import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Compiler.Imperative.Frontend+import Feldspar.Compiler.Imperative.Representation (Expression(..)) import Feldspar.Compiler.Imperative.FromCore.Interpretation @@ -62,14 +64,14 @@ where compileExprSym (Sem name _) info args = do argExprs <- sequence $ listArgs compileExpr args- return $ Fun (compileTypeRep (infoType info) (infoSize info)) name argExprs+ return $ fun (compileTypeRep (infoType info) (infoSize info)) name argExprs -- | Convenient implementation of 'compileExprSym' for primitive functions compilePrim :: (Semantic expr, Compile dom dom) => (expr :|| Type) a -> Info (DenResult a) -> Args (AST (Decor Info dom)) a- -> CodeWriter Expr+ -> CodeWriter (Expression ()) compilePrim (C' s) = compileExprSym $ semantics s instance Compile dom dom => Compile (BITS :|| Type) dom where compileExprSym = compilePrim@@ -82,5 +84,6 @@ instance Compile dom dom => Compile (Logic :|| Type) dom where compileExprSym = compilePrim instance Compile dom dom => Compile (NUM :|| Type) dom where compileExprSym = compilePrim instance Compile dom dom => Compile (ORD :|| Type) dom where compileExprSym = compilePrim+instance Compile dom dom => Compile (REALFLOAT :|| Type) dom where compileExprSym = compilePrim instance Compile dom dom => Compile (Trace :|| Type) dom where compileExprSym = compilePrim
lib/Feldspar/Compiler/Imperative/FromCore/SourceInfo.hs view
@@ -41,17 +41,17 @@ import Feldspar.Core.Types import Feldspar.Core.Constructs.SourceInfo -import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Compiler.Imperative.Representation (Program(..)) import Feldspar.Compiler.Imperative.FromCore.Interpretation -instance Compile dom dom => Compile ((Decor SourceInfo1 Identity) :|| Type) dom+instance Compile dom dom => Compile (Decor SourceInfo1 Identity :|| Type) dom where compileProgSym (C' (Decor (SourceInfo1 info) Id)) _ loc (a :* Nil) = do- tellProg [BComment info]+ tellProg [Comment True info] compileProg loc a compileExprSym (C' (Decor (SourceInfo1 info) Id)) _ (a :* Nil) = do- tellProg [BComment info]+ tellProg [Comment True info] compileExpr a
+ lib/Feldspar/Compiler/Imperative/FromCore/Switch.hs view
@@ -0,0 +1,59 @@+{-# LANGUAGE GADTs #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}++module Feldspar.Compiler.Imperative.FromCore.Switch where++import Language.Syntactic+import Language.Syntactic.Constructs.Binding++import Feldspar.Core.Types (Type)+import Feldspar.Core.Interpretation+import Feldspar.Core.Constructs.Eq+import Feldspar.Core.Constructs.Condition+import Feldspar.Core.Constructs.Switch++import qualified Feldspar.Compiler.Imperative.Representation as R+import Feldspar.Compiler.Imperative.FromCore.Interpretation+++instance ( Compile dom dom+ , Project (EQ :|| Type) dom+ , Project (Condition :|| Type) dom+ )+ => Compile (Switch :|| Type) dom+ where+ compileProgSym (C' Switch) _ loc (tree@(cond :$ (op :$ _ :$ s) :$ _ :$ _) :* Nil)+ | Just (C' Condition) <- prjF cond+ , Just (C' Equal) <- prjF op+ = do+ scrutinee <- compileExpr s+ alts <- chaseTree loc s tree+ tellProg [R.Switch{..}]++ compileProgSym (C' Switch) _ loc (tree :* Nil)+ = compileProg loc tree++chaseTree :: ( Compile dom dom+ , Project (Condition :|| Type) dom+ , Project (EQ :|| Type) dom+ )+ => Location -> ASTF (Decor Info dom) a -> ASTF (Decor Info dom) b -> CodeWriter [(R.Pattern (), R.Block ())]+chaseTree loc s (cond :$ (op :$ c :$ a) :$ t :$ f)+ | Just (C' Condition) <- prjF cond+ , Just (C' Equal) <- prjF op+ -- , alphaEq s a -- TODO check that the scrutinees are equal+ = do+ e <- compileExpr c+ (_,body) <- confiscateBlock $ compileProg loc t+ cases <- chaseTree loc s f+ return $ (R.Pat e, body) : cases++chaseTree loc s a = do+ (_,body) <- confiscateBlock $ compileProg loc a+ return [(R.PatDefault, body)]+
lib/Feldspar/Compiler/Imperative/FromCore/Tuple.hs view
@@ -35,13 +35,14 @@ module Feldspar.Compiler.Imperative.FromCore.Tuple where +import Control.Applicative import Language.Syntactic import Feldspar.Core.Types import Feldspar.Core.Constructs.Tuple -import Feldspar.Compiler.Imperative.Frontend hiding (Type)+import Feldspar.Compiler.Imperative.Representation (Expression(..)) import Feldspar.Compiler.Imperative.FromCore.Interpretation @@ -49,60 +50,60 @@ instance Compile dom dom => Compile (Tuple :|| Type) dom where compileProgSym (C' Tup2) _ loc (m1 :* m2 :* Nil) = do- compileExpr m1 >>= assign (loc :.: "member1")- compileExpr m2 >>= assign (loc :.: "member2")+ compileProg (StructField <$> loc <*> pure "member1") m1+ compileProg (StructField <$> loc <*> pure "member2") m2 compileProgSym (C' Tup3) _ loc (m1 :* m2 :* m3 :* Nil) = do- compileExpr m1 >>= assign (loc :.: "member1")- compileExpr m2 >>= assign (loc :.: "member2")- compileExpr m3 >>= assign (loc :.: "member3")+ compileProg (StructField <$> loc <*> pure "member1") m1+ compileProg (StructField <$> loc <*> pure "member2") m2+ compileProg (StructField <$> loc <*> pure "member3") m3 compileProgSym (C' Tup4) _ loc (m1 :* m2 :* m3 :* m4 :* Nil) = do- compileExpr m1 >>= assign (loc :.: "member1")- compileExpr m2 >>= assign (loc :.: "member2")- compileExpr m3 >>= assign (loc :.: "member3")- compileExpr m4 >>= assign (loc :.: "member4")+ compileProg (StructField <$> loc <*> pure "member1") m1+ compileProg (StructField <$> loc <*> pure "member2") m2+ compileProg (StructField <$> loc <*> pure "member3") m3+ compileProg (StructField <$> loc <*> pure "member4") m4 compileProgSym (C' Tup5) _ loc (m1 :* m2 :* m3 :* m4 :* m5 :* Nil) = do- compileExpr m1 >>= assign (loc :.: "member1")- compileExpr m2 >>= assign (loc :.: "member2")- compileExpr m3 >>= assign (loc :.: "member3")- compileExpr m4 >>= assign (loc :.: "member4")- compileExpr m5 >>= assign (loc :.: "member5")+ compileProg (StructField <$> loc <*> pure "member1") m1+ compileProg (StructField <$> loc <*> pure "member2") m2+ compileProg (StructField <$> loc <*> pure "member3") m3+ compileProg (StructField <$> loc <*> pure "member4") m4+ compileProg (StructField <$> loc <*> pure "member5") m5 compileProgSym (C' Tup6) _ loc (m1 :* m2 :* m3 :* m4 :* m5 :* m6 :* Nil) = do- compileExpr m1 >>= assign (loc :.: "member1")- compileExpr m2 >>= assign (loc :.: "member2")- compileExpr m3 >>= assign (loc :.: "member3")- compileExpr m4 >>= assign (loc :.: "member4")- compileExpr m5 >>= assign (loc :.: "member5")- compileExpr m6 >>= assign (loc :.: "member6")+ compileProg (StructField <$> loc <*> pure "member1") m1+ compileProg (StructField <$> loc <*> pure "member2") m2+ compileProg (StructField <$> loc <*> pure "member3") m3+ compileProg (StructField <$> loc <*> pure "member4") m4+ compileProg (StructField <$> loc <*> pure "member5") m5+ compileProg (StructField <$> loc <*> pure "member6") m6 compileProgSym (C' Tup7) _ loc (m1 :* m2 :* m3 :* m4 :* m5 :* m6 :* m7 :* Nil) = do- compileExpr m1 >>= assign (loc :.: "member1")- compileExpr m2 >>= assign (loc :.: "member2")- compileExpr m3 >>= assign (loc :.: "member3")- compileExpr m4 >>= assign (loc :.: "member4")- compileExpr m5 >>= assign (loc :.: "member5")- compileExpr m6 >>= assign (loc :.: "member6")- compileExpr m7 >>= assign (loc :.: "member7")+ compileProg (StructField <$> loc <*> pure "member1") m1+ compileProg (StructField <$> loc <*> pure "member2") m2+ compileProg (StructField <$> loc <*> pure "member3") m3+ compileProg (StructField <$> loc <*> pure "member4") m4+ compileProg (StructField <$> loc <*> pure "member5") m5+ compileProg (StructField <$> loc <*> pure "member6") m6+ compileProg (StructField <$> loc <*> pure "member7") m7 instance Compile dom dom => Compile (Select :|| Type) dom where compileExprSym (C' Sel1) _ (tup :* Nil) = do tupExpr <- compileExpr tup- return $ tupExpr :.: "member1"+ return $ StructField tupExpr "member1" compileExprSym (C' Sel2) _ (tup :* Nil) = do tupExpr <- compileExpr tup- return $ tupExpr :.: "member2"+ return $ StructField tupExpr "member2" compileExprSym (C' Sel3) _ (tup :* Nil) = do tupExpr <- compileExpr tup- return $ tupExpr :.: "member3"+ return $ StructField tupExpr "member3" compileExprSym (C' Sel4) _ (tup :* Nil) = do tupExpr <- compileExpr tup- return $ tupExpr :.: "member4"+ return $ StructField tupExpr "member4" compileExprSym (C' Sel5) _ (tup :* Nil) = do tupExpr <- compileExpr tup- return $ tupExpr :.: "member5"+ return $ StructField tupExpr "member5" compileExprSym (C' Sel6) _ (tup :* Nil) = do tupExpr <- compileExpr tup- return $ tupExpr :.: "member6"+ return $ StructField tupExpr "member6" compileExprSym (C' Sel7) _ (tup :* Nil) = do tupExpr <- compileExpr tup- return $ tupExpr :.: "member7"+ return $ StructField tupExpr "member7"
lib/Feldspar/Compiler/Imperative/Frontend.hs view
@@ -26,451 +26,224 @@ -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RecordWildCards #-} module Feldspar.Compiler.Imperative.Frontend where -import Data.List-import Data.Monoid-import Control.Arrow (second)--import Feldspar.Compiler.Imperative.Representation hiding (Type, UserType, Cast, In, Out, Variable, Block, Pointer, Comment, Spawn, Run)-import qualified Feldspar.Compiler.Imperative.Representation as AIR----- * Frontend data types--data Mod = Mod [Ent]- deriving (Show)--data Ent- = StructD String [(String, Type)]- | ProcDf String [Var] [Var] Prog- | ProcDcl String [Var] [Var]- deriving (Eq,Show)--data Type- = Void- | Boolean- | Bit- | Floating- | I8 | I16 | I32 | I40 | I64- | U8 | U16 | U32 | U40 | U64- | Complex Type- | UserType String- | Array Type- | SizedArray Int Type- | Struct [(String, Type)]- | IVar Type- deriving Eq--data Expr- = Var Type String- | Ptr Type String- | Tr- | Fl- | LitI Type Integer- | LitF Double- | LitC Expr Expr- | Expr :!: Expr- | Expr :.: String- | Binop Type String [Expr]- | Fun Type String [Expr]- | Cast Type Expr- | SizeofE Expr- | SizeofT Type- deriving (Eq,Show)+import Feldspar.Compiler.Imperative.Representation -data Prog- = Skip- | BComment String- | Comment String- | Expr := Expr- | Call String [Param]- | Seq [Prog]- | If Expr Prog Prog- | While Prog Expr Prog- | For String Expr Int Prog- | Block [Def] Prog- deriving (Eq,Show)+import Feldspar.Range+import Feldspar.Core.Types (Length) -instance Monoid Prog- where- mempty = Skip- mappend Skip p = p- mappend p Skip = p- mappend (Seq pa) (Seq pb) = Seq $ mappend pa pb- mappend pa pb = Seq [mappend pa pb]+toBlock :: Program () -> Block ()+toBlock (BlockProgram b) = b+toBlock p = Block [] p -data Param- = In Expr- | Out Expr- | TypAuto Type- | TypScalar Type- | Fn String- | FnAddr String- deriving (Eq,Show)+toProg :: Block () -> Program ()+toProg (Block [] p) = p+toProg e = BlockProgram e -data Block = Bl [Def] Prog- deriving (Eq,Show)+-- | Copies expressions into a destination. If the destination is+-- a non-scalar the arguments are appended to the destination.+copyProg :: Maybe (Expression ())-> [Expression ()] -> Program ()+copyProg _ [] = error "copyProg: missing source parameter."+copyProg Nothing _ = Empty+copyProg (Just outExp) inExp+ | outExp == head inExp+ && null (tail inExp) = Empty+ | otherwise = call "copy" (map ValueParameter (outExp:inExp)) -instance Monoid Block+mkInitialize :: String -> Maybe (Expression ()) -> Expression () -> Program ()+mkInitialize _ Nothing _ = Empty+mkInitialize name (Just arr) len = Assign arr $ fun (typeof arr) name [arr, sz, len] where- mempty = Bl [] Skip- mappend (Bl da pa) (Bl db pb) = Bl (mappend da db) (mappend pa pb)+ sz | isArray t' = binop (NumType Unsigned S32) "-" (litI32 0) t+ | otherwise = t+ t = SizeOf t'+ t' = go $ typeof arr+ go (ArrayType _ e) = e+ go (Pointer typ) = go typ+ go _ = error $ "Feldspar.Compiler.Imperative.Frontend." ++ name ++ ": invalid type of array " ++ show arr ++ "::" ++ show (typeof arr) -data Def- = Init Type String Expr- | Def Type String- deriving (Eq,Show)+initArray :: Maybe (Expression ()) -> Expression () -> Program ()+initArray = mkInitialize "initArray" -data Var- = Variable Type String- | Pointer Type String- deriving (Eq,Show)+setLength :: Maybe (Expression ()) -> Expression () -> Program ()+setLength = mkInitialize "setLength" -class Named a where- getName :: a -> String-instance Named Def where- getName (Init _ n _) = n- getName (Def _ n) = n-instance Named Var where- getName (Variable _ n) = n- getName (Pointer _ n) = n+freeArray :: Variable () -> Program ()+freeArray arr = call "freeArray" [ValueParameter $ varToExpr arr] --- * Conversion between representation and frontend+freeArrays :: [Declaration ()] -> [Program ()]+freeArrays defs = map freeArray arrays+ where+ arrays = filter (isArray . typeof) $ map dVar defs -class Interface t where- type Repr t- toInterface :: Repr t -> t- fromInterface :: t -> Repr t+arrayLength :: Expression () -> Expression ()+arrayLength arr+ | Just r <- chaseArray arr = litI32 $ fromIntegral (upperBound r)+ | otherwise = FunctionCall (Function "getLength" (NumType Unsigned S32) Prefix) [arr] -instance Interface Mod where- type Repr Mod = AIR.Module ()- toInterface (Module es ()) = Mod $ map toInterface es- fromInterface (Mod es) = AIR.Module (map fromInterface es) ()+chaseArray :: Expression t-> Maybe (Range Length)+chaseArray = go [] -- TODO: Extend to handle x.member1.member2+ where go :: [String] -> Expression t -> Maybe (Range Length)+ go [] (ConstExpr (ArrayConst l)) = Just (singletonRange $ fromIntegral $ length l)+ go [] (VarExpr (Variable (ArrayType r _) _)) | isSingleton r = Just r+ go [] (VarExpr (Variable (NativeArray (Just r) _) _)) = Just (singletonRange r)+ go ss (StructField e s) = go (s:ss) e+ go ss (AddrOf e) = go ss e+ go (s:_) (VarExpr (Variable (StructType _ fields) _))+ | Just (ArrayType r _) <- lookup s fields+ , isSingleton r = Just r+ | Just (NativeArray (Just r) _) <- lookup s fields+ = Just (singletonRange r)+ go _ _ = Nothing -instance Interface Ent where- type Repr Ent = AIR.Entity ()- toInterface (AIR.StructDef name members () ()) =- StructD name (map (\(StructMember mname mtyp ())->(mname,toInterface mtyp)) members)- toInterface (AIR.ProcDef name inparams outparams body () ()) =- ProcDf name (map toInterface inparams) (map toInterface outparams) (toProg body)- toInterface (AIR.ProcDecl name inparams outparams () ()) =- ProcDcl name (map toInterface inparams) (map toInterface outparams)- toInterface AIR.TypeDef{} = error "TypeDef not handled"- fromInterface (StructD name members) =- AIR.StructDef name (map (\(mname,mtyp)->(StructMember mname (fromInterface mtyp) ())) members) () ()- fromInterface (ProcDf name inparams outparams body) =- AIR.ProcDef name (map fromInterface inparams) (map fromInterface outparams) (toBlock body) () ()- fromInterface (ProcDcl name inparams outparams) =- AIR.ProcDecl name (map fromInterface inparams) (map fromInterface outparams) () ()+iVarInit :: Expression () -> Program ()+iVarInit var = call "ivar_init" [ValueParameter var] -instance Interface Type where- type Repr Type = AIR.Type- toInterface VoidType = Void- toInterface Alias{} = error "Alias not handled"- toInterface AIR.BoolType = Boolean- toInterface BitType = Bit- toInterface AIR.FloatType = Floating- toInterface (NumType Signed S8) = I8- toInterface (NumType Signed S16) = I16- toInterface (NumType Signed S32) = I32- toInterface (NumType Signed S40) = I40- toInterface (NumType Signed S64) = I64- toInterface (NumType Unsigned S8) = U8- toInterface (NumType Unsigned S16) = U16- toInterface (NumType Unsigned S32) = U32- toInterface (NumType Unsigned S40) = U40- toInterface (NumType Unsigned S64) = U64- toInterface (AIR.ComplexType t) = Complex $ toInterface t- toInterface (AIR.UserType s) = UserType s- toInterface (AIR.ArrayType (LiteralLen l) t) = SizedArray l $ toInterface t- toInterface (AIR.ArrayType _ t) = Array $ toInterface t- toInterface (AIR.StructType fields) = Struct $ map (second toInterface) fields- toInterface (AIR.IVarType t) = IVar $ toInterface t- fromInterface Void = VoidType- fromInterface Boolean = AIR.BoolType- fromInterface Bit = BitType- fromInterface Floating = AIR.FloatType- fromInterface I8 = NumType Signed S8- fromInterface I16 = NumType Signed S16- fromInterface I32 = NumType Signed S32- fromInterface I40 = NumType Signed S40- fromInterface I64 = NumType Signed S64- fromInterface U8 = NumType Unsigned S8- fromInterface U16 = NumType Unsigned S16- fromInterface U32 = NumType Unsigned S32- fromInterface U40 = NumType Unsigned S40- fromInterface U64 = NumType Unsigned S64- fromInterface (Complex t) = AIR.ComplexType $ fromInterface t- fromInterface (UserType s) = AIR.UserType s- fromInterface (Array t) = AIR.ArrayType UndefinedLen $ fromInterface t- fromInterface (SizedArray l t) = AIR.ArrayType (LiteralLen l) $ fromInterface t- fromInterface (Struct fields) = AIR.StructType $ map (second fromInterface) fields- fromInterface (IVar t) = AIR.IVarType $ fromInterface t+iVarGet :: Expression () -> Expression () -> Program ()+iVarGet loc ivar + | isArray typ = call "ivar_get_array" [ValueParameter loc, ValueParameter ivar]+ | otherwise = call "ivar_get" [TypeParameter typ, ValueParameter (AddrOf loc), ValueParameter ivar]+ where+ typ = typeof loc -instance Interface Expr where- type Repr Expr = Expression ()- toInterface (VarExpr (AIR.Variable name t Value ()) ()) = Var (toInterface t) name- toInterface (VarExpr (AIR.Variable name t AIR.Pointer ()) ()) = Ptr (toInterface t) name- toInterface (ArrayElem arr idx () ()) = toInterface arr :!: toInterface idx- toInterface (StructField str field () ()) = toInterface str :.: field- toInterface (ConstExpr (BoolConst True () ()) ()) = Tr- toInterface (ConstExpr (BoolConst False () ()) ()) = Fl- toInterface (ConstExpr (IntConst x t () ()) ()) = LitI (toInterface t) x- toInterface (ConstExpr (FloatConst x () ()) ()) = LitF x- toInterface (ConstExpr (ComplexConst r i () ()) ()) = LitC (toInterface $ ConstExpr r ()) (toInterface $ ConstExpr i ())- toInterface (FunctionCall (Function name t Prefix) ps () ()) = Fun (toInterface t) name $ map toInterface ps- toInterface (FunctionCall (Function name t Infix) ps () ()) = Binop (toInterface t) name $ map toInterface ps- toInterface (AIR.Cast t e () ()) = Cast (toInterface t) (toInterface e)- toInterface (SizeOf (Left t) () ()) = SizeofT $ toInterface t- toInterface (SizeOf (Right e) () ()) = SizeofE $ toInterface e- fromInterface (Var t name) = VarExpr (AIR.Variable name (fromInterface t) Value ()) ()- fromInterface (Ptr t name) = VarExpr (AIR.Variable name (fromInterface t) AIR.Pointer ()) ()- fromInterface (Tr) = ConstExpr (BoolConst True () ()) ()- fromInterface (Fl) = ConstExpr (BoolConst False () ()) ()- fromInterface (LitI t x) = ConstExpr (IntConst x (fromInterface t) () ()) ()- fromInterface (LitF x) = ConstExpr (FloatConst x () ()) ()- fromInterface (LitC (fromInterface -> (ConstExpr r ())) (fromInterface -> (ConstExpr i ()))) =- ConstExpr (ComplexConst r i () ()) ()- fromInterface (LitC _ _) = error "Illegal LitC" -- TODO (?)- fromInterface (Binop t name es) = FunctionCall (Function name (fromInterface t) Infix) (map fromInterface es) () ()- fromInterface (Fun t name es) = FunctionCall (Function name (fromInterface t) Prefix) (map fromInterface es) () ()- fromInterface (Cast t e) = AIR.Cast (fromInterface t) (fromInterface e) () ()- fromInterface (SizeofE e) = SizeOf (Right $ fromInterface e) () ()- fromInterface (SizeofT t) = SizeOf (Left $ fromInterface t) () ()- fromInterface (arr :!: idx) = ArrayElem (fromInterface arr) (fromInterface idx) () ()- fromInterface (str :.: field) = StructField (fromInterface str) field () ()+iVarPut :: Expression () -> Expression () -> Program ()+iVarPut ivar msg+ | isArray typ = call "ivar_put_array" [ValueParameter ivar, ValueParameter msg]+ | otherwise = call "ivar_put" [TypeParameter typ, ValueParameter ivar, ValueParameter (AddrOf msg)]+ where+ typ = typeof msg -instance Interface Prog where- type Repr Prog = AIR.Program ()- toInterface (Empty () ()) = Skip- toInterface (AIR.Comment True s () ()) = BComment s- toInterface (AIR.Comment False s () ()) = Comment s- toInterface Assign{..} = toInterface lhs := toInterface rhs- toInterface (ProcedureCall s ps () ()) = Call s (map toInterface ps)- toInterface (Sequence ps () ()) = Seq (map toInterface ps)- toInterface (Branch e b1 b2 () ()) = If (toInterface e) (toProg b1) (toProg b2)- toInterface (SeqLoop e pe b () ()) = While (toProg pe) (toInterface e) (toProg b)- toInterface (ParLoop v e i b () ()) = For (varName v) (toInterface e) i (toProg b)- toInterface (BlockProgram b ()) = Block (map toInterface $ locals b) (toInterface $ blockBody b)- fromInterface (Skip) = Empty () ()- fromInterface (BComment s) = AIR.Comment True s () ()- fromInterface (Comment s) = AIR.Comment False s () ()- fromInterface (lhs := rhs) = Assign (fromInterface lhs) (fromInterface rhs) () ()- fromInterface (Call s ps) = ProcedureCall s (map fromInterface ps) () ()- fromInterface (Seq ps) = Sequence (map fromInterface ps) () ()- fromInterface (If e p1 p2) = Branch (fromInterface e) (toBlock p1) (toBlock p2) () ()- fromInterface (While pe e p) = SeqLoop (fromInterface e) (toBlock pe) (toBlock p) () ()- fromInterface (For s e i p) = ParLoop- (AIR.Variable s (NumType Unsigned S32) Value ()) (fromInterface e) i (toBlock p) () ()- fromInterface (Block ds p) = BlockProgram (AIR.Block (map fromInterface ds) (fromInterface p) ()) ()+iVarDestroy :: Variable () -> Program ()+iVarDestroy v = call "ivar_destroy" [ValueParameter $ AddrOf $ varToExpr v] -instance Interface Param where- type Repr Param = ActualParameter ()- toInterface (AIR.In e ()) = In (toInterface e)- toInterface (AIR.Out e ()) = Out (toInterface e)- toInterface (AIR.TypeParameter e AIR.Auto ()) = TypAuto (toInterface e)- toInterface (AIR.TypeParameter e AIR.Scalar ()) = TypScalar (toInterface e)- toInterface (AIR.FunParameter n False ()) = Fn n- toInterface (AIR.FunParameter n True ()) = FnAddr n- fromInterface (In e) = AIR.In (fromInterface e) ()- fromInterface (Out e) = AIR.Out (fromInterface e) ()- fromInterface (TypAuto e) = AIR.TypeParameter (fromInterface e) Auto ()- fromInterface (TypScalar e) = AIR.TypeParameter (fromInterface e) Scalar ()- fromInterface (Fn n) = AIR.FunParameter n False ()- fromInterface (FnAddr n) = AIR.FunParameter n True ()+freeIVars :: [Declaration ()] -> [Program ()]+freeIVars defs = map iVarDestroy ivars+ where+ ivars = filter (isIVar . typeof) $ map dVar defs -instance Interface Def where- type Repr Def = Declaration ()- toInterface (Declaration v (Just e) ()) = Init (toInterface $ varType v) (varName v) (toInterface e)- toInterface (Declaration v Nothing ()) = Def (toInterface $ varType v) (varName v)- fromInterface (Init t s e) = Declaration (AIR.Variable s (fromInterface t) Value ()) (Just $ fromInterface e) ()- fromInterface (Def t s) = Declaration (AIR.Variable s (fromInterface t) Value ()) Nothing ()+spawn :: String -> [Variable ()] -> Program ()+spawn taskName vs = call spawnName allParams+ where+ spawnName = "spawn" ++ show (length vs)+ taskParam = FunParameter taskName+ typeParams = map (TypeParameter . typeof) vs+ varParams = map (ValueParameter . mkv) vs+ where mkv v = let v' = VarExpr $ Variable (typeof v) (vName v)+ in if isPointer $ typeof v then AddrOf v' else v'+ allParams = taskParam : concat (zipWith (\a b -> [a,b]) typeParams varParams) -instance Interface Block where- type Repr Block = AIR.Block ()- toInterface (AIR.Block ds p ()) = Bl (map toInterface ds) (toInterface p)- fromInterface (Bl ds p) = AIR.Block (map fromInterface ds) (fromInterface p) ()+run :: String -> [Variable ()] -> Program ()+run taskName vs = call runName allParams+ where+ runName = "run" ++ show (length vs)+ typeParams = map (TypeParameter . typeof) vs+ taskParam = FunParameter taskName+ allParams = taskParam : typeParams -instance Interface Var where- type Repr Var = AIR.Variable ()- toInterface (AIR.Variable name typ Value ()) = Variable (toInterface typ) name- toInterface (AIR.Variable name typ AIR.Pointer ()) = Pointer (toInterface typ) name- fromInterface (Variable typ name) = AIR.Variable name (fromInterface typ) Value ()- fromInterface (Pointer typ name) = AIR.Variable name (fromInterface typ) AIR.Pointer ()+intWidth :: Type -> Maybe Integer+intWidth (NumType _ S8) = Just 8+intWidth (NumType _ S16) = Just 16+intWidth (NumType _ S32) = Just 32+intWidth (NumType _ S40) = Just 40+intWidth (NumType _ S64) = Just 64+intWidth _ = Nothing -toBlock :: Prog -> AIR.Block ()-toBlock (Block ds p) = AIR.Block (map fromInterface ds) (fromInterface p) ()-toBlock p = AIR.Block [] (fromInterface p) ()+intSigned :: Type -> Maybe Bool+intSigned (NumType Unsigned _) = Just False+intSigned (NumType Signed _) = Just True+intSigned _ = Nothing -toProg :: AIR.Block () -> Prog-toProg (AIR.Block [] p ()) = toInterface p-toProg (AIR.Block ds p ()) = Block (map toInterface ds) (toInterface p)+litF :: Float -> Expression t+litF n = ConstExpr (FloatConst n) -boolToExpr :: Bool -> Expr-boolToExpr True = Tr-boolToExpr False = Fl+litD :: Double -> Expression t+litD n = ConstExpr (DoubleConst n) -setLength :: Expr -> Expr -> Prog-setLength arr len = Call "setLength" [Out arr, In len]+litB :: Bool -> Expression ()+litB b = ConstExpr (BoolConst b) -copyProg :: Expr -> Expr -> Prog-copyProg outExp inExp = Call "copy" [Out outExp, In inExp]+litC :: Constant () -> Constant () -> Expression ()+litC r i = ConstExpr (ComplexConst r i) -copyProgPos :: Expr -> Expr -> Expr -> Prog-copyProgPos outExp shift inExp = Call "copyArrayPos" [Out outExp, In shift, In inExp]+litI :: Type -> Integer -> Expression ()+litI t n = ConstExpr (IntConst n t) -copyProgLen :: Expr -> Expr -> Expr -> Prog-copyProgLen outExp inExp len = Call "copyArrayLen" [Out outExp, In inExp, In len]+litI32 :: Integer -> Expression ()+litI32 = litI (NumType Unsigned S32) -initArray :: Expr -> Expr -> Prog-initArray arr len = Call "initArray" [Out arr, In s, In len]- where- s- | isArray t = Binop U32 "-" [LitI U32 0,SizeofT t]- | otherwise = SizeofT t- t = case typeof arr of- Array e -> e- SizedArray _ e -> e- _ -> error $ "Feldspar.Compiler.Imperative.Frontend.initArray: invalid type of array " ++ show arr ++ "::" ++ show (typeof arr)+isArray :: Type -> Bool+isArray ArrayType{} = True+isArray (Pointer t) = isArray t+isArray _ = False -assignProg :: Expr -> Expr -> Prog-assignProg lhs rhs- | isArray (typeof lhs) = Seq [ini,cp]- | otherwise = cp- where- ini = initArray lhs $ arrayLength rhs- cp = copyProg lhs rhs+isNativeArray :: Type -> Bool+isNativeArray NativeArray{} = True+isNativeArray (Pointer t) = isNativeArray t+isNativeArray _ = False -freeArray :: Var -> Prog-freeArray arr = Call "freeArray" [Out $ varToExpr arr]+isIVar :: Type -> Bool+isIVar IVarType{} = True+isIVar _ = False -arrayLength :: Expr -> Expr-arrayLength (Var (SizedArray n _) _) = LitI U32 $ fromIntegral n-arrayLength (Ptr (SizedArray n _) _) = LitI U32 $ fromIntegral n-arrayLength arr = Fun U32 "getLength" [arr]+isPointer :: Type -> Bool+isPointer Pointer{} = True+isPointer _ = False -iVarInit :: Expr -> Prog-iVarInit var = Call "ivar_init" [Out var]+isVarExpr :: Expression () -> Bool+isVarExpr VarExpr{} = True+isVarExpr _ = False -iVarGet :: Expr -> Expr -> Prog-iVarGet loc ivar - | isArray typ = Call "ivar_get_array" [Out loc, In ivar]- | otherwise = Call "ivar_get" [TypScalar typ, Out loc, In ivar]- where- typ = typeof loc+containsNativeArray :: Type -> Bool+containsNativeArray t = any (isNativeArray . snd) $ flattenStructs t -iVarPut :: Expr -> Expr -> Prog-iVarPut ivar msg- | isArray typ = Call "ivar_put_array" [In ivar, Out msg]- | otherwise = Call "ivar_put" [TypAuto typ, In ivar, Out msg]- where- typ = typeof msg+-- | Returns a list of access functions and types for the leaves of the struct tree of the type+flattenStructs :: Type -> [(Expression () -> Expression (), Type)]+flattenStructs (StructType _ fts) = [(\ e -> af $ StructField e fname, t') | (fname,t) <- fts, (af, t') <- flattenStructs t]+flattenStructs t = [(id, t)] -spawn :: String -> [Var] -> Prog-spawn taskName vs = Call spawnName allParams- where- spawnName = "spawn" ++ show (length vs)- taskParam = FnAddr taskName- typeParams = map (TypAuto . vType) vs- varParams = map (\v -> In $ Var (vType v) (vName v)) vs- allParams = taskParam : concat (zipWith (\a b -> [a,b]) typeParams varParams)+hasReference ArrayType{} = True+hasReference NativeArray{} = True -- TODO: Reconsider this safe approximation if we start using native arrays for performance+hasReference Pointer{} = True+hasReference IVarType{} = True+hasReference (StructType _ fs) = any (hasReference . snd) fs+hasReference t = False -run :: String -> [Var] -> Prog-run taskName vs = Call runName allParams- where- runName = "run" ++ show (length vs)- typeParams = map (TypAuto . vType) vs- taskParam = Fn taskName- allParams = taskParam : typeParams- -instance Show Type- where- show Void = "void"- show Boolean = "bool"- show Bit = "bit"- show Floating = "float"- show I8 = "int8"- show I16 = "int16"- show I32 = "int32"- show I40 = "int40"- show I64 = "int64"- show U8 = "uint8"- show U16 = "uint16"- show U32 = "uint32"- show U40 = "uint40"- show U64 = "uint64"- show (Complex t) = "complexOf_" ++ show t- show (UserType s) = "userType_" ++ s- show (Array t) = "arrayOf_" ++ show t- show (SizedArray i t) = "arrayOfSize_" ++ show i ++ "_" ++ show t- show (Struct fields) = "struct_" ++ intercalate "_" (map (\(s,t) -> s ++ "_" ++ show t) fields)- show (IVar t) = "ivarOf_" ++ show t+dVar :: Declaration () -> Variable ()+dVar (Declaration v _) = v -instance HasType Expr- where- type TypeOf Expr = Type- typeof = toInterface . typeof . fromInterface+vName :: Variable t -> String+vName Variable{..} = varName -instance HasType Var- where- type TypeOf Var = Type- typeof = toInterface . typeof . fromInterface+lName :: Expression t -> String+lName (VarExpr v@Variable{}) = vName v+lName (ArrayElem e _) = lName e+lName (StructField e _) = lName e+lName (AddrOf e) = lName e+lName e = error $ "Feldspar.Compiler.Imperative.Frontend.lName: invalid location: " ++ show e -intWidth :: Type -> Maybe Integer-intWidth I8 = Just 8-intWidth I16 = Just 16-intWidth I32 = Just 32-intWidth I40 = Just 40-intWidth I64 = Just 64-intWidth U8 = Just 8-intWidth U16 = Just 16-intWidth U32 = Just 32-intWidth U40 = Just 40-intWidth U64 = Just 64-intWidth _ = Nothing+varToExpr :: Variable t -> Expression t+varToExpr = VarExpr -intSigned :: Type -> Maybe Bool-intSigned I8 = Just True-intSigned I16 = Just True-intSigned I32 = Just True-intSigned I40 = Just True-intSigned I64 = Just True-intSigned U8 = Just False-intSigned U16 = Just False-intSigned U32 = Just False-intSigned U40 = Just False-intSigned U64 = Just False-intSigned _ = Nothing+binop :: Type -> String -> Expression () -> Expression () -> Expression ()+binop t n e1 e2 = fun' Infix t n [e1, e2] -litB :: Bool -> Expr-litB True = Tr-litB False = Fl+fun :: Type -> String -> [Expression ()] -> Expression ()+fun = fun' Prefix -isArray :: Type -> Bool-isArray (Array _) = True-isArray (SizedArray _ _) = True-isArray _ = False+fun' :: FunctionMode -> Type -> String -> [Expression ()] -> Expression ()+fun' m t n = FunctionCall (Function n t m) -vType :: Var -> Type-vType (Variable t _) = t-vType (Pointer t _) = t+call :: String -> [ActualParameter ()] -> Program ()+call = ProcedureCall -vName :: Var -> String-vName (Variable _ s) = s-vName (Pointer _ s) = s+for :: Bool -> String -> Expression () -> Expression () -> Block () -> Program ()+for _ _ _ _ (Block [] (Sequence [Empty])) = Empty+for p s e i b = ParLoop p (Variable (NumType Unsigned S32) s) e i b -lName :: Expr -> String-lName (Var _ s) = s-lName (Ptr _ s) = s-lName (e :!: _) = lName e-lName (e :.: _) = lName e-lName e = error $ "Feldspar.Compiler.Imperative.Frontend.lName: invalid location: " ++ show e+while :: Block () -> Expression () -> Block () -> Program ()+while p e = SeqLoop e p -varToExpr :: Var -> Expr-varToExpr (Variable t name) = Var t name-varToExpr (Pointer t name) = Ptr t name
− lib/Feldspar/Compiler/Imperative/Plugin/CollectFreeVars.hs
@@ -1,82 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.------ Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:------ * Redistributions of source code must retain the above copyright notice,--- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.------ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE--- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE GADTs #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE TypeOperators #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE OverlappingInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Imperative.Plugin.CollectFreeVars where--import Data.Map (Map)-import qualified Data.Map as Map-import qualified Feldspar.Compiler.Imperative.Frontend as Front-import Feldspar.Transformation--data Collect = Collect--type Collection = Map String Front.Var--instance Default Collection where- def = Map.empty--instance Combine Collection where- combine = Map.union--instance Transformation Collect- where- type From Collect = ()- type To Collect = ()- type Down Collect = ()- type Up Collect = Collection- type State Collect = ()--instance Plugin Collect- where- type ExternalInfo Collect = ()- executePlugin _ externalInfo = result . transform Collect () externalInfo--instance Transformable Collect Variable where- transform _ _ _ v = Result v () $ Map.singleton (varName v) (Front.toInterface v)--instance Transformable Collect Block where- transform t _ _ bl = Result bl' () diff- where- Result bl' _ m = defaultTransform t () () bl- localNames = map (varName . declVar) $ locals bl'- localMap = Map.fromList $ map (\name -> (name,())) localNames- diff = m `Map.difference` localMap--instance Transformable Collect Program where- transform t _ _ pr@(ParLoop idxVar _ _ _ _ _) = Result pr' () diff- where- Result pr' _ m = defaultTransform t () () pr- diff = Map.delete (varName idxVar) m- transform t _ _ prog = defaultTransform t () () prog
− lib/Feldspar/Compiler/Imperative/Plugin/ConstantFolding.hs
@@ -1,69 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Imperative.Plugin.ConstantFolding where--import Feldspar.Transformation--data ConstantFolding = ConstantFolding--instance Plugin ConstantFolding where- type ExternalInfo ConstantFolding = ()- executePlugin ConstantFolding _ procedure = result $ transform ConstantFolding () () procedure--instance Transformation ConstantFolding where- type From ConstantFolding = ()- type To ConstantFolding = ()- type Down ConstantFolding = ()- type Up ConstantFolding = ()- type State ConstantFolding = ()--instance Transformable ConstantFolding Expression where- transform t s d f@FunctionCall{} = case funMode $ function f' of- Infix -> case funName $ function f' of- "+" -> tr' $ elimParamIf (isConstIntN 0) True $ result tr- "-" -> tr' $ elimParamIf (isConstIntN 0) False $ result tr- "*" -> tr' $ elimParamIf (isConstIntN 1) True $ result tr- _ -> tr- _ -> tr- where- tr = defaultTransform t s d f- tr' x = tr {result = x}- f' = result tr- isConstIntN n (ConstExpr (IntConst i _ _ _) _) = n == i- isConstIntN _ _ = False-- elimParamIf predicate flippable funCall@(FunctionCall (Function _ _ Infix) (x:xs) _ _)- | predicate (head xs) = x- | flippable && predicate x = head xs- | otherwise = funCall- elimParamIf _ _ funCall = funCall- transform t s d e = defaultTransform t s d e
− lib/Feldspar/Compiler/Imperative/Plugin/Free.hs
@@ -1,61 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE GADTs #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE TypeOperators #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE OverlappingInstances #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Imperative.Plugin.Free where--import Feldspar.Compiler.Imperative.Frontend (toInterface, fromInterface, isArray, freeArray)-import Feldspar.Transformation--data Free = Free--instance Transformation Free- where- type From Free = ()- type To Free = ()- type Down Free = ()- type Up Free = ()- type State Free = ()--instance Plugin Free- where- type ExternalInfo Free = ()- executePlugin _ _ = result . transform Free () ()--instance Transformable Free Block where- transform _ _ _ (Block locs b _) = Result bl' () ()- where- arrays = filter (isArray . typeof) $ map (toInterface . declVar) locs- newBody = Sequence (b : map (fromInterface . freeArray) arrays) () ()- bl' = Block locs newBody ()
lib/Feldspar/Compiler/Imperative/Plugin/IVars.hs view
@@ -52,31 +52,17 @@ executePlugin _ _ = result . transform IVarPlugin () False instance Transformable IVarPlugin Entity where- transform t _ _ p@ProcDef{} = defaultTransform t () (isTask p) p+ transform t _ _ p@Proc{} = defaultTransform t () (isTask p) p where- isTask proc = "task" `isPrefixOf` procName proc -- TODO: this is hacky :)+ isTask _ = False -- KTask == procKind proc transform t _ d p = defaultTransform t () d p instance Transformable IVarPlugin Program where- transform _ _ d (ProcedureCall name ps _ _)+ transform _ _ d (ProcedureCall name ps) | "ivar_get" `isPrefixOf` name = Result pc' () () where- pc' = ProcedureCall name' ps () ()+ pc' = ProcedureCall name' ps name' | d = name | otherwise = name ++ "_nontask" transform t _ d x = defaultTransform t () d x--instance Transformable IVarPlugin Block where- transform t _ d b = Result b{ blockBody = body' } () ()- where- body' = Sequence prg () ()- prg = result (transform t () d $ blockBody b) : destrs- iVars = filter isIVar $ map declVar $ locals b- isIVar v = case varType v of- IVarType _ -> True- _ -> False- ivarFun s v = ProcedureCall ("ivar_" ++ s) [p] () ()- where- p = Out (VarExpr v ()) ()- destrs = map (ivarFun "destroy") iVars
− lib/Feldspar/Compiler/Imperative/Plugin/Naming.hs
@@ -1,194 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Imperative.Plugin.Naming where--import Data.List (isPrefixOf)--import Feldspar.Transformation--import qualified Feldspar.NameExtractor as Precompiler-import Feldspar.Compiler.Error-import Feldspar.Compiler.Backend.C.Library--import System.IO.Unsafe---- ===========================================================================--- == Precompilation plugin--- ===========================================================================--data SignatureInformation = SignatureInformation {- originalFunctionName :: String,- generatedImperativeParameterNames :: [String],- originalParameterNames :: Maybe [Maybe String]-} deriving (Show, Eq)--instance Default SignatureInformation where def = precompilationError InternalError "Default value should not be used"--precompilationError :: ErrorClass -> String -> a-precompilationError = handleError "PluginArch/Naming"--data Precompilation = Precompilation--instance Transformation Precompilation where- type From Precompilation = ()- type To Precompilation = ()- type Down Precompilation = SignatureInformation- type Up Precompilation = ()- type State Precompilation = ()---instance Transformable Precompilation Entity where- transform t s d x@(ProcDef n i _ _ _ _)- | n == "PLACEHOLDER" = tr { result = (result tr){ procName = n' } }- where- d' = d { generatedImperativeParameterNames = map varName i }- tr = defaultTransform t s d' x- n' = originalFunctionName d- transform t s d x@(ProcDef n _ _ _ _ _)- | any (n `isPrefixOf`) proceduresToPrefix = tr { result = (result tr){ procName = n' } }- where- n' = prefix d n- tr = defaultTransform t s d' x- d' = d{ generatedImperativeParameterNames = [] }- transform t s d x@ProcDef{} = defaultTransform t s d' x- where- d' = d{ generatedImperativeParameterNames = [] }- transform t s d x = defaultTransform t s d x---instance Transformable Precompilation Variable where- transform _ s d v = Result newVar s def- where- newVar = v - { varName = maybeStr2Str (getVariableName d $ varName v) ++ varName v- , varLabel = ()- }--instance Transformable Precompilation ActualParameter where- transform _ s d (FunParameter n addr _)- | any (n `isPrefixOf`) proceduresToPrefix- = Result (FunParameter (prefix d n) addr ()) s def- transform t s d x = defaultTransform t s d x--instance Transformable Precompilation Program where- transform t s d c@(ProcedureCall n _ _ _)- | any (n `isPrefixOf`) proceduresToPrefix = tr { result = (result tr){ procCallName = n' } }- where- tr = defaultTransform t s d c- n' = prefix d n- transform t s d x = defaultTransform t s d x--proceduresToPrefix :: [String]-proceduresToPrefix = ["noinline", "task"]--prefix :: SignatureInformation -> String -> String-prefix d n = originalFunctionName d ++ "_" ++ n--getVariableName :: SignatureInformation -> String -> Maybe String-getVariableName signatureInformation origname = case originalParameterNames signatureInformation of- Just originalParameterNameList ->- if length (generatedImperativeParameterNames signatureInformation) == length originalParameterNameList then- case searchResults of- [] -> Nothing- _ -> snd $ head searchResults- else- Nothing- -- precompilationError InternalError $ "parameter name list length mismatch:" ++- -- show (generatedImperativeParameterNames signatureInformation) ++ " " ++ show originalParameterNameList- where- searchResults = filter ((origname ==).fst)- (zip (generatedImperativeParameterNames signatureInformation) originalParameterNameList)- Nothing -> Nothing--maybeStr2Str :: Maybe String -> String-maybeStr2Str (Just s) = s ++ "_"-maybeStr2Str Nothing = ""--data PrecompilationExternalInfo = PrecompilationExternalInfo {- originalFunctionSignature :: Precompiler.OriginalFunctionSignature, - inputParametersDescriptor :: [Int],- numberOfFunctionArguments :: Int,- compilationMode :: CompilationMode-}--addPostfixNumberToMaybeString :: (Maybe String, Int) -> Maybe String-addPostfixNumberToMaybeString (ms, num) = ms >>= \s -> return $ s ++ show num--inflate :: Int -> [Maybe String] -> [Maybe String]-inflate target list | length list < target = inflate target (list++[Nothing])- | length list == target = list- | otherwise = precompilationError InternalError "Unexpected situation in 'inflate'"---- Replicates each element of the [parameter list given by the precompiler] based on the input parameter descriptor-parameterNameListConsolidator :: PrecompilationExternalInfo -> [Maybe String]-parameterNameListConsolidator externalInfo =- if numberOfFunctionArguments externalInfo == length (inputParametersDescriptor externalInfo)- then- concatMap (uncurry replicate)- (zip (inputParametersDescriptor externalInfo)- (Precompiler.originalParameterNames $ originalFunctionSignature externalInfo))- else- precompilationError InternalError "numArgs should be equal to the length of the input parameters' descriptor"--instance Plugin Precompilation where- type ExternalInfo Precompilation = PrecompilationExternalInfo- executePlugin Precompilation externalInfo procedure = result- $ transform Precompilation ({-state-}) SignatureInformation{- originalFunctionName = Precompiler.originalFunctionName $ originalFunctionSignature externalInfo,- generatedImperativeParameterNames = precompilationError InternalError "GIPN should have been overwritten", - originalParameterNames = case compilationMode externalInfo of- Standalone ->- if -- ultimate check, should be enough...- numberOfFunctionArguments externalInfo ==- length (Precompiler.originalParameterNames $ originalFunctionSignature externalInfo)- then- Just $ parameterNameListConsolidator externalInfo- else- unsafePerformIO $ do- withColor Yellow $ putStrLn $ unwords [ "[WARNING @ PluginArch/Naming]:"- , " not enough named parameters in function "- , Precompiler.originalFunctionName (originalFunctionSignature externalInfo)- ]- withColor Yellow $ putStrLn $ "numArgs: " ++ show (numberOfFunctionArguments externalInfo) ++- ", parameter list: " ++ show (Precompiler.originalParameterNames $- originalFunctionSignature externalInfo) - return $ Just $ parameterNameListConsolidator (externalInfo {- originalFunctionSignature = (originalFunctionSignature externalInfo) {- Precompiler.originalParameterNames =- inflate (numberOfFunctionArguments externalInfo) $- Precompiler.originalParameterNames $- originalFunctionSignature externalInfo- }- })- Interactive -> Nothing -- no parameter name handling in interactive mode- } procedure-
− lib/Feldspar/Compiler/Imperative/Plugin/Unroll.hs
@@ -1,285 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE MultiParamTypeClasses #-}--module Feldspar.Compiler.Imperative.Plugin.Unroll where--import Feldspar.Compiler.Backend.C.Options-import Feldspar.Transformation---- ============================--- == Unroll's Semantic info ==--- ============================--data SemInfPrg = SemInfPrg- { position :: Int- , varNames :: [String]- , loopVar :: String- } deriving (Eq, Show)--data UnrollSemInf--instance Annotation UnrollSemInf Module where- type Label UnrollSemInf Module = ()--instance Annotation UnrollSemInf Entity where- type Label UnrollSemInf Entity = ()--instance Annotation UnrollSemInf Struct where- type Label UnrollSemInf Struct = ()--instance Annotation UnrollSemInf StructMember where- type Label UnrollSemInf StructMember = ()--instance Annotation UnrollSemInf ProcDef where- type Label UnrollSemInf ProcDef = ()--instance Annotation UnrollSemInf ProcDecl where- type Label UnrollSemInf ProcDecl = ()--instance Annotation UnrollSemInf Block where- type Label UnrollSemInf Block = ()--instance Annotation UnrollSemInf Program where- type Label UnrollSemInf Program = Maybe SemInfPrg--instance Annotation UnrollSemInf Empty where- type Label UnrollSemInf Empty = ()--instance Annotation UnrollSemInf Comment where- type Label UnrollSemInf Comment = ()--instance Annotation UnrollSemInf Assign where- type Label UnrollSemInf Assign = ()--instance Annotation UnrollSemInf ProcedureCall where- type Label UnrollSemInf ProcedureCall = ()--instance Annotation UnrollSemInf Spawn where- type Label UnrollSemInf Spawn = ()--instance Annotation UnrollSemInf Run where- type Label UnrollSemInf Run = ()--instance Annotation UnrollSemInf Sequence where- type Label UnrollSemInf Sequence = ()--instance Annotation UnrollSemInf Branch where- type Label UnrollSemInf Branch = ()--instance Annotation UnrollSemInf SeqLoop where- type Label UnrollSemInf SeqLoop = ()--instance Annotation UnrollSemInf ParLoop where- type Label UnrollSemInf ParLoop = ()--instance Annotation UnrollSemInf ActualParameter where- type Label UnrollSemInf ActualParameter = ()--instance Annotation UnrollSemInf Declaration where- type Label UnrollSemInf Declaration = ()--instance Annotation UnrollSemInf Expression where- type Label UnrollSemInf Expression = ()--instance Annotation UnrollSemInf FunctionCall where- type Label UnrollSemInf FunctionCall = ()--instance Annotation UnrollSemInf Cast where- type Label UnrollSemInf Cast = ()--instance Annotation UnrollSemInf SizeOf where- type Label UnrollSemInf SizeOf = ()--instance Annotation UnrollSemInf ArrayElem where- type Label UnrollSemInf ArrayElem = ()--instance Annotation UnrollSemInf StructField where- type Label UnrollSemInf StructField = ()--instance Annotation UnrollSemInf Constant where- type Label UnrollSemInf Constant = ()--instance Annotation UnrollSemInf IntConst where- type Label UnrollSemInf IntConst = ()--instance Annotation UnrollSemInf FloatConst where- type Label UnrollSemInf FloatConst = ()--instance Annotation UnrollSemInf BoolConst where- type Label UnrollSemInf BoolConst = ()--instance Annotation UnrollSemInf ArrayConst where- type Label UnrollSemInf ArrayConst = ()--instance Annotation UnrollSemInf ComplexConst where- type Label UnrollSemInf ComplexConst = ()--instance Annotation UnrollSemInf Variable where- type Label UnrollSemInf Variable = ()---- ==--- == Plugin--- ==--instance Default Bool where- def = False--instance Combine Bool where- combine = (||)--instance Default (Maybe SemInfPrg) where def = Nothing ---instance Plugin UnrollPlugin where- type ExternalInfo UnrollPlugin = UnrollStrategy- executePlugin UnrollPlugin ei p = case ei of- NoUnroll -> p- Unroll unrollCount -> result $ transform Unroll2 () Nothing $ result $ transform Unroll1 () unrollCount p- -data UnrollPlugin = UnrollPlugin-instance Transformation UnrollPlugin where- type From UnrollPlugin = ()- type To UnrollPlugin = ()- type Down UnrollPlugin = ()- type Up UnrollPlugin = ()- type State UnrollPlugin = ()--data Unroll1 = Unroll1-instance Transformation Unroll1 where- type From Unroll1 = ()- type To Unroll1 = UnrollSemInf- type Down Unroll1 = Int- type Up Unroll1 = Bool- type State Unroll1 = ()--instance Transformable Unroll1 Program where- transform t s d p@ParLoop{}- | not (up tr)- , unrollPossible = tr'- | otherwise = tr- where- tr = defaultTransform t s d p- tr' = tr - { result = (result tr)- { pLoopStep = d- , pLoopBlock = loopCore- { locals = unrollDecls- , blockBody = Sequence prgs () Nothing- }- }- , up = True- }- prgs = map (\(i,prg) -> prg{ programLabel = Just (SemInfPrg i vns loopCounter) }) $ zip [0,1..] replPrg- replPrg = replicate d $ blockBody loopCore- unrollDecls = concatMap (uncurry renameDecls) $ zip [0..] replDecls- renameDecls (i :: Int) = map (\decl -> renameDeclaration decl (getVarNameDecl decl ++ "_u" ++ show i))- replDecls = replicate d $ locals loopCore- loopCore = pLoopBlock $ result tr - loopBound = pLoopBound $ result tr- loopCounter = varName $ pLoopCounter $ result tr- vns = map getVarNameDecl $ locals loopCore- unrollPossible = case loopBound of- (ConstExpr (IntConst i _ _ _) _) -> mod i (toInteger d) == 0- _ -> False- transform t s d p = defaultTransform t s d p---data Unroll2 = Unroll2 -instance Transformation Unroll2 where- type From Unroll2 = UnrollSemInf- type To Unroll2 = ()- type Down Unroll2 = Maybe SemInfPrg- type Up Unroll2 = ()- type State Unroll2 = ()--instance Transformable Unroll2 Program where- transform t s d p = defaultTransform t s d' p where- d' = case programLabel p of- Nothing -> d- x -> x --instance Transformable Unroll2 Expression where- transform t s d l = case d of- Nothing -> tr- Just x -> case l of- VarExpr n _- | varName n == loopVar x -> tr - { result = FunctionCall - { function = Function- { funName = "+"- , returnType = NumType Signed S32- , funMode = Infix- }- , funCallParams = - [ result tr- , ConstExpr (IntConst (toInteger $ position x) (NumType Signed S32) () ()) ()- ]- , funCallLabel = ()- , exprLabel = ()- }- }- | otherwise -> tr- _ -> tr- where- tr = defaultTransform t s d l---instance Transformable Unroll2 Variable where- transform t s d v = case d of- Just x- | varName v `elem` varNames x -> tr- { result = (result tr)- { varName = varName v ++ "_u" ++ show (position x)- , varLabel = ()- }- }- | otherwise -> tr- Nothing -> tr- where- tr = defaultTransform t s d v----- helper functions : -isJust :: Maybe t -> Bool-isJust (Just _) = True-isJust _ = False--getVarNameDecl :: Declaration t -> String-getVarNameDecl d = varName $ declVar d--renameDeclaration :: Declaration t -> String -> Declaration t-renameDeclaration d n = d { declVar = renameVariable (declVar d) n }--renameVariable :: Variable t -> String -> Variable t-renameVariable v n = v { varName = n }-
lib/Feldspar/Compiler/Imperative/Representation.hs view
@@ -28,11 +28,9 @@ {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE KindSignatures #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverlappingInstances #-}@@ -41,19 +39,14 @@ module Feldspar.Compiler.Imperative.Representation where import Data.Typeable-import qualified Data.List as List (find)+import Data.List (nub)+import Data.Maybe (fromMaybe)+import Data.Monoid import Feldspar.Compiler.Error --- ===============================================================================================--- == Class defining semantic information attached to different nodes in the imperative program ==--- ===============================================================================================--class Annotation t (s :: * -> *) where- type Label t s--instance Annotation () s where- type Label () s = ()+import Feldspar.Range+import Feldspar.Core.Types (Length) -- ================================================= -- == Data stuctures to store imperative programs ==@@ -61,255 +54,192 @@ data Module t = Module { entities :: [Entity t]- , moduleLabel :: Label t Module }- deriving Typeable--deriving instance (ShowLabel t) => Show (Module t)-deriving instance (EqLabel t) => Eq (Module t)+ deriving (Typeable, Show, Eq) data Entity t = StructDef { structName :: String , structMembers :: [StructMember t]- , structLabel :: Label t Struct- , definitionLabel :: Label t Entity } | TypeDef { actualType :: Type , typeName :: String- , definitionLabel :: Label t Entity }- | ProcDef+ | Proc { procName :: String , inParams :: [Variable t] , outParams :: [Variable t]- , procBody :: Block t- , procDefLabel :: Label t ProcDef- , definitionLabel :: Label t Entity+ , procBody :: Maybe (Block t) }- | ProcDecl- { procName :: String- , inParams :: [Variable t]- , outParams :: [Variable t]- , procDeclLabel :: Label t ProcDecl- , definitionLabel :: Label t Entity+ | ValueDef+ { valVar :: Variable t+ , valValue :: Constant t }- deriving Typeable--deriving instance (ShowLabel t) => Show (Entity t)-deriving instance (EqLabel t) => Eq (Entity t) + deriving (Typeable, Show, Eq) data StructMember t = StructMember { structMemberName :: String , structMemberType :: Type- , structMemberLabel :: Label t StructMember }- deriving Typeable--deriving instance (ShowLabel t) => Show (StructMember t)-deriving instance (EqLabel t) => Eq (StructMember t)+ deriving (Typeable, Show, Eq) data Block t = Block { locals :: [Declaration t] , blockBody :: Program t- , blockLabel :: Label t Block }- deriving Typeable--deriving instance (ShowLabel t) => Show (Block t)-deriving instance (EqLabel t) => Eq (Block t)+ deriving (Typeable, Show, Eq) data Program t = Empty- { emptyLabel :: Label t Empty- , programLabel :: Label t Program+ { } | Comment { isBlockComment :: Bool , commentValue :: String- , commentLabel :: Label t Comment- , programLabel :: Label t Program } | Assign { lhs :: Expression t , rhs :: Expression t- , assignLabel :: Label t Assign- , programLabel :: Label t Program } | ProcedureCall { procCallName :: String , procCallParams :: [ActualParameter t]- , procCallLabel :: Label t ProcedureCall- , programLabel :: Label t Program } | Sequence { sequenceProgs :: [Program t]- , sequenceLabel :: Label t Sequence- , programLabel :: Label t Program }- | Branch- { branchCond :: Expression t- , thenBlock :: Block t- , elseBlock :: Block t- , branchLabel :: Label t Branch- , programLabel :: Label t Program+ | Switch+ { scrutinee :: Expression t+ , alts :: [(Pattern t, Block t)] } | SeqLoop { sLoopCond :: Expression t , sLoopCondCalc :: Block t , sLoopBlock :: Block t- , sLoopLabel :: Label t SeqLoop- , programLabel :: Label t Program } | ParLoop- { pLoopCounter :: Variable t+ { pParallel :: Bool+ , pLoopCounter :: Variable t , pLoopBound :: Expression t- , pLoopStep :: Int+ , pLoopStep :: Expression t , pLoopBlock :: Block t- , pLoopLabel :: Label t ParLoop- , programLabel :: Label t Program } | BlockProgram { blockProgram :: Block t- , programLabel :: Label t Program }- deriving Typeable+ deriving (Typeable, Show, Eq) -deriving instance (ShowLabel t) => Show (Program t)-deriving instance (EqLabel t) => Eq (Program t)+data Pattern t+ = PatDefault+ | Pat (Expression t)+ deriving (Typeable, Show, Eq) data ActualParameter t- = In- { inParam :: Expression t- , actParamLabel :: Label t ActualParameter- }- | Out- { outParam :: Expression t- , actParamLabel :: Label t ActualParameter+ = ValueParameter+ { valueParam :: Expression t } | TypeParameter { typeParam :: Type- , typeParamMode :: TypeParameterMode- , actParamLabel :: Label t ActualParameter } | FunParameter { funParamName :: String- , addressNeeded :: Bool- , actParamLabel :: Label t ActualParameter }- deriving Typeable--deriving instance (ShowLabel t) => Show (ActualParameter t)-deriving instance (EqLabel t) => Eq (ActualParameter t)+ deriving (Typeable, Show, Eq) data Declaration t = Declaration { declVar :: Variable t , initVal :: Maybe (Expression t)- , declLabel :: Label t Declaration }- deriving Typeable--deriving instance (ShowLabel t) => Show (Declaration t)-deriving instance (EqLabel t) => Eq (Declaration t)+ deriving (Typeable, Show, Eq) data Expression t = VarExpr- { var :: Variable t- , exprLabel :: Label t Expression+ { varExpr :: Variable t } | ArrayElem { array :: Expression t , arrayIndex :: Expression t- , arrayLabel :: Label t ArrayElem- , exprLabel :: Label t Expression } | StructField { struct :: Expression t , fieldName :: String- , structFieldLabel :: Label t StructField- , exprLabel :: Label t Expression } | ConstExpr { constExpr :: Constant t- , exprLabel :: Label t Expression } | FunctionCall { function :: Function , funCallParams :: [Expression t]- , funCallLabel :: Label t FunctionCall- , exprLabel :: Label t Expression } | Cast { castType :: Type , castExpr :: Expression t- , castLabel :: Label t Cast- , exprLabel :: Label t Expression }+ | AddrOf+ { addrExpr :: Expression t+ } | SizeOf- { sizeOf :: Either Type (Expression t)- , sizeOfLabel :: Label t SizeOf- , exprLabel :: Label t Expression+ { sizeOf :: Type }- deriving Typeable--deriving instance (ShowLabel t) => Show (Expression t)-deriving instance (EqLabel t) => Eq (Expression t)+ deriving (Typeable, Show, Eq) -data Function = Function {- funName :: String- , returnType :: Type- , funMode :: FunctionMode-} deriving (Eq, Show)+data Function+ = Function+ { funName :: String+ , returnType :: Type+ , funMode :: FunctionMode+ }+ deriving (Typeable, Show, Eq) data Constant t = IntConst { intValue :: Integer , intType :: Type- , intConstLabel :: Label t IntConst- , constLabel :: Label t Constant }+ | DoubleConst+ { doubleValue :: Double+ } | FloatConst- { floatValue :: Double- , floatConstLabel :: Label t FloatConst- , constLabel :: Label t Constant+ { floatValue :: Float } | BoolConst { boolValue :: Bool- , boolConstLabel :: Label t BoolConst- , constLabel :: Label t Constant } | ComplexConst- { realPartComplexValue :: Constant t- , imagPartComplexValue :: Constant t- , complexConstLabel :: Label t ComplexConst- , constLabel :: Label t Constant+ { realPartComplexValue :: Constant t+ , imagPartComplexValue :: Constant t }- deriving Typeable+ | ArrayConst+ { arrayValues :: [Constant t]+ }+ deriving (Typeable, Show, Eq) -deriving instance (ShowLabel t) => Show (Constant t)-deriving instance (EqLabel t) => Eq (Constant t)+data Variable t+ = Variable+ { varType :: Type+ , varName :: String+ }+ deriving (Typeable, Show, Eq) -data Variable t = Variable- { varName :: String- , varType :: Type- , varRole :: VariableRole- , varLabel :: Label t Variable- }- deriving Typeable+instance Monoid (Program t)+ where+ mempty = Empty+ mappend Empty p = p+ mappend p Empty = p+ mappend (Sequence pa) (Sequence pb) = Sequence (mappend pa pb)+ mappend pa pb = Sequence [mappend pa pb] -deriving instance (ShowLabel t) => Show (Variable t)-deriving instance (EqLabel t) => Eq (Variable t)+instance Monoid (Block t)+ where+ mempty = Block [] Empty+ mappend (Block da pa) (Block db pb) = Block (mappend da db) (mappend pa pb) + -- ====================== -- == Basic structures == -- ====================== -data Length =- LiteralLen Int- | UndefinedLen- deriving (Eq,Show)- data Size = S8 | S16 | S32 | S40 | S64 deriving (Eq,Show) @@ -321,32 +251,21 @@ | BoolType | BitType | FloatType+ | DoubleType | NumType Signedness Size | ComplexType Type | UserType String | Alias Type String- | ArrayType Length Type- | StructType [(String, Type)]+ | ArrayType (Range Length) Type+ | NativeArray (Maybe Length) Type+ | StructType String [(String, Type)]+ | Pointer Type | IVarType Type deriving (Eq,Show) data FunctionMode = Prefix | Infix deriving (Eq,Show) -data VariableRole = Value | Pointer- deriving (Eq,Show)--data Place- = Declaration_pl- | MainParameter_pl- | ValueNeed_pl- | AddressNeed_pl- | FunctionCallIn_pl- deriving (Eq,Show)--data TypeParameterMode = Auto | Scalar- deriving (Eq,Show)- ---------------------- -- Type inference -- ----------------------@@ -359,40 +278,44 @@ type TypeOf (Variable t) = Type typeof Variable{..} = varType -instance (ShowLabel t) => HasType (Constant t) where+instance HasType (Constant t) where type TypeOf (Constant t) = Type typeof IntConst{..} = intType+ typeof DoubleConst{} = DoubleType typeof FloatConst{} = FloatType typeof BoolConst{} = BoolType+ typeof ArrayConst{..} = NativeArray (Just (fromIntegral $ length arrayValues)) t+ where t = typeof $ head arrayValues typeof ComplexConst{..} = ComplexType $ typeof realPartComplexValue -instance (ShowLabel t) => HasType (Expression t) where+instance HasType (Expression t) where type TypeOf (Expression t) = Type- typeof VarExpr{..} = typeof var+ typeof VarExpr{..} = typeof varExpr typeof ArrayElem{..} = decrArrayDepth $ typeof array where decrArrayDepth :: Type -> Type- decrArrayDepth (ArrayType _ t) = t- decrArrayDepth t = reprError InternalError $ "Non-array variable is indexed! " ++ show array ++ " :: " ++ show t+ decrArrayDepth (ArrayType _ t) = t+ decrArrayDepth (NativeArray _ t) = t+ decrArrayDepth (Pointer t) = decrArrayDepth t+ decrArrayDepth t = reprError InternalError $ "Non-array variable is indexed! " ++ show array ++ " :: " ++ show t typeof StructField{..} = getStructFieldType fieldName $ typeof struct where getStructFieldType :: String -> Type -> Type- getStructFieldType f (StructType l) = case List.find (\(a,_) -> a == f) l of- Just (_,t) -> t- Nothing -> structFieldNotFound f+ getStructFieldType f (StructType _ l) = fromMaybe (structFieldNotFound f) $ lookup f l getStructFieldType f (Alias t _) = getStructFieldType f t+ getStructFieldType f (Pointer t) = getStructFieldType f t getStructFieldType f t = reprError InternalError $ "Trying to get a struct field from not a struct typed expression\n" ++ "Field: " ++ f ++ "\nType: " ++ show t structFieldNotFound f = reprError InternalError $ "Not found struct field with this name: " ++ f typeof ConstExpr{..} = typeof constExpr typeof FunctionCall{..} = returnType function typeof Cast{..} = castType+ typeof AddrOf{..} = Pointer $ typeof addrExpr typeof SizeOf{..} = NumType Signed S32 -instance (ShowLabel t) => HasType (ActualParameter t) where+instance HasType (ActualParameter t) where type TypeOf (ActualParameter t) = Type- typeof In{..} = typeof inParam- typeof Out{..} = typeof outParam+ typeof ValueParameter{..}= typeof valueParam typeof TypeParameter{..} = typeParam typeof FunParameter{} = VoidType @@ -400,221 +323,16 @@ reprError :: forall a. ErrorClass -> String -> a reprError = handleError "Feldspar.Compiler.Imperative.Representation" --- =====================--- == Technical types ==--- =====================--data Struct t-data ProcDef t-data ProcDecl t-data Empty t-data Comment t-data Assign t-data ProcedureCall t-data Spawn t-data Run t-data Sequence t-data Branch t-data SeqLoop t-data ParLoop t-data FunctionCall t-data Cast t-data SizeOf t-data ArrayElem t-data StructField t-data LeftFunCall t-data IntConst t-data FloatConst t-data BoolConst t-data ArrayConst t-data ComplexConst t---- ==========================--- == Show and Eq instance ==--- ==========================--class ( Show (Label t Module)- , Show (Label t Entity)- , Show (Label t Struct)- , Show (Label t ProcDef)- , Show (Label t ProcDecl)- , Show (Label t StructMember)- , Show (Label t Block)- , Show (Label t Program)- , Show (Label t Empty)- , Show (Label t Comment)- , Show (Label t Assign)- , Show (Label t ProcedureCall)- , Show (Label t Spawn)- , Show (Label t Run)- , Show (Label t Sequence)- , Show (Label t Branch)- , Show (Label t SeqLoop)- , Show (Label t ParLoop)- , Show (Label t ActualParameter)- , Show (Label t Declaration)- , Show (Label t Expression)- , Show (Label t FunctionCall)- , Show (Label t Cast)- , Show (Label t SizeOf)- , Show (Label t ArrayElem)- , Show (Label t StructField)- , Show (Label t Constant)- , Show (Label t IntConst)- , Show (Label t FloatConst)- , Show (Label t BoolConst)- , Show (Label t ArrayConst)- , Show (Label t ComplexConst)- , Show (Label t Variable)- ) => ShowLabel t--instance ( Show (Label t Module)- , Show (Label t Entity)- , Show (Label t Struct)- , Show (Label t ProcDef)- , Show (Label t ProcDecl)- , Show (Label t StructMember)- , Show (Label t Block)- , Show (Label t Program)- , Show (Label t Empty)- , Show (Label t Comment)- , Show (Label t Assign)- , Show (Label t ProcedureCall)- , Show (Label t Spawn)- , Show (Label t Run)- , Show (Label t Sequence)- , Show (Label t Branch)- , Show (Label t SeqLoop)- , Show (Label t ParLoop)- , Show (Label t ActualParameter)- , Show (Label t Declaration)- , Show (Label t Expression)- , Show (Label t FunctionCall)- , Show (Label t Cast)- , Show (Label t SizeOf)- , Show (Label t ArrayElem)- , Show (Label t StructField)- , Show (Label t Constant)- , Show (Label t IntConst)- , Show (Label t FloatConst)- , Show (Label t BoolConst)- , Show (Label t ArrayConst)- , Show (Label t ComplexConst)- , Show (Label t Variable)- ) => ShowLabel t--class ( Eq (Label t Module)- , Eq (Label t Entity)- , Eq (Label t Struct)- , Eq (Label t ProcDef)- , Eq (Label t ProcDecl)- , Eq (Label t StructMember)- , Eq (Label t Block)- , Eq (Label t Program)- , Eq (Label t Empty)- , Eq (Label t Comment)- , Eq (Label t Assign)- , Eq (Label t ProcedureCall)- , Eq (Label t Spawn)- , Eq (Label t Run)- , Eq (Label t Sequence)- , Eq (Label t Branch)- , Eq (Label t SeqLoop)- , Eq (Label t ParLoop)- , Eq (Label t ActualParameter)- , Eq (Label t Declaration)- , Eq (Label t Expression)- , Eq (Label t FunctionCall)- , Eq (Label t Cast)- , Eq (Label t SizeOf)- , Eq (Label t StructField)- , Eq (Label t ArrayElem)- , Eq (Label t Constant)- , Eq (Label t IntConst)- , Eq (Label t FloatConst)- , Eq (Label t BoolConst)- , Eq (Label t ArrayConst)- , Eq (Label t ComplexConst)- , Eq (Label t Variable)- ) => EqLabel t--instance ( Eq (Label t Module)- , Eq (Label t Entity)- , Eq (Label t Struct)- , Eq (Label t ProcDef)- , Eq (Label t ProcDecl)- , Eq (Label t StructMember)- , Eq (Label t Block)- , Eq (Label t Program)- , Eq (Label t Empty)- , Eq (Label t Comment)- , Eq (Label t Assign)- , Eq (Label t ProcedureCall)- , Eq (Label t Spawn)- , Eq (Label t Run)- , Eq (Label t Sequence)- , Eq (Label t Branch)- , Eq (Label t SeqLoop)- , Eq (Label t ParLoop)- , Eq (Label t ActualParameter)- , Eq (Label t Declaration)- , Eq (Label t Expression)- , Eq (Label t FunctionCall)- , Eq (Label t Cast)- , Eq (Label t SizeOf)- , Eq (Label t StructField)- , Eq (Label t ArrayElem)- , Eq (Label t Constant)- , Eq (Label t IntConst)- , Eq (Label t FloatConst)- , Eq (Label t BoolConst)- , Eq (Label t ArrayConst)- , Eq (Label t ComplexConst)- , Eq (Label t Variable)- ) => EqLabel t---- * Set and get labels--class Labeled c where- label :: c t -> Label t c- setLabel :: c t -> Label t c -> c t--instance Labeled Module where- label = moduleLabel- setLabel c lab = c{ moduleLabel = lab }--instance Labeled Entity where- label = definitionLabel- setLabel c lab = c{ definitionLabel = lab }--instance Labeled Program where- label = programLabel- setLabel c lab = c{ programLabel = lab }--instance Labeled Declaration where- label = declLabel- setLabel c lab = c{ declLabel = lab }--instance Labeled Constant where- label = constLabel- setLabel c lab = c{ constLabel = lab }--instance Labeled StructMember where- label = structMemberLabel- setLabel c lab = c{ structMemberLabel = lab }--instance Labeled Variable where- label = varLabel- setLabel c lab = c{ varLabel = lab }--instance Labeled Expression where- label = exprLabel- setLabel c lab = c{ exprLabel = lab }+-- | Free variables of an expression.+fv :: Expression t -> [Variable t]+fv = nub . fv' -instance Labeled ActualParameter where- label = actParamLabel- setLabel c lab = c{ actParamLabel = lab }+fv' :: Expression t -> [Variable t]+fv' (VarExpr v) = [v]+fv' (ArrayElem e i) = fv' e ++ fv' i+fv' (StructField e _) = fv' e+fv' (FunctionCall _ ps) = concatMap fv' ps+fv' (Cast _ e) = fv' e+fv' (AddrOf e) = fv' e+fv' _ = [] -instance Labeled Block where- label = blockLabel- setLabel c lab = c{ blockLabel = lab }
lib/Feldspar/Compiler/Imperative/TransformationInstance.hs view
@@ -1,11 +1,11 @@ -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved.--- +-- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, +--+-- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the@@ -13,10 +13,10 @@ -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission.--- +-- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR@@ -35,7 +35,7 @@ module Feldspar.Compiler.Imperative.TransformationInstance where -+import Control.Arrow ((***)) import Feldspar.Transformation.Framework import Feldspar.Compiler.Imperative.Representation @@ -43,125 +43,130 @@ -- == Classes for the plugin architecture == -- ========================================= --- class to simplify contexts-class (Transformation t, Convert (Label (From t) s) (Label (To t) s), Default (Label (To t) s)) => Conversion t s--instance (Transformation t, Convert (Label (From t) s) (Label (To t) s), Default (Label (To t) s)) => Conversion t s- -- ==================== -- == Transformation == -- ==================== -instance (Transformable1 t [] Entity, Conversion t Module)+instance (Transformable1 t [] Entity) => DefaultTransformable t Module where- defaultTransform t s d (Module m inf) = Result (Module (result1 tr) $ convert inf) (state1 tr) (up1 tr) where+ defaultTransform t s d (Module m) = Result (Module (result1 tr)) (state1 tr) (up1 tr) where tr = transform1 t s d m -instance (Transformable1 t [] StructMember, Transformable1 t [] Variable, Transformable t Block, Transformable t Declaration, Conversion t Entity, Conversion t Struct, Conversion t ProcDef, Conversion t ProcDecl)+instance (Transformable1 t [] StructMember, Transformable1 t [] Variable, Transformable t Block, Transformable t Declaration, Transformable t Constant, Combine (Up t), Default (Up t), Transformation t) => DefaultTransformable t Entity where- defaultTransform t s d (StructDef n m inf1 inf2) =- Result (StructDef n (result1 tr) (convert inf1) $ convert inf2) (state1 tr) (up1 tr) where+ defaultTransform t s d (StructDef n m) =+ Result (StructDef n (result1 tr)) (state1 tr) (up1 tr) where tr = transform1 t s d m- defaultTransform _ s _ (TypeDef typ n inf) =- Result (TypeDef typ n (convert inf)) s def- defaultTransform t s d (ProcDef n i o p inf1 inf2) =- Result (ProcDef n (result1 tr1) (result1 tr2) (result tr3) (convert inf1) $ convert inf2)- (state tr3) (foldl combine (up1 tr1) [up1 tr2, up tr3]) where+ defaultTransform _ s _ (TypeDef typ n) =+ Result (TypeDef typ n) s def+ defaultTransform t s d (Proc n i o p) =+ Result (Proc n (result1 tr1) (result1 tr2) (result1 tr3))+ (state1 tr3) (foldl combine (up1 tr1) [up1 tr2, up1 tr3]) where tr1 = transform1 t s d i tr2 = transform1 t (state1 tr1) d o- tr3 = transform t (state1 tr2) d p- defaultTransform t s d (ProcDecl name inp outp inf1 inf2) =- Result (ProcDecl name (result1 tr1) (result1 tr2) (convert inf1) (convert inf2))- (state1 tr2) (foldl1 combine [up1 tr1, up1 tr2]) where- tr1 = transform1 t s d inp- tr2 = transform1 t (state1 tr1) d outp+ tr3 = transform1 t (state1 tr2) d p+ defaultTransform t s d (ValueDef var val) =+ Result (ValueDef (result tr1) (result tr2)) (state tr2) (combine (up tr1) (up tr2)) where+ tr1 = transform t s d var+ tr2 = transform t (state tr1) d val -instance (Conversion t StructMember, Default (Up t))+instance (Default (Up t)) => DefaultTransformable t StructMember where- defaultTransform _ s _ (StructMember n typ inf) = Result (StructMember n typ $ convert inf) s def+ defaultTransform _ s _ (StructMember n typ) = Result (StructMember n typ) s def -instance (Transformable1 t [] Declaration, Transformable t Program, Conversion t Block)+instance (Transformable1 t [] Declaration, Transformable t Program, Combine (Up t)) => DefaultTransformable t Block where- defaultTransform t s d (Block l b inf) = Result (Block (result1 tr1) (result tr2) $ convert inf) (state tr2) (combine (up1 tr1) (up tr2)) where+ defaultTransform t s d (Block l b) = Result (Block (result1 tr1) (result tr2)) (state tr2) (combine (up1 tr1) (up tr2)) where tr1 = transform1 t s d l tr2 = transform t (state1 tr1) d b -instance (Transformable1 t [] Program, Transformable t Expression, Transformable1 t [] ActualParameter, Transformable t Block, Transformable t Variable, Conversion t Program, Conversion t Empty, Conversion t Comment, Conversion t Assign, Conversion t ProcedureCall, Conversion t Spawn, Conversion t Run, Conversion t Sequence, Conversion t Branch, Conversion t SeqLoop, Conversion t ParLoop, Default (Up t))+instance (Transformable1 t [] Program, Transformable t Expression, Transformable1 t [] ActualParameter, Transformable t Block, Transformable t Variable, Combine (Up t), Default (Up t), Transformation t) => DefaultTransformable t Program where- defaultTransform _ s _ (Empty inf1 inf2) = Result (Empty (convert inf1) $ convert inf2) s def- defaultTransform _ s _ (Comment b c inf1 inf2) = Result (Comment b c (convert inf1) $ convert inf2) s def- defaultTransform t s d (Assign l r inf1 inf2) = Result (Assign (result tr1) (result tr2) (convert inf1) $ convert inf2) (state tr2) (combine (up tr1) (up tr2)) where+ defaultTransform _ s _ Empty = Result Empty s def+ defaultTransform _ s _ (Comment b c) = Result (Comment b c) s def+ defaultTransform t s d (Assign l r) = Result (Assign (result tr1) (result tr2)) (state tr2) (combine (up tr1) (up tr2)) where tr1 = transform t s d l tr2 = transform t (state tr1) d r- defaultTransform t s d (ProcedureCall f par inf1 inf2) = Result (ProcedureCall f (result1 tr) (convert inf1) $ convert inf2) (state1 tr) (up1 tr) where+ defaultTransform t s d (ProcedureCall f par) = Result (ProcedureCall f (result1 tr)) (state1 tr) (up1 tr) where tr = transform1 t s d par- defaultTransform t s d (Sequence p inf1 inf2) = Result (Sequence (result1 tr) (convert inf1) $ convert inf2) (state1 tr) (up1 tr) where+ defaultTransform t s d (Sequence p) = Result (Sequence (result1 tr)) (state1 tr) (up1 tr) where tr = transform1 t s d p- defaultTransform t s d (Branch e p1 p2 inf1 inf2) = Result (Branch (result tr1) (result tr2) (result tr3) (convert inf1) $ convert inf2) (state tr3) (foldl combine (up tr1) [up tr2, up tr3]) where- tr1 = transform t s d e- tr2 = transform t (state tr1) d p1- tr3 = transform t (state tr2) d p2- defaultTransform t s d (SeqLoop v c p inf1 inf2) = Result (SeqLoop (result tr1) (result tr2) (result tr3) (convert inf1) $ convert inf2) (state tr3) (foldl combine (up tr1) [up tr2, up tr3]) where+ defaultTransform t s d (Switch scrut (alt:alts)) = Result (Switch (result tr1) ralts) lstate (foldl combine (up tr1) (map (up . snd) alts')) where+ tr1 = transform t s d scrut+ alts' = go (transformPattern (state tr1) alt) [] alts+ lstate = state . snd . last $ alts'+ ralts = map (result *** result) alts'+ go prevAlt acc [] = reverse (prevAlt:acc)+ go (p2, prev) acc (h:t') = go (transformPattern (state prev) h) ((p2,prev):acc) t'+ transformPattern st (p, e) = (pat', transform t (state pat') d e)+ where pat' = transform t st d p++ defaultTransform t s d (SeqLoop v c p) = Result (SeqLoop (result tr1) (result tr2) (result tr3)) (state tr3) (foldl combine (up tr1) [up tr2, up tr3]) where tr1 = transform t s d v tr2 = transform t (state tr1) d c tr3 = transform t (state tr2) d p- defaultTransform t s d (ParLoop v b i p inf1 inf2) = Result (ParLoop (result tr1) (result tr2) i (result tr3) (convert inf1) $ convert inf2) (state tr3) (foldl combine (up tr1) [up tr2, up tr3]) where+ defaultTransform t s d (ParLoop pp v b i p) = Result (ParLoop pp (result tr1) (result tr2) (result tr3) (result tr4)) (state tr4) (foldl combine (up tr1) [up tr2, up tr3, up tr4]) where tr1 = transform t s d v tr2 = transform t (state tr1) d b- tr3 = transform t (state tr2) d p- defaultTransform t s d (BlockProgram b inf) = Result (BlockProgram (result tr) $ convert inf) (state tr) (up tr) where+ tr3 = transform t (state tr2) d i+ tr4 = transform t (state tr3) d p+ defaultTransform t s d (BlockProgram b) = Result (BlockProgram (result tr)) (state tr) (up tr) where tr = transform t s d b -instance (Transformable t Expression, Conversion t ActualParameter)+instance (Transformable t Constant, Transformable t Expression, Transformable1 t [] ActualParameter, Transformable t Block, Transformable t Variable, Combine (Up t), Default (Up t))+ => DefaultTransformable t Pattern where+ defaultTransform _ s _ PatDefault = Result PatDefault s def+ defaultTransform t s d (Pat p) = Result (Pat (result tr1)) (state tr1) (up tr1) where+ tr1 = transform t s d p++instance (Transformable t Expression, Default (Up t)) => DefaultTransformable t ActualParameter where- defaultTransform t s d (In p inf) = Result (In (result tr) $ convert inf) (state tr) (up tr) where- tr = transform t s d p- defaultTransform t s d (Out p inf) = Result (Out (result tr) $ convert inf) (state tr) (up tr) where+ defaultTransform t s d (ValueParameter p) = Result (ValueParameter (result tr)) (state tr) (up tr) where tr = transform t s d p- defaultTransform _ s _ (TypeParameter p r inf) = Result (TypeParameter p r $ convert inf) s def- defaultTransform _ s _ (FunParameter n b inf) = Result (FunParameter n b $ convert inf) s def+ defaultTransform _ s _ (TypeParameter p) = Result (TypeParameter p) s def+ defaultTransform _ s _ (FunParameter n) = Result (FunParameter n) s def -instance (Transformable t Variable, Transformable1 t Maybe Expression, Conversion t Declaration)+instance (Transformable t Variable, Transformable1 t Maybe Expression, Combine (Up t)) => DefaultTransformable t Declaration where- defaultTransform t s d (Declaration v i inf) = Result (Declaration (result tr1) (result1 tr2) $ convert inf) (state1 tr2) (combine (up tr1) (up1 tr2)) where+ defaultTransform t s d (Declaration v i) = Result (Declaration (result tr1) (result1 tr2)) (state1 tr2) (combine (up tr1) (up1 tr2)) where tr1 = transform t s d v tr2 = transform1 t (state tr1) d i -instance (Transformable t Expression, Transformable t Variable, Transformable t Constant, Transformable1 t [] Expression, Conversion t Expression, Conversion t FunctionCall, Conversion t ArrayElem, Conversion t StructField, Conversion t SizeOf, Conversion t Cast, Default (Up t))+instance (Transformable t Expression, Transformable t Variable, Transformable t Constant, Transformable1 t [] Expression, Combine (Up t), Default (Up t)) => DefaultTransformable t Expression where- defaultTransform t s d (VarExpr v inf) = Result (VarExpr (result tr) $ convert inf) (state tr) (up tr) where+ defaultTransform t s d (VarExpr v) = Result (VarExpr (result tr)) (state tr) (up tr) where tr = transform t s d v- defaultTransform t s d (ArrayElem a i inf1 inf2) = Result (ArrayElem (result tr1) (result tr2) (convert inf1) (convert inf2)) (state tr2) (combine (up tr1) (up tr2)) where+ defaultTransform t s d (ArrayElem a i) = Result (ArrayElem (result tr1) (result tr2)) (state tr2) (combine (up tr1) (up tr2)) where tr1 = transform t s d a tr2 = transform t (state tr1) d i- defaultTransform t s d (StructField l n inf1 inf2) = Result (StructField (result tr) n (convert inf1) $ convert inf2) (state tr) (up tr) where+ defaultTransform t s d (StructField l n) = Result (StructField (result tr) n) (state tr) (up tr) where tr = transform t s d l- defaultTransform t s d (ConstExpr c inf) = Result (ConstExpr (result tr) $ convert inf) (state tr) (up tr) where+ defaultTransform t s d (ConstExpr c) = Result (ConstExpr (result tr)) (state tr) (up tr) where tr = transform t s d c- defaultTransform t s d (FunctionCall f par inf1 inf2) =- Result (FunctionCall f (result1 tr) (convert inf1) $ convert inf2) (state1 tr) (up1 tr) where+ defaultTransform t s d (FunctionCall f par) =+ Result (FunctionCall f (result1 tr)) (state1 tr) (up1 tr) where tr = transform1 t s d par- defaultTransform t s d (Cast typ ex inf1 inf2) = Result (Cast typ (result tr) (convert inf1) $ convert inf2) (state tr) (up tr) where+ defaultTransform t s d (Cast typ ex) = Result (Cast typ (result tr)) (state tr) (up tr) where tr = transform t s d ex- defaultTransform t s d (SizeOf par inf1 inf2) = case par of- Left typ -> Result (SizeOf (Left typ) (convert inf1) $ convert inf2) s def- Right ex -> Result (SizeOf (Right $ result tr) (convert inf1) $ convert inf2) (state tr) (up tr) where- tr = transform t s d ex+ defaultTransform t s d (AddrOf ex) = Result (AddrOf (result tr)) (state tr) (up tr) where+ tr = transform t s d ex+ defaultTransform t s d (SizeOf typ) = Result (SizeOf typ) s def -instance (Transformable t Constant, Transformable1 t [] Constant, Conversion t Constant, Conversion t IntConst, Conversion t FloatConst, Conversion t BoolConst, Conversion t ArrayConst, Conversion t ComplexConst, Default (Up t))+instance (Transformable t Constant, Transformable1 t [] Constant, Combine (Up t), Default (Up t)) => DefaultTransformable t Constant where- defaultTransform _ s _ (IntConst c typ inf1 inf2) = Result (IntConst c typ (convert inf1) $ convert inf2) s def- defaultTransform _ s _ (FloatConst c inf1 inf2) = Result (FloatConst c (convert inf1) $ convert inf2) s def- defaultTransform _ s _ (BoolConst c inf1 inf2) = Result (BoolConst c (convert inf1) $ convert inf2) s def- -- defaultTransform t s d (ArrayConst c inf1 inf2) = Result (ArrayConst (result1 tr) (convert inf1) $ convert inf2) (state1 tr) (up1 tr) where- -- tr = transform1 t s d c- defaultTransform t s d (ComplexConst re im inf1 inf2) = Result (ComplexConst (result tr1) (result tr2) (convert inf1) $ convert inf2) (state tr2) (combine (up tr1) $ up tr2) where+ defaultTransform _ s _ (IntConst c typ) = Result (IntConst c typ) s def+ defaultTransform _ s _ (DoubleConst c) = Result (DoubleConst c) s def+ defaultTransform _ s _ (FloatConst c) = Result (FloatConst c) s def+ defaultTransform _ s _ (BoolConst c) = Result (BoolConst c) s def+ defaultTransform t s d (ArrayConst c) = Result (ArrayConst (result1 tr)) (state1 tr) (up1 tr) where+ tr = transform1 t s d c+ defaultTransform t s d (ComplexConst re im) = Result (ComplexConst (result tr1) (result tr2)) (state tr2) (combine (up tr1) $ up tr2) where tr1 = transform t s d re tr2 = transform t (state tr1) d im -instance (Conversion t Variable, Default (Up t))+instance (Default (Up t)) => DefaultTransformable t Variable where- defaultTransform _ s _ (Variable name typ role inf) = Result (Variable name typ role $ convert inf) s def+ defaultTransform _ s _ (Variable name typ) = Result (Variable name typ) s def instance (Transformable t a, Default (Up t), Combine (Up t), Transformation t)
+ lib/Feldspar/Compiler/Internal.hs view
@@ -0,0 +1,46 @@+--+-- Copyright (c) 2009-2011, ERICSSON AB+-- All rights reserved.+--+-- Redistribution and use in source and binary forms, with or without+-- modification, are permitted provided that the following conditions are met:+--+-- * Redistributions of source code must retain the above copyright notice,+-- this list of conditions and the following disclaimer.+-- * Redistributions in binary form must reproduce the above copyright+-- notice, this list of conditions and the following disclaimer in the+-- documentation and/or other materials provided with the distribution.+-- * Neither the name of the ERICSSON AB nor the names of its contributors+-- may be used to endorse or promote products derived from this software+-- without specific prior written permission.+--+-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+--++module Feldspar.Compiler.Internal+ ( defaultOptions+ , c99PlatformOptions+ , c99OpenMpPlatformOptions+ , tic64xPlatformOptions+ , unrollOptions+ , nativeArrayRules+ , noPrimitiveInstructionHandling+ , noMemoryInformation+ , module Internal+ ) where++import Feldspar.Compiler.Compiler+import Feldspar.Compiler.Frontend.Interactive.Interface as Internal+import Feldspar.Compiler.Backend.C.Options as Internal+import Feldspar.Compiler.Imperative.Frontend as Internal hiding (spawn)+import Feldspar.Compiler.Backend.C.Platforms (nativeArrayRules)+
+ lib/Feldspar/Compiler/Marshal.hs view
@@ -0,0 +1,212 @@+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Marshaling between Feldspar and C99 types+--+module Feldspar.Compiler.Marshal+ ( SA(..)+ )+ where++import System.Plugins.MultiStage+import Feldspar.Core.Types (IntN(..), WordN(..))++import Data.Int (Int32)+import Data.Word (Word32)+import Data.Complex (Complex(..),realPart,imagPart)+import Data.Default+import Control.Applicative++import Foreign.Ptr+import Foreign.Marshal (free, new, newArray, peekArray)+import Foreign.Storable (Storable(..))+import Foreign.Storable.Tuple ()+import qualified Foreign.Storable.Record as Store++instance Reference IntN where type Ref IntN = IntN+instance Reference WordN where type Ref WordN = WordN+instance Reference (Complex a) where type Ref (Complex a) = Complex a++instance Marshal IntN where type Rep IntN = IntN+instance Marshal WordN where type Rep WordN = WordN+instance Marshal (Complex a) where type Rep (Complex a) = Complex a++instance Default (Ptr a) where def = nullPtr++instance (Storable (Rep a), Marshal a) => Marshal [a]+ where+ type Rep [a] = Ptr (SA (Rep a))+ to xs = do+ let len = fromIntegral $ length xs+ let size = fromIntegral $ sizeOf (undefined :: Rep a)+ ys <- mapM to xs+ buffer <- newArray ys+ new $ SA buffer len size (fromIntegral (len * size))+ from p = peek p >>= go+ where+ go SA{..} = do+ res <- mapM from =<< peekArray (fromIntegral elems) buf+ free buf+ return res+++-- | Buffer descriptor for Feldspar arrays+data SA a = SA { buf :: Ptr a+ , elems :: Int32+ , esize :: Int32+ , bytes :: Word32+ }+ deriving (Eq, Show)++instance Default (SA a) where+ def = SA nullPtr def def def++storeSA :: Storable a => Store.Dictionary (SA a)+storeSA = Store.run $ SA+ <$> Store.element buf+ <*> Store.element elems+ <*> Store.element esize+ <*> Store.element bytes++instance Storable a => Storable (SA a)+ where+ sizeOf = Store.sizeOf storeSA+ alignment = Store.alignment storeSA+ peek = Store.peek storeSA+ poke = Store.poke storeSA++instance Reference (Ptr a)+ where+ type Ref (Ptr a) = Ptr a+ ref = return+ deref = return++instance (Storable a) => Reference (SA a)+ where+ type Ref (SA a) = Ptr (SA a)+ ref = new+ deref = peek++storeComplex :: (RealFloat a, Storable a)+ => Store.Dictionary (Complex a)+storeComplex = Store.run $ (:+)+ <$> Store.element realPart+ <*> Store.element imagPart++instance (RealFloat a, Storable a) => Storable (Complex a)+ where+ sizeOf = Store.sizeOf storeComplex+ alignment = Store.alignment storeComplex+ peek = Store.peek storeComplex+ poke = Store.poke storeComplex++instance (Storable (a,b)) => Reference (a,b)+ where+ type Ref (a,b) = Ptr (a,b)+ ref = new+ deref = peek++instance (Storable (a,b,c)) => Reference (a,b,c)+ where+ type Ref (a,b,c) = Ptr (a,b,c)+ ref = new+ deref = peek++instance (Storable (a,b,c,d)) => Reference (a,b,c,d)+ where+ type Ref (a,b,c,d) = Ptr (a,b,c,d)+ ref = new+ deref = peek++instance (Storable (a,b,c,d,e)) => Reference (a,b,c,d,e)+ where+ type Ref (a,b,c,d,e) = Ptr (a,b,c,d,e)+ ref = new+ deref = peek++instance (Storable (a,b,c,d,e,f)) => Reference (a,b,c,d,e,f)+ where+ type Ref (a,b,c,d,e,f) = Ptr (a,b,c,d,e,f)+ ref = new+ deref = peek++instance (Storable (a,b,c,d,e,f,g)) => Reference (a,b,c,d,e,f,g)+ where+ type Ref (a,b,c,d,e,f,g) = Ptr (a,b,c,d,e,f,g)+ ref = new+ deref = peek++instance ( Marshal a+ , Marshal b+ ) => Marshal (a,b)+ where+ type Rep (a,b) = (Rep a,Rep b)+ to (a,b) = (,) <$> to a <*> to b+ from (a,b) = (,) <$> from a <*> from b++instance ( Marshal a+ , Marshal b+ , Marshal c+ ) => Marshal (a,b,c)+ where+ type Rep (a,b,c) = (Rep a,Rep b,Rep c)+ to (a,b,c) = (,,) <$> to a <*> to b <*> to c+ from (a,b,c) = (,,) <$> from a <*> from b <*> from c++instance ( Marshal a+ , Marshal b+ , Marshal c+ , Marshal d+ ) => Marshal (a,b,c,d)+ where+ type Rep (a,b,c,d) = (Rep a,Rep b,Rep c,Rep d)+ to (a,b,c,d) =+ (,,,) <$> to a <*> to b <*> to c <*> to d+ from (a,b,c,d) =+ (,,,) <$> from a <*> from b <*> from c <*> from d++instance ( Marshal a+ , Marshal b+ , Marshal c+ , Marshal d+ , Marshal e+ ) => Marshal (a,b,c,d,e)+ where+ type Rep (a,b,c,d,e) = (Rep a,Rep b,Rep c,Rep d,Rep e)+ to (a,b,c,d,e) =+ (,,,,) <$> to a <*> to b <*> to c <*> to d <*> to e+ from (a,b,c,d,e) =+ (,,,,) <$> from a <*> from b <*> from c <*> from d <*> from e++instance ( Marshal a+ , Marshal b+ , Marshal c+ , Marshal d+ , Marshal e+ , Marshal f+ ) => Marshal (a,b,c,d,e,f)+ where+ type Rep (a,b,c,d,e,f) = (Rep a,Rep b,Rep c,Rep d,Rep e,Rep f)+ to (a,b,c,d,e,f) =+ (,,,,,) <$> to a <*> to b <*> to c <*> to d <*> to e <*> to f+ from (a,b,c,d,e,f) =+ (,,,,,) <$> from a <*> from b <*> from c <*> from d <*> from e <*> from f++instance ( Marshal a+ , Marshal b+ , Marshal c+ , Marshal d+ , Marshal e+ , Marshal f+ , Marshal g+ ) => Marshal (a,b,c,d,e,f,g)+ where+ type Rep (a,b,c,d,e,f,g) = (Rep a,Rep b,Rep c,Rep d,Rep e,Rep f,Rep g)+ to (a,b,c,d,e,f,g) =+ (,,,,,,) <$> to a <*> to b <*> to c <*> to d <*> to e <*> to f <*> to g+ from (a,b,c,d,e,f,g) =+ (,,,,,,) <$> from a <*> from b <*> from c <*> from d <*> from e <*> from f <*> from g+
+ lib/Feldspar/Compiler/Plugin.hs view
@@ -0,0 +1,174 @@+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE ForeignFunctionInterface #-}++-- | Dynamically load a compiled Feldspar function as a Haskell function+module Feldspar.Compiler.Plugin+ ( loadFun+ , loadFunOpts+ , loadFunWithConfig+ , defaultConfig+ , pack -- from MultiStage+ , unpack -- from MultiStage+ )+ where++import GHC.Paths (ghc)+import System.Plugins (initLinker, loadRawObject, resolveObjs)+import System.Plugins.MultiStage+import Data.List (isPrefixOf)+import Distribution.Verbosity (silent,verbose)+import Distribution.Simple.Utils (defaultPackageDesc)+import Distribution.PackageDescription+import Distribution.PackageDescription.Parse (readPackageDescription)+import Distribution.PackageDescription.Configuration (flattenPackageDescription)++import Feldspar.Compiler.CallConv (rewriteType, buildCType, buildHaskellType)++import Data.Default+import Foreign.Ptr+import Foreign.Marshal (with)+import Foreign.Marshal.Unsafe (unsafeLocalState)+import Foreign.Storable (Storable(..))+import Foreign.C.String (CString, withCString)++import Control.Monad (join, (>=>), when, unless)+import Control.Applicative++import Language.Haskell.TH++import System.Directory (doesFileExist, removeFile, createDirectoryIfMissing)+import System.Process (readProcessWithExitCode)+import System.Exit (ExitCode(..))+import System.Info (os)+import System.IO.Unsafe (unsafePerformIO)+++-- Feldspar specific+import Feldspar.Runtime+import Feldspar.Compiler (compile, defaultOptions)+import Feldspar.Compiler.Backend.C.Library (encodeFunctionName)+import Feldspar.Compiler.Marshal ()++-- | Default configuration for the loader+feldsparPluginConfig :: Config+feldsparPluginConfig =+ defaultConfig { builder = feldsparBuilder+ , worker = feldsparWorker+ , typeFromName = loadFunType >=> rewriteType+ , mkHSig = buildHaskellType+ , mkCSig = buildCType+ }++-- | Compile and load Feldspar functions into the current GHC session.+--+-- > prog1 :: Data Index -> Vector1 Index+-- > prog1 c = indexed c (const c)+-- >+-- > $(loadFun ['prog1])+--+-- The call to @loadFun@ above will splice code into the current module+-- to compile, load and wrap a Feldspar function as a Haskell function:+--+-- > c_prog1 :: Index -> [Index]+--+loadFun :: [Name] -> Q [Dec]+loadFun = loadFunWithConfig feldsparPluginConfig++-- | Call @loadFun@ with C compiler options+loadFunOpts :: [String] -> [Name] -> Q [Dec]+loadFunOpts o = loadFunWithConfig feldsparPluginConfig{opts = o}++feldsparWorker :: Name -> [Name] -> Q Body+feldsparWorker fun as = normalB+ [|with def $ \outPtr -> do+ join $(infixApp (apply ([|pure $(varE fun)|] : map toRef as)) [|(<*>)|] [|pure outPtr|])+ peek outPtr >>= from+ |]+ where+ toRef name = [| pack $(varE name) |]++ apply :: [ExpQ] -> ExpQ+ apply [] = error "apply []"+ apply [x] = x+ apply (x:y:zs) = apply (infixApp x [|(<*>)|] y : zs)++feldsparBuilder :: Config -> Name -> Q Body+feldsparBuilder Config{..} fun = do+ let db = getDB+ let opts' = opts ++ map ("-I"++) db+ normalB [|unsafeLocalState $ do+ createDirectoryIfMissing True wdir+ $(varE 'compile) $(varE fun) basename base defaultOptions+ compileAndLoad basename opts'+ lookupSymbol symbol+ |]+ where+ base = nameBase fun+ basename = wdir ++ "/" ++ base+ symbol = ldprefix ++ encodeFunctionName base+ ldprefix = case os of+ "darwin" -> "_"+ _ -> ""++getDB :: [String]+getDB = unsafePerformIO $ do+ dirs <- sequence [ sandbox, user, local ]+ putStrLn $ unwords $ "Using feldspar runtime in" : concat dirs+ return $ concat dirs++ where+ sandbox = do+ (c,d,_) <- readProcessWithExitCode "cabal" ["sandbox", "hc-pkg","field","feldspar-compiler","include-dirs"] ""+ case c of+ ExitSuccess -> return $ drop 1 $ words d+ _ -> return []+ user = do+ (c,d,_) <- readProcessWithExitCode "ghc-pkg" ["field","feldspar-compiler","include-dirs"] ""+ case c of+ ExitSuccess -> return $ drop 1 $ words d+ _ -> return []+ local = do+ pd <- readPackageDescription verbose =<< defaultPackageDesc verbose+ let f a = return $ includeDirs $ libBuildInfo a+ maybe (return []) f (maybeHasLibs $ flattenPackageDescription pd)++maybeHasLibs :: PackageDescription -> Maybe Library+maybeHasLibs p =+ library p >>= \lib -> if buildable (libBuildInfo lib)+ then Just lib+ else Nothing++compileAndLoad :: String -> [String] -> IO ()+compileAndLoad name opts = do+ let cname = name ++ ".c"+ let oname = name ++ ".o"+ exists <- doesFileExist oname+ when exists $ removeFile oname+ compileC cname oname opts+ initLinker+ _ <- loadRawObject oname+ resolveObjs $ error $ "Symbols in " ++ oname ++ " could not be resolved"++compileC :: String -> String -> [String] -> IO ()+compileC srcfile objfile opts = do+ let args = [ "-optc -std=c99"+ , "-optc -Wall"+ , "-w"+ , "-c"+ ]+ (_,stdout,stderr) <- readProcessWithExitCode ghc (args ++ opts ++ ["-o",objfile,srcfile]) ""+ let output = stdout ++ stderr+ unless (null output) $ putStrLn output++lookupSymbol :: String -> IO (Ptr a)+lookupSymbol symbol = do+ when (0 /= feldspar_compiler_hook) $ error "lookupSymbol: Runtime library missing"+ mptr <- withCString symbol _lookupSymbol+ when (mptr == nullPtr) $ error $ "Symbol " ++ symbol ++ " not found"+ return mptr++foreign import ccall safe "lookupSymbol"+ _lookupSymbol :: CString -> IO (Ptr a)+
− lib/Feldspar/NameExtractor.hs
@@ -1,159 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----module Feldspar.NameExtractor where--import System.IO-import System.IO.Unsafe-import Language.Haskell.Exts-import Feldspar.Compiler.Error-import Feldspar.Compiler.Backend.C.Library--data OriginalFunctionSignature = OriginalFunctionSignature {- originalFunctionName :: String,- originalParameterNames :: [Maybe String]-} deriving (Show, Eq)--nameExtractorError :: ErrorClass -> String -> a-nameExtractorError = handleError "NameExtractor"--neutralName :: String-neutralName = "\\"++ r 4 ++"/\\"++ r 7 ++"\n ) ( ')"++ r 6 ++"\n( / )"++ r 7 ++"\n \\(__)|"- where r n = replicate n ' '--ignore :: OriginalFunctionSignature-ignore = OriginalFunctionSignature neutralName []--warning :: String -> a -> a-warning msg retval = unsafePerformIO $ do- withColor Yellow $ putStrLn $ "Warning: " ++ msg- return retval---- Module SrcLoc ModuleName [OptionPragma] (Maybe WarningText) (Maybe [ExportSpec]) [ImportDecl] [Decl]-stripModule :: Module -> [Decl]-stripModule x = case x of- Module _ _ _ _ _ _ g -> g--stripFunBind :: Decl -> OriginalFunctionSignature-stripFunBind x = case x of- FunBind [Match _ b c _ _ _] ->- OriginalFunctionSignature (stripName b) (map stripPattern c) -- going for name and parameter list- -- "Match SrcLoc Name [Pat] (Maybe Type) Rhs Binds"- FunBind l@(Match _ b _ _ _ _ : _) | length l > 1 -> warning- ("Ignoring function " ++ stripName b ++- ": multi-pattern function definitions are not compilable as Feldspar functions.") ignore- PatBind _ b _ _ _ -> case stripPattern b of- Just functionName -> OriginalFunctionSignature functionName [] -- parameterless declarations (?)- Nothing -> nameExtractorError InternalError ("Unsupported pattern binding: " ++ show b)- TypeSig{} -> ignore --head b -- we don't need the type signature (yet)- DataDecl{} -> ignore- InstDecl{} -> ignore- -- TypeDecl SrcLoc Name [TyVarBind] Type- TypeDecl{} -> ignore- unknown -> nameExtractorError InternalError ("Unexpected language element [SFB/1]: " ++ show unknown- ++ "\nPlease file a feature request with an example attached.")--stripPattern :: Pat -> Maybe String-stripPattern (PVar x) = Just $ stripName x-stripPattern PWildCard = Nothing-stripPattern (PAsPat x _) = Just $ stripName x-stripPattern (PParen pattern) = stripPattern pattern-stripPattern _ = Nothing--stripName :: Name -> String-stripName (Ident a) = a-stripName (Symbol a) = a--stripModule2 :: Module -> ModuleName-stripModule2 (Module _ b _ _ _ _ _) = b--stripModuleName :: ModuleName -> String-stripModuleName (ModuleName x) = x--getModuleName :: FilePath -> String -> String -- filename, filecontents -> modulename-getModuleName fileName = stripModuleName . stripModule2 . fromParseResult . customizedParse fileName--usedExtensions :: [Extension]-usedExtensions = glasgowExts ++ [ExplicitForAll]---- Ultimate debug function-getParseOutput :: FilePath -> IO (ParseResult Module)-getParseOutput = parseFileWithMode (defaultParseMode { extensions = usedExtensions })--customizedParse :: FilePath -> FilePath -> ParseResult Module-customizedParse fileName = parseFileContentsWithMode- (defaultParseMode- { extensions = usedExtensions- , parseFilename = fileName- })--getFullDeclarationListWithParameterList :: FilePath -> String -> [OriginalFunctionSignature]-getFullDeclarationListWithParameterList fileName fileContents =- map stripFunBind (stripModule $ fromParseResult $ customizedParse fileName fileContents )--functionNameNeeded :: String -> Bool-functionNameNeeded functionName = functionName /= neutralName--stripUnnecessary :: [String] -> [String]-stripUnnecessary = filter functionNameNeeded--printDeclarationList :: FilePath -> IO (String -> [String])-printDeclarationList fileName = do- handle <- openFile fileName ReadMode- fileContents <- hGetContents handle- return $ getDeclarationList fileContents--printDeclarationListWithParameterList :: FilePath -> IO ()-printDeclarationListWithParameterList fileName = do- handle <- openFile fileName ReadMode- fileContents <- hGetContents handle- print $ filter (functionNameNeeded . originalFunctionName) (getFullDeclarationListWithParameterList fileName fileContents)--printParameterListOfFunction :: FilePath -> String -> IO [Maybe String]-printParameterListOfFunction = getParameterList---- The interface-getDeclarationList :: FilePath -> String -> [String] -- filename, filecontents -> Stringlist-getDeclarationList fileName = stripUnnecessary . map originalFunctionName . getFullDeclarationListWithParameterList fileName--getExtendedDeclarationList :: FilePath -> String -> [OriginalFunctionSignature] -- filename, filecontents -> ExtDeclList-getExtendedDeclarationList fileName fileContents =- filter (functionNameNeeded . originalFunctionName)- (getFullDeclarationListWithParameterList fileName fileContents)--getParameterListOld :: FilePath -> String -> String -> [Maybe String]-getParameterListOld fileName fileContents funName = originalParameterNames $ head $- filter ((==funName) . originalFunctionName)- (getExtendedDeclarationList fileName fileContents)--getParameterList :: FilePath -> String -> IO [Maybe String]-getParameterList fileName funName = do- handle <- openFile fileName ReadMode- fileContents <- hGetContents handle- return $ originalParameterNames $ head $- filter ((==funName) . originalFunctionName) (getExtendedDeclarationList fileName fileContents)
+ lib/Feldspar/Runtime.hs view
@@ -0,0 +1,26 @@+-- | A module provinding a linker hook that can be referenced to ensure+-- that the runtime support files are linked.+--+-- NOTE. This file should not be loaded from ghci+--++module Feldspar.Runtime+ ( feldspar_compiler_hook+ )+ where++feldspar_compiler_hook :: Int+feldspar_compiler_hook = sum [ feldspar_c99_hook+ , feldspar_ivar_hook+ , feldspar_taskpool_hook+ ]++foreign import ccall safe "feldspar_c99_hook"+ feldspar_c99_hook :: Int++foreign import ccall safe "feldspar_ivar_hook"+ feldspar_ivar_hook :: Int++foreign import ccall safe "feldspar_taskpool_hook"+ feldspar_taskpool_hook :: Int+
lib/Feldspar/Transformation.hs view
@@ -34,8 +34,8 @@ ) where import Feldspar.Transformation.Framework as X-import Feldspar.Compiler.Imperative.TransformationInstance as X import Feldspar.Compiler.Imperative.Representation as X+import Feldspar.Compiler.Imperative.TransformationInstance () -- ================================================================================================ -- == Plugin class
lib/Feldspar/Transformation/Framework.hs view
@@ -55,9 +55,6 @@ combine :: t -> t -> t combine = transformationError "Default combination function used." -class Convert a b where- convert :: a -> b- instance Default () where def = () @@ -85,9 +82,6 @@ instance (Combine a, Combine b) => Combine (a,b) where combine (x,y) (v,w) = (combine x v, combine y w)--instance Default b => Convert a b where- convert _ = def -- ============================= -- == TransformationFramework ==
− src/Feldspar/Compiler/Frontend/CommandLine/API.hs
@@ -1,155 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE CPP #-}-module Feldspar.Compiler.Frontend.CommandLine.API where--import qualified Feldspar.NameExtractor as NameExtractor-import Feldspar.Compiler.Backend.C.Options-import Feldspar.Compiler.Compiler-import Feldspar.Compiler.Imperative.FromCore-import Feldspar.Compiler.Frontend.CommandLine.API.Library-import Feldspar.Compiler.Backend.C.Library-import Language.Haskell.Interpreter-import Language.Haskell.Interpreter.Unsafe-import qualified Data.Typeable as T-import Control.Monad---- ====================================== System imports ==================================-import System.Directory-import System.FilePath-import System.IO-import System.Exit-import System.Environment-import System.Console.GetOpt--import Control.Exception (catch, IOException)--data CompilationResult- = CompilationSuccess- | CompilationFailure- deriving (Eq, Show, T.Typeable)--#ifdef RELEASE-releaseMode = True-#else-releaseMode = False-#endif-- -- A general interpreter body for interpreting an expression-generalInterpreterBody :: forall a . (T.Typeable (IO a))- => String -- the expression to interpret- -> Interpreter (IO a)-generalInterpreterBody expression = interpret expression (as::IO a)---- A high-level interface for calling the interpreter-highLevelInterpreter :: T.Typeable (IO a)- => String -- the module name (for example My.Module)- -> String -- the input file name (for example "My/Module.hs")- -> [String] -- globalImportList- -> Bool -- need to import global modules qualified?- -> Interpreter (IO a) -- ^ an interpreter body- -> IO CompilationResult-highLevelInterpreter moduleName inputFileName importList needQualify interpreterBody = do- actionToExecute <- runInterpreter $ do- set [ languageExtensions := [GADTs, ScopedTypeVariables, TypeSynonymInstances, StandaloneDeriving,- DeriveDataTypeable, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses,- FunctionalDependencies, ExistentialQuantification, Rank2Types, TypeOperators,- EmptyDataDecls, GeneralizedNewtypeDeriving, TypeFamilies, ViewPatterns,- UnknownExtension "ImplicitPrelude" ]- ]- unsafeSetGhcOption "-fcontext-stack=100"- -- in relesae mode, globalImportList modules are package modules and shouldn't be loaded, only imported- -- in normal mode, we need to load them before importing them- loadModules $ inputFileName : if not releaseMode then importList else []- setTopLevelModules [moduleName]- -- Import modules qualified to prevent name collisions with user defined entities- if needQualify- then setImportsQ $ zip importList $ map Just importList- else setImports importList- interpreterBody- case actionToExecute of- Left err -> do- printInterpreterError err- return CompilationFailure- Right action -> do- action- return CompilationSuccess- -- either printInterpreterError id actionToExecute--printInterpreterError :: InterpreterError -> IO ()-printInterpreterError (WontCompile []) = return ()-printInterpreterError (WontCompile (x:xs)) = do- printGhcError x- printInterpreterError (WontCompile xs)- where- printGhcError (GhcError {errMsg=s}) = hPutStrLn stderr s-printInterpreterError e = hPutStrLn stderr $ "Code generation failed: " ++ show e--handleOptions :: [OptDescr (a -> IO a)] -> a -> String -> IO (a, String)-handleOptions descriptors startOptions helpHeader = do- args <- getArgs-- when (null args) (do- putStrLn $ usageInfo helpHeader descriptors- exitSuccess)-- -- Parse options, getting a list of option actions- let (actions, nonOptions, errors) = getOpt Permute descriptors args-- when (length errors > 0) (do- putStrLn $ concat errors- putStrLn $ usageInfo helpHeader descriptors- exitWith (ExitFailure 1))-- -- Here we thread startOptions through all supplied option actions- opts <- foldl (>>=) (return startOptions) actions-- when (length nonOptions /= 1) (do- putStrLn "ERROR: Exactly one input file expected."- exitWith (ExitFailure 1))-- let inputFileName = replace (head nonOptions) "\\" "/" -- change it for multi-file operation-- return (opts, inputFileName)--removeFileIfPossible :: String -> IO ()-removeFileIfPossible filename = removeFile filename `Control.Exception.catch` (\(e :: IOException) -> return ())--prepareInputFile :: String -> IO ()-prepareInputFile inputFileName = do- removeFileIfPossible $ replaceExtension inputFileName ".hi"- removeFileIfPossible $ replaceExtension inputFileName ".o"--standaloneCompile :: (Compilable t internal) =>- t -> FilePath -> FilePath -> NameExtractor.OriginalFunctionSignature -> Options -> IO ()-standaloneCompile prg inputFileName outputFileName originalFunctionSignature opts = do- appendFile (makeCFileName outputFileName) $ sourceCode $ sctccrSource compilationResult- appendFile (makeHFileName outputFileName) $ sourceCode $ sctccrHeader compilationResult- where- compilationResult = compileToCCore Standalone prg (Just outputFileName) IncludesNeeded originalFunctionSignature opts
− src/Feldspar/Compiler/Frontend/CommandLine/API/Constants.hs
@@ -1,36 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----module Feldspar.Compiler.Frontend.CommandLine.API.Constants where--globalImportList = ["Feldspar.Compiler.Compiler"]--warningPrefix = "[WARNING]: "-errorPrefix = "[ERROR ]: "--
− src/Feldspar/Compiler/Frontend/CommandLine/API/Library.hs
@@ -1,72 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----module Feldspar.Compiler.Frontend.CommandLine.API.Library where---import Data.Char-import Language.Haskell.Interpreter-import System.Console.ANSI-import Feldspar.Compiler.Backend.C.Library--lowerFirst :: String -> String-lowerFirst (first:rest) = toLower first : rest-lowerFirst s = s--upperFirst :: String -> String-upperFirst (first:rest) = toUpper first : rest-upperFirst s = s--formatStringListCore :: [String] -> String-formatStringListCore [] = ""-formatStringListCore [x] = x-formatStringListCore (x:xs) = x ++ " | " ++ formatStringListCore xs--formatStringList :: [String] -> String-formatStringList list | not (null list) = "(" ++ formatStringListCore list ++ ")"-formatStringList _ = error "This list should not be empty."--rpad :: Int -> String -> String-rpad target = rpadWith target ' '--rpadWith :: Int -> Char -> String -> String-rpadWith target padchar s- | length s >= target = s- | otherwise = rpadWith target padchar (s ++ [padchar])--iPutStrLn :: String -> Interpreter ()-iPutStrLn = liftIO . putStrLn--iPutStr :: String -> Interpreter ()-iPutStr = liftIO . putStr--fancyWrite :: String -> IO ()-fancyWrite s = do- withColor Blue $ putStr "=== [ "- withColor Cyan $ putStr $ rpad 70 s- withColor Blue $ putStrLn " ] ==="
− src/Feldspar/Compiler/Frontend/CommandLine/API/Options.hs
@@ -1,135 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----module Feldspar.Compiler.Frontend.CommandLine.API.Options where--import qualified Feldspar.Compiler.Backend.C.Options as CompilerCoreOptions-import qualified Feldspar.Compiler.Compiler as CompilerCore-import qualified Feldspar.Compiler.Frontend.CommandLine.API.Library as StandaloneLib-import Feldspar.Compiler.Frontend.CommandLine.API.Constants-import Feldspar.Compiler.Backend.C.Platforms--import Data.List-import Data.Char-import Data.Maybe (fromMaybe)--import System.Console.GetOpt-import System.Exit-import System.Environment-import System.IO-import System.Process-import System.Info-import System.Directory--availablePlatformsStrRep = StandaloneLib.formatStringList $- map (StandaloneLib.upperFirst . CompilerCoreOptions.name) availablePlatforms--data StandaloneMode = SingleFunction String | MultiFunction--data Options = Options { optStandaloneMode :: StandaloneMode- , optOutputFileName :: Maybe String- , optCompilerMode :: CompilerCoreOptions.Options- }---- | Default options-startOptions :: Options-startOptions = Options { optStandaloneMode = MultiFunction- , optOutputFileName = Nothing- , optCompilerMode = CompilerCore.defaultOptions- }--helpHeader = "Standalone Feldspar Compiler\nUsage: feldspar [options] inputfile\n" ++- "Notes: \n" ++- " * When no output file name is specified, the input file's name with .c extension is used\n" ++- " * The inputfile parameter is always needed, even in single-function mode\n" ++- "\nAvailable options: \n"---- | Option descriptions for getOpt-optionDescriptors :: [ OptDescr (Options -> IO Options) ]-optionDescriptors =- [ Option "f" ["singlefunction"]- (ReqArg- (\arg opt -> return opt { optStandaloneMode = SingleFunction arg })- "FUNCTION")- "Enables single-function compilation"- , Option "o" ["output"]- (ReqArg- (\arg opt -> return opt { optOutputFileName = Just arg })- "outputfile")- "Overrides the file names for the generated output code"-- , Option "p" ["platform"]- (ReqArg- (\arg opt -> return opt { optCompilerMode = (optCompilerMode opt)- { CompilerCoreOptions.platform = decodePlatform arg } })- "<platform>")- ("Overrides the target platform " ++ availablePlatformsStrRep)- , Option "u" ["unroll"]- (ReqArg- (\arg opt -> return opt {- optCompilerMode = (optCompilerMode opt) {- CompilerCoreOptions.unroll = CompilerCoreOptions.Unroll (parseInt arg "Invalid unroll count")- }- })- "<unrollCount>")- "Enables loop unrolling"- , Option "D" ["debuglevel"]- (ReqArg- (\arg opt -> return opt { optCompilerMode = (optCompilerMode opt)- { CompilerCoreOptions.debug = decodeDebug arg } })- "<level>")- "Specifies debug level (currently the only possible option is NoPrimitiveInstructionHandling)"- , Option "h" ["help"]- (NoArg- (\_ -> do- --prg <- getProgName- hPutStrLn stderr (usageInfo helpHeader optionDescriptors)- exitSuccess))- "Show this help message"- ]---- ==============================================================================--- == Option Decoders--- ==============================================================================--findPlatformByName :: String -> Maybe CompilerCoreOptions.Platform-findPlatformByName platformName = -- Finds a platform by name using case-insensitive comparison- find (\platform -> map toLower platformName == map toLower (CompilerCoreOptions.name platform))- availablePlatforms--decodePlatform :: String -> CompilerCoreOptions.Platform-decodePlatform s = fromMaybe (error $ "Invalid platform specified. Valid platforms are: " ++ availablePlatformsStrRep)- $ findPlatformByName s--decodeDebug "NoPrimitiveInstructionHandling" = CompilerCoreOptions.NoPrimitiveInstructionHandling-decodeDebug _ = error "Invalid debug level specified"--parseInt :: String -> String -> Int-parseInt arg message = case reads arg of- [(x, "")] -> x- _ -> error message
− src/Feldspar/Compiler/Frontend/CommandLine/Main.hs
@@ -1,219 +0,0 @@------ Copyright (c) 2009-2011, ERICSSON AB--- All rights reserved.--- --- Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions are met:--- --- * Redistributions of source code must retain the above copyright notice, --- this list of conditions and the following disclaimer.--- * Redistributions in binary form must reproduce the above copyright--- notice, this list of conditions and the following disclaimer in the--- documentation and/or other materials provided with the distribution.--- * Neither the name of the ERICSSON AB nor the names of its contributors--- may be used to endorse or promote products derived from this software--- without specific prior written permission.--- --- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"--- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE--- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE --- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE--- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL--- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER--- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,--- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE--- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-----{-# LANGUAGE ScopedTypeVariables #-}--module Main where--- ====================================== Feldspar imports ==================================-import Feldspar.NameExtractor-import Feldspar.Compiler.Compiler-import qualified Feldspar.Compiler.Compiler as CompilerCore-import Feldspar.Compiler.Backend.C.Options-import qualified Feldspar.Compiler.Backend.C.Options as CoreOptions-import Feldspar.Compiler.Frontend.CommandLine.API.Options as StandaloneOptions-import Feldspar.Compiler.Frontend.CommandLine.API.Constants-import Feldspar.Compiler.Frontend.CommandLine.API.Library as StandaloneLib-import Feldspar.Compiler.Backend.C.Library-import Feldspar.Compiler.Frontend.CommandLine.API-import Feldspar.Compiler.Imperative.Representation-import Feldspar.Compiler.Backend.C.CodeGeneration-import Feldspar.Compiler.Error-import Feldspar.Compiler.Backend.C.Plugin.PrettyPrint--- ====================================== System imports ==================================-import System.IO-import System.Exit-import System.Info-import System.Process-import System.IO.Error-import System.FilePath-import System.Directory-import System.Environment-import System.Console.GetOpt--- ====================================== Control imports ==================================-import Control.Monad-import Control.Exception-import Control.Monad.Error-import Control.Monad.CatchIO--- ====================================== Other imports ==================================-import Data.List-import Data.Maybe (fromMaybe)-import Debug.Trace-import Language.Haskell.Interpreter---data CompilationError =- InterpreterError InterpreterError- | InternalErrorCall String--compileFunction :: String -> String -> CoreOptions.Options -> OriginalFunctionSignature- -> Interpreter (String, Either SplitModuleDescriptor CompilationError)-compileFunction inFileName outFileName coreOptions originalFunctionSignature = do- let functionName = originalFunctionName originalFunctionSignature- (SomeCompilable prg) <- interpret ("SomeCompilable " ++ functionName) (as::SomeCompilable)- let splitModuleDescriptor = executePluginChain Standalone prg originalFunctionSignature coreOptions- -- XXX force evaluation in order to be able to catch the exceptions- -- liftIO $ evaluate $ compToC coreOptions compilationUnit -- XXX somehow not enough(?!) -- counter-example: structexamples- liftIO $ do- tempdir <- Control.Exception.catch getTemporaryDirectory (\(_ :: IOException) -> return ".")- (tempfile, temph) <- openTempFile tempdir "feldspar-temp.txt"- let core = compileToCCore Standalone prg (Just outFileName) IncludesNeeded originalFunctionSignature coreOptions- Control.Exception.finally (do hPutStrLn temph $ sourceCode $ sctccrSource core- hPutStrLn temph $ sourceCode $ sctccrHeader core)- (do hClose temph- removeFileIfPossible tempfile)- return (functionName, Left splitModuleDescriptor)--compileAllFunctions :: String -> String -> CoreOptions.Options -> [OriginalFunctionSignature]- -> Interpreter [(String, Either SplitModuleDescriptor CompilationError)]-compileAllFunctions inFileName outFileName options [] = return []-compileAllFunctions inFileName outFileName options (x:xs) = do- let functionName = originalFunctionName x- resultCurrent <- catchError (compileFunction inFileName outFileName options x)- (\(e::InterpreterError) -> return (functionName, Right $ InterpreterError e))- `Control.Monad.CatchIO.catch`- (\msg -> return (functionName,- Right $ InternalErrorCall $ errorPrefix ++ show (msg::Control.Exception.ErrorCall)))- resultRest <- compileAllFunctions inFileName outFileName options xs- return $ resultCurrent : resultRest---- | Interpreter body for single-function compilation-singleFunctionCompilationBody :: String -> String -> CoreOptions.Options -> OriginalFunctionSignature- -> Interpreter (IO ())-singleFunctionCompilationBody inFileName outFileName coreOptions originalFunctionSignature = do- liftIO $ fancyWrite $ "Compiling function " ++ originalFunctionName originalFunctionSignature ++ "..."- SomeCompilable prg <-- interpret ("SomeCompilable " ++ originalFunctionName originalFunctionSignature) (as::SomeCompilable)- liftIO $ standaloneCompile prg inFileName outFileName originalFunctionSignature coreOptions- return $ return ()--mergeModules :: [Module ()] -> Module ()-mergeModules [] = handleError "Standalone" InvariantViolation "Called mergeModules with an empty list"-mergeModules [x] = x-mergeModules l@(x:xs) = Module {- entities = nub $ entities x ++ entities (mergeModules xs), -- nub is in fact a "global plugin" here- moduleLabel = ()-}--padFunctionName :: String -> String-padFunctionName n = StandaloneLib.rpadWith 50 '.' $ "Function " ++ n--writeErrors :: (String, Either a CompilationError) -> IO ()-writeErrors (functionName, Left x) = return ()-writeErrors (functionName, Right err) = case err of - InterpreterError ie -> do- withColor Red $ putStrLn $ "Error in function " ++ functionName ++ ":"- printInterpreterError ie- InternalErrorCall ec -> do- withColor Red $ putStrLn $ "Error in function " ++ functionName ++ ":"- withColor Red $ putStrLn ec--writeSummary :: (String, Either a CompilationError) -> IO ()-writeSummary (functionName, Left x) = do- withColor Cyan $ putStr $ padFunctionName functionName- withColor Green $ putStrLn "[OK]"-writeSummary (functionName, Right msg) = do- withColor Cyan $ putStr $ padFunctionName functionName- withColor Red $ putStrLn "[FAILED]"--filterLefts :: [(String, Either a b)] -> [a]-filterLefts [] = []-filterLefts [(_,Left x)] = [x]-filterLefts [(_,Right _)] = []-filterLefts ((_,Left x):xs) = x : filterLefts xs-filterLefts ((_,Right _):xs) = filterLefts xs---- | Interpreter body for multi-function compilation-multiFunctionCompilationBody :: String -> String -> CoreOptions.Options -> [OriginalFunctionSignature] -> Interpreter (IO ())-multiFunctionCompilationBody inFileName outFileName coreOptions declarationList = do- let (hIncludes, hLineNum) = genIncludeLines coreOptions Nothing- let (cIncludes, cLineNum) = genIncludeLines coreOptions (Just outFileName)- liftIO $ appendFile (makeHFileName outFileName) hIncludes- liftIO $ appendFile (makeCFileName outFileName) cIncludes- modules <- compileAllFunctions inFileName outFileName coreOptions declarationList- liftIO $ do- mapM_ writeErrors modules- withColor Blue $ putStrLn "\n================= [ Summary of compilation results ] =================\n"- mapM_ writeSummary modules- let mergedCModules = mergeModules $ map smdSource $ filterLefts modules- let mergedHModules = mergeModules $ map smdHeader $ filterLefts modules- let cCompToCResult = compToCWithInfos ((coreOptions, Declaration_pl), cLineNum) mergedCModules- let hCompToCResult = compToCWithInfos ((coreOptions, Declaration_pl), hLineNum) mergedHModules- appendFile (makeCFileName outFileName) (fst $ snd cCompToCResult) `Control.Exception.catch` errorHandler- appendFile (makeHFileName outFileName) (fst $ snd hCompToCResult) `Control.Exception.catch` errorHandler- writeFile (makeDebugCFileName outFileName) (show $ fst cCompToCResult) `Control.Exception.catch` errorHandler- writeFile (makeDebugHFileName outFileName) (show $ fst hCompToCResult) `Control.Exception.catch` errorHandler- return $ return ()- where- errorHandler msg = withColor Red $ putStrLn $ errorPrefix ++ show (msg::Control.Exception.ErrorCall)---- | Calculates the output file name.-convertOutputFileName :: String -> Maybe String -> String-convertOutputFileName inputFileName = fromMaybe (takeFileName $ dropExtension inputFileName)--makeBackup :: String -> IO ()-makeBackup filename = renameFile filename (filename ++ ".bak") `Control.Exception.catch` (\(_ :: IOException) -> return ())--main = do- (opts, inputFileName) <- handleOptions optionDescriptors startOptions helpHeader- let outputFileName = convertOutputFileName inputFileName (optOutputFileName opts)-- prepareInputFile inputFileName- makeBackup $ makeHFileName outputFileName- makeBackup $ makeCFileName outputFileName- makeBackup $ makeDebugHFileName outputFileName- makeBackup $ makeDebugCFileName outputFileName-- fileDescriptor <- openFile inputFileName ReadMode- fileContents <- hGetContents fileDescriptor-- let declarationList = getExtendedDeclarationList inputFileName fileContents- let moduleName = getModuleName inputFileName fileContents- fancyWrite $ "Compilation target: module " ++ moduleName- fancyWrite $ "Output file: " ++ outputFileName-- let highLevelInterpreterWithModuleInfo =- highLevelInterpreter moduleName inputFileName globalImportList False-- -- C code generation- case optStandaloneMode opts of- MultiFunction- | null declarationList -> putStrLn "No functions to compile."- | otherwise -> do- fancyWrite $ "Number of functions to compile: " ++ show (length declarationList)- highLevelInterpreterWithModuleInfo- (multiFunctionCompilationBody inputFileName outputFileName (optCompilerMode opts) declarationList)- return ()- SingleFunction funName -> do- let originalFunctionSignatureNeeded =- case filter ((==funName).originalFunctionName) declarationList of- [a] -> a- [] -> error $ "Function " ++ funName ++ " not found"- _ -> error "Unexpected error SC/01"- highLevelInterpreterWithModuleInfo- (singleFunctionCompilationBody inputFileName outputFileName (optCompilerMode opts) originalFunctionSignatureNeeded)- return ()
+ tests/CallingConvention.hs view
@@ -0,0 +1,57 @@+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE ForeignFunctionInterface #-}++-- | Test that the compiler respects the calling conventions of Feldspar++module Main where++import qualified Prelude++import Test.Tasty+import Test.Tasty.QuickCheck+import Test.QuickCheck++import Feldspar hiding (assert)+import Feldspar.Vector+import Feldspar.Compiler+import Feldspar.Compiler.Plugin++pairArg :: (Data Word8,Data IntN) -> Data IntN+pairArg (a,b) = i2n a + b++pairRes :: Data Word16 -> (Data WordN, Data IntN)+pairRes a = (i2n a, i2n a)++vecId :: Vector1 Word32 -> Vector1 Word32+vecId = id++vectorInPair :: (Vector1 WordN, Data WordN) -> (Data WordN, Vector1 WordN)+vectorInPair (v,a) = (a,v)++vectorInVector :: Vector (Vector1 WordN) -> Data WordN+vectorInVector v = sum $ map sum v++vectorInPairInVector :: Data WordN -> Vector (Data WordN, Vector1 WordN)+vectorInPairInVector l = indexed l $ \i -> (i, indexed i id)++loadFun ['pairArg, 'pairRes, 'vecId, 'vectorInPair, 'vectorInVector, 'vectorInPairInVector]++prop_pairArg = eval pairArg ==== c_pairArg+prop_pairRes = eval pairRes ==== c_pairRes+prop_vecId = eval vecId ==== c_vecId+prop_vectorInPair = eval vectorInPair ==== c_vectorInPair+prop_vectorInVector = eval vectorInVector ==== c_vectorInVector+prop_vectorInPairInVector = forAll (choose (0,63)) $ \l -> eval vectorInPairInVector l ==== c_vectorInPairInVector l++tests :: TestTree+tests = testGroup "CodeGeneration"+ [ testProperty "pairArg" prop_pairArg+ , testProperty "pairRes" prop_pairRes+ , testProperty "vecId" prop_vecId+ , testProperty "vectorInPair" prop_vectorInPair+ , testProperty "vectorInVector" prop_vectorInVector+ , testProperty "vectorInPairInVector" prop_vectorInPairInVector+ ]++main :: IO ()+main = defaultMain tests
+ tests/RegressionTests.hs view
@@ -0,0 +1,175 @@+{-# LANGUAGE TemplateHaskell #-}++module Main where++-- To generate the golden files use a script similiar to this one+-- > ghc -ilib -isrc -itests tests/RegressionTests.hs -e 'writeGoldFile example9 "example9" defaultOptions'+-- > ghc -ilib -isrc -itests tests/RegressionTests.hs -e 'writeGoldFile example9 "example9_native" nativeOpts'++import Test.Tasty+import Test.Tasty.Golden.Advanced+import Test.Tasty.QuickCheck++import qualified Prelude+import Feldspar+import Feldspar.Compiler+import Feldspar.Compiler.Plugin+import Feldspar.Vector+import Feldspar.Vector.Internal (scan)+import qualified Feldspar.Vector.Push as PV++import Control.Monad+import Control.Monad.Error (liftIO)+import Data.Monoid ((<>))+import qualified Data.ByteString.Lazy as LB+import System.Process+import Text.Printf++example9 :: Data Int32 -> Data Int32+example9 a = condition (a<5) (3*(a+20)) (30*(a+20))++-- Compile and load example9 as c_example9 (using plugins)+loadFun ['example9]++topLevelConsts :: Data Index -> Data Index -> Data Index+topLevelConsts a b = condition (a<5) (d ! (b+5)) (c ! (b+5))+ where+ c = value [1,2,3,4,5] :: Data [Index]+ d = value [2,3,4,5,6] :: Data [Index]++pairParam :: (Data Index, Data Index) -> Data Index+pairParam (x, _) = x++pairParam2 :: (Data Int16, Data Int16) ->+ ((Data Int16, Data Int16), (Data Int16, Data Int16))+pairParam2 c = (c, c)++-- One test starting.+metrics :: Vector1 IntN -> Vector1 IntN+ -> Vector (Vector (Data Index, Data Index)) -> Vector (Vector1 IntN)+metrics s _ = scan (columnMetrics s) initialMetrics++initialMetrics :: Vector1 IntN+initialMetrics = replicate 8 (-32678)++columnMetrics :: Vector1 IntN -> Vector1 IntN -> Vector (Data Index, Data Index)+ -> Vector1 IntN+columnMetrics s prev zf = zipWith (metricFast prev) zf s++metricFast :: Vector1 IntN -> (Data Index, Data Index) -> Data IntN -> Data IntN+metricFast prev (z, _) _ = prev ! z+-- End one test.++copyPush :: Vector1 Index -> PV.PushVector1 Index+copyPush v = let pv = PV.toPush v in pv PV.++ pv++scanlPush :: PV.PushVector1 WordN -> Vector1 WordN -> PV.PushVector (PV.PushVector1 WordN)+scanlPush = PV.scanl const++concatV :: Vector (Vector1 IntN) -> Vector1 IntN+concatV = fold (++) Empty++complexWhileCond :: Data Int32 -> (Data Int32, Data Int32)+complexWhileCond y = whileLoop (0,y) (\(a,b) -> ((\a b -> a * a /= b * b) a (b-a))) (\(a,b) -> (a+1,b))++-- One test starting+divConq3 :: Vector1 IntN -> Vector1 IntN+divConq3 xs = concatV $ pmap (map (+1)) (segment 1024 xs)++pmap :: (Syntax a, Syntax b) => (a -> b) -> Vector a -> Vector b+pmap f = map await . force . map (future . f)++segment :: Syntax a => Data Length -> Vector a -> Vector (Vector a)+segment l xs = indexed clen (\ix -> take l $ drop (ix*l) xs)+ where clen = length xs `div` l+-- End one test.++-- | We rewrite `return x >>= \_ -> return y` into `return x >> return y`+-- This test ensures that we can still `return x` in the first action.+bindToThen :: Data Index -> Data Index+bindToThen y = runMutable $ do+ ref <- newRef y+ _ <- getRef ref+ getRef ref++switcher :: Data Word8 -> Data Bool -> Data Word8+switcher i = switch (value 0) [(true,i), (false,2)]++ivartest :: Data Index -> Data Index+ivartest a = share (future (a+1)) $ \a' -> await a' * 2++ivartest2 :: (Data Index, Data Index) -> (Data Index, Data Index)+ivartest2 a = share (future a) $ \a' -> await a'++tests :: TestTree+tests = testGroup "RegressionTests"+ [ testProperty "example9 (plugin)" $ eval example9 ==== c_example9+ , mkGoldTest example9 "example9" defaultOptions+ , mkGoldTest pairParam "pairParam" defaultOptions+ , mkGoldTest pairParam2 "pairParam2" defaultOptions+ , mkGoldTest concatV "concatV" defaultOptions+ , mkGoldTest complexWhileCond "complexWhileCond" defaultOptions+ , mkGoldTest topLevelConsts "topLevelConsts" defaultOptions+ , mkGoldTest topLevelConsts "topLevelConsts_native" nativeOpts+ , mkGoldTest topLevelConsts "topLevelConsts_sics" sicsOpts+ , mkGoldTest metrics "metrics" defaultOptions+ , mkGoldTest scanlPush "scanlPush" defaultOptions+ , mkGoldTest divConq3 "divConq3" defaultOptions+ , mkGoldTest ivartest "ivartest" defaultOptions+ , mkGoldTest ivartest2 "ivartest2" defaultOptions+ , mkBuildTest pairParam "pairParam" defaultOptions+ , mkBuildTest concatV "concatV" defaultOptions+ , mkBuildTest topLevelConsts "topLevelConsts" defaultOptions+ , mkBuildTest topLevelConsts "topLevelConsts_native" nativeOpts+ , mkBuildTest topLevelConsts "topLevelConsts_sics" sicsOpts+ , mkBuildTest metrics "metrics" defaultOptions+ , mkBuildTest copyPush "copyPush" defaultOptions+ , mkBuildTest scanlPush "scanlPush" defaultOptions+ , mkBuildTest divConq3 "divConq3" defaultOptions+ , testProperty "bindToThen" (\y -> eval bindToThen y Prelude.== y)+ , mkGoldTest switcher "switcher" defaultOptions+ , mkBuildTest ivartest "ivartest" defaultOptions+ , mkBuildTest ivartest2 "ivartest2" defaultOptions+ ]++main :: IO ()+main = defaultMain tests+++-- Helper functions+testDir, goldDir :: Prelude.FilePath+testDir = "tests/"+goldDir = "tests/gold/"++nativeOpts :: Options+nativeOpts = defaultOptions{rules=nativeArrayRules}+sicsOpts :: Options+sicsOpts = defaultOptions{frontendOpts=defaultFeldOpts{targets= [SICS]}}++writeGoldFile :: Syntax a => a -> Prelude.FilePath -> Options -> IO ()+writeGoldFile fun n = compile fun (goldDir <> n) n++mkGoldTest fun n opts = do+ let ref = goldDir <> n+ new = testDir <> n+ act = compile fun new n opts+ cmp = simpleCmp $ printf "Files '%s' and '%s' differ" ref new+ upd = LB.writeFile ref+ goldenTest n (vgReadFiles ref) (liftIO act >> vgReadFiles new) cmp upd++simpleCmp :: Prelude.Eq a => String -> a -> a -> IO (Maybe String)+simpleCmp e x y =+ return $ if x Prelude.== y then Nothing else Just e++vgReadFiles :: String -> ValueGetter r LB.ByteString+vgReadFiles base = liftM LB.concat $ mapM (vgReadFile . (base<>)) [".h",".c"]++mkBuildTest fun n opts = do+ let new = testDir <> n <> "_build_test"+ cfile = new <> ".c"+ act = do compile fun new n opts+ (_,so,se) <- readProcessWithExitCode "ghc" [cfile, "-c", "-optc -Ilib/Feldspar/C", "-optc -std=c99", "-Wall"] ""+ return $ so <> se+ cmp _ _ = return Nothing+ upd _ = return ()+ goldenTest n (return "") (liftIO act >> return "") cmp upd