-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | An optimising compiler for a functional, array-oriented language. -- -- Futhark is a small programming language designed to be compiled to -- efficient parallel code. It is a statically typed, data-parallel, and -- purely functional array language in the ML family, and comes with a -- heavily optimising ahead-of-time compiler that presently generates GPU -- code via CUDA and OpenCL, although the language itself is -- hardware-agnostic. -- -- For more information, see the website at -- https://futhark-lang.org -- -- For introductionary information about hacking on the Futhark compiler, -- see the hacking guide. Regarding the internal design of the -- compiler, the following modules make good starting points: -- --
-- rtscatomics.h --atomicsH :: Text -- |
-- rtscchaselev.h --chaselevH :: Text -- |
-- rtsccuda.h --cudaH :: Text -- |
-- rtscfree_list.h --freeListH :: Text -- |
-- rtschalf.h --halfH :: Text -- |
-- rtsclock.h --lockH :: Text -- |
-- rtscopencl.h --openclH :: Text -- |
-- rtscscalar_f16.h --scalarF16H :: Text -- |
-- rtscscalar.h --scalarH :: Text -- |
-- rtscscheduler.h --schedulerH :: Text -- |
-- rtscserver.h --serverH :: Text -- |
-- rtsctiming.h --timingH :: Text -- |
-- rtsctuning.h --tuningH :: Text -- |
-- rtscutil.h --utilH :: Text -- |
-- rtscvalues.h --valuesH :: Text -- | Code snippets used by the JS backends. module Futhark.CodeGen.RTS.JavaScript -- |
-- rtsjavascriptserver.js --serverJs :: Text -- |
-- rtsjavascriptvalues.js --valuesJs :: Text -- |
-- rtsjavascriptwrapperclasses.js --wrapperclassesJs :: Text -- | Code snippets used by the Python backends. module Futhark.CodeGen.RTS.Python -- |
-- rtspythonmemory.py --memoryPy :: Text -- |
-- rtspythonopencl.py --openclPy :: Text -- |
-- rtspythonpanic.py --panicPy :: Text -- |
-- rtspythonscalar.py --scalarPy :: Text -- |
-- rtspythonserver.py --serverPy :: Text -- |
-- rtspythontuning.py --tuningPy :: Text -- |
-- rtspythonvalues.py --valuesPy :: Text -- | Types (and a few other simple definitions) for futhark-pkg. module Futhark.Pkg.Types -- | A package path is a unique identifier for a package, for example -- github.comuserfoo. type PkgPath = Text -- | Turn a package path (which always uses forward slashes) into a file -- path in the local file system (which might use different slashes). pkgPathFilePath :: PkgPath -> FilePath -- | The dependencies of a (revision of a) package is a mapping from -- package paths to minimum versions (and an optional hash pinning). newtype PkgRevDeps PkgRevDeps :: Map PkgPath (SemVer, Maybe Text) -> PkgRevDeps -- | Convert a SemVer back to its textual representation. prettySemVer :: SemVer -> Text -- | An (Ideal) version number that conforms to Semantic Versioning. This -- is a prescriptive parser, meaning it follows the SemVer -- standard. -- -- Legal semvers are of the form: MAJOR.MINOR.PATCH-PREREL+META -- -- Example: 1.2.3-r1+commithash -- -- Extra Rules: -- --
-- > let loc = Loc (Pos "filename" 3 5 7) (Pos "filename" 5 7 9) -- > in putStrLn $ prettyPragma 80 $ srcloc loc <> text "foo" </> text "bar" </> text "baz" ---- -- will be printed as -- --
-- foo -- #line 3 "filename" -- bar -- baz --prettyPragma :: Int -> Doc -> String -- | Render and display a document with #line pragmas. prettyPragmaS :: Int -> Doc -> ShowS -- | Display a rendered document with #line pragmas. displayPragmaS :: RDoc -> ShowS -- | Render and convert a document to a String compactly. prettyCompact :: Doc -> String -- | Render and display a document compactly. prettyCompactS :: Doc -> ShowS -- | Render and display a document. prettyS :: Int -> Doc -> ShowS -- | Display a rendered document. displayS :: RDoc -> ShowS -- | Render a document without indentation on infinitely long lines. Since -- no 'pretty' printing is involved, this renderer is fast. The resulting -- output contains fewer characters. renderCompact :: Doc -> RDoc -- | Render a document given a maximum width. render :: Int -> Doc -> RDoc -- | Equivalent of error, but with a document instead of a string. errordoc :: Doc -> a -- | Equivalent of fail, but with a document instead of a string. faildoc :: MonadFail m => Doc -> m a -- | The document fillbreak i d renders document -- d, appending spaces until the width is equal -- to i. If the width of d is already greater than -- i, the nesting level is increased by i and a -- line is appended. fillbreak :: Int -> Doc -> Doc -- | The document fill i d renders document x, -- appending spaces until the width is equal to i. If -- the width of d is already greater than i, nothing is -- appended. fill :: Int -> Doc -> Doc -- | The document width d f is produced by concatenating -- d with the result of calling f with the width of the -- document d. width :: Doc -> (Int -> Doc) -> Doc -- | The document column f is produced by calling -- f with the current nesting level. nesting :: (Int -> Doc) -> Doc -- | The document column f is produced by calling -- f with the current column. column :: (Int -> Doc) -> Doc -- | The document nest i d renders the document d -- with the current indentation level increased by i. nest :: Int -> Doc -> Doc -- | The document indent i d renders d with a -- nesting level set to the current column plus i, -- including the first line. indent :: Int -> Doc -> Doc -- | The document hang i d renders d with a -- nesting level set to the current column plus i, not -- including the first line. hang :: Int -> Doc -> Doc -- | The document align d renders d with a nesting -- level set to the current column. align :: Doc -> Doc -- | The document list ds separates ds with commas -- and encloses them with brackets. list :: [Doc] -> Doc -- | The document tuple ds separates ds with -- commas and encloses them with parentheses. tuple :: [Doc] -> Doc -- | The document enclosesep l r p ds separates ds -- with the punctuation p and encloses the result using -- l and r. When wrapped, punctuation appears at the -- end of the line. The enclosed portion of the document is aligned one -- column to the right of the opening document. -- --
-- > ws = map text (words "The quick brown fox jumps over the lazy dog") -- > test = pretty 15 (enclosesep lparen rparen comma ws) ---- -- will be layed out as: -- --
-- (The, quick, -- brown, fox, -- jumps, over, -- the, lazy, -- dog) --enclosesep :: Doc -> Doc -> Doc -> [Doc] -> Doc -- | The document semisep ds semicolon-space separates -- ds, aligning the resulting document to the current nesting -- level. semisep :: [Doc] -> Doc -- | The document commasep ds comma-space separates -- ds, aligning the resulting document to the current nesting -- level. commasep :: [Doc] -> Doc -- | The document punctuate p ds obeys the law: -- --
-- punctuate p [d1, d2, ..., dn] = [d1 <> p, d2 <> p, ..., dn] --punctuate :: Doc -> [Doc] -> [Doc] -- | The document sep ds concatenates the documents -- ds with the space document as long as there is room, -- and uses line when there isn't. sep :: [Doc] -> Doc -- | The document cat ds concatenates the documents -- ds with the empty document as long as there is room, -- and uses line when there isn't. cat :: [Doc] -> Doc -- | The document stack ds concatenates the documents -- ds with line. stack :: [Doc] -> Doc -- | The document spread ds concatenates the documents -- ds with space. spread :: [Doc] -> Doc -- | The document folddoc f ds obeys the laws: -- -- folddoc :: (Doc -> Doc -> Doc) -> [Doc] -> Doc -- | The document parensIf p d encloses the document -- d in parenthesis if p is True, and -- otherwise yields just d. parensIf :: Bool -> Doc -> Doc -- | The document parens d encloses the aligned document -- d in (...). parens :: Doc -> Doc -- | The document brackets d encloses the aligned document -- d in [...]. brackets :: Doc -> Doc -- | The document braces d encloses the aligned document -- d in {...}. braces :: Doc -> Doc -- | The document backquotes d encloses the aligned -- document d in `...`. backquotes :: Doc -> Doc -- | The document angles d encloses the aligned document -- d in <...>. angles :: Doc -> Doc -- | The document dquotes d encloses the aligned document -- d in "...". dquotes :: Doc -> Doc -- | The document squotes d encloses the alinged document -- d in '...'. squotes :: Doc -> Doc -- | The document enclose l r d encloses the document -- d between the documents l and r using -- <>. It obeys the law -- --
-- enclose l r d = l <> d <> r --enclose :: Doc -> Doc -> Doc -> Doc -- | The document flatten d will flatten d to -- one line. flatten :: Doc -> Doc -- | The document group d will flatten d to -- one line if there is room for it, otherwise the original -- d. group :: Doc -> Doc -- | Provide alternative layouts of the same content. Invariant: both -- arguments must flatten to the same document. (<|>) :: Doc -> Doc -> Doc infixl 3 <|> -- | Concatenates two documents with a softbreak in between. (/>) :: Doc -> Doc -> Doc infixr 5 /> -- | Concatenates two documents with a softline in between, with -- identity empty. (<+/>) :: Doc -> Doc -> Doc infixr 5 <+/> -- | Concatenates two documents with a line in between, with -- identity empty. (>) :: Doc -> Doc -> Doc infixr 5 > -- | Concatenates two documents with a space in between, with -- identity empty. (<+>) :: Doc -> Doc -> Doc infixr 6 <+> -- | Becomes empty if there is room, otherwise line. softbreak :: Doc -- | Becomes space if there is room, otherwise line. -- --
-- pretty 11 $ text "foo" <+/> text "bar" <+/> text "baz" =="foo bar baz" -- pretty 7 $ text "foo" <+/> text "bar" <+/> text "baz" == "foo bar\nbaz" -- pretty 6 $ text "foo" <+/> text "bar" <+/> text "baz" == "foo\nbar\nbaz" --softline :: Doc -- | The document line advances to the next line and -- indents to the current indentation level. When undone by group, -- it behaves like space. line :: Doc -- | The document srcloc x tags the current line with -- locOf x. Only shown when running prettyPragma -- and friends. srcloc :: Located a => a -> Doc -- | The empty document. empty :: Doc -- | The document rparen consists of a right brace, ")". rparen :: Doc -- | The document lparen consists of a right brace, "(". lparen :: Doc -- | The document rbracket consists of a right brace, -- "]". rbracket :: Doc -- | The document lbracket consists of a right brace, -- "[". lbracket :: Doc -- | The document rbrace consists of a right brace, "}". rbrace :: Doc -- | The document lbrace consists of a left brace, "{". lbrace :: Doc -- | The document rangle consists of a greater-than sign, -- ">". rangle :: Doc -- | The document langle consists of a less-than sign, -- "<". langle :: Doc -- | The document dquote consists of a double quote, -- "\"". dquote :: Doc -- | The document squote consists of a single quote, -- "\'". squote :: Doc -- | The document backquote consists of a backquote, "`". backquote :: Doc -- | The document space n consists of n spaces. spaces :: Int -> Doc -- | The document space consists of a space, " ". space :: Doc -- | The document semi consists of a semicolon, ";". semi :: Doc -- | The document equals consists of an equals sign, "=". equals :: Doc -- | The document dot consists of a period, ".". dot :: Doc -- | The document comma consists of a comma, ",". comma :: Doc -- | The document colon consists of a colon, ":". colon :: Doc -- | The document star consists of an asterisk, "*". star :: Doc -- | The document lazyText s consists of the Text -- s, which should not contain any newlines. lazyText :: Text -> Doc -- | The document strictText s consists of the Text -- s, which should not contain any newlines. strictText :: Text -> Doc -- | The document rational r is equivalent to text (show -- r). rational :: Rational -> Doc -- | The document double d is equivalent to text (show -- d). double :: Double -> Doc -- | The document float f is equivalent to text (show f). float :: Float -> Doc -- | The document integer i is equivalent to text (show -- i). text. integer :: Integer -> Doc -- | The document int i is equivalent to text (show i). int :: Int -> Doc -- | The document string s consists of all the characters -- in s but with newlines replaced by line. string :: String -> Doc -- | The document char c consists the single character -- c. char :: Char -> Doc -- | The document bool b is equivalent to text (show b). bool :: Bool -> Doc -- | The document text s consists of the string s, -- which should not contain any newlines. For a string that may include -- newlines, use string. text :: String -> Doc -- | The abstract type of documents. data Doc -- | A rendered document. data RDoc -- | The empty document REmpty :: RDoc -- | A single character RChar :: {-# UNPACK #-} !Char -> RDoc -> RDoc -- | String with associated length (to avoid recomputation) RString :: {-# UNPACK #-} !Int -> String -> RDoc -> RDoc -- | Text RText :: Text -> RDoc -> RDoc -- | Text RLazyText :: Text -> RDoc -> RDoc -- | Tag output with source location RPos :: Pos -> RDoc -> RDoc -- | A newline with the indentation of the subsequent line. If this is -- followed by a RPos, output an appropriate #line pragma -- before the newline. RLine :: {-# UNPACK #-} !Int -> RDoc -> RDoc -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Re-export of pretty. prettyDoc :: Int -> Doc -> String -- | Prettyprint a list enclosed in curly braces. prettyTuple :: Pretty a => [a] -> String -- | Prettyprint a value to a Text, wrapped to 80 characters. prettyText :: Pretty a => a -> Text -- | Prettyprint a value to a Text without any width restriction. prettyTextOneLine :: Pretty a => a -> Text -- | Prettyprint a value without any width restriction. prettyOneLine :: Pretty a => a -> String -- | The document apply ds separates ds with -- commas and encloses them with parentheses. apply :: [Doc] -> Doc -- | Make sure that the given document is printed on just a single line. oneLine :: Doc -> Doc -- | Stack and prepend a list of Docs to another Doc, -- separated by a linebreak. If the list is empty, the second Doc -- will be returned without a preceding linebreak. annot :: [Doc] -> Doc -> Doc -- | Surround the given document with enclosers and add linebreaks and -- indents. nestedBlock :: String -> String -> Doc -> Doc -- | Like text, but splits the string into words and permits line -- breaks between all of them. textwrap :: String -> Doc -- | Prettyprint on a single line up to at most some appropriate number of -- characters, with trailing ... if necessary. Used for error messages. shorten :: Pretty a => a -> Doc -- | Like commasep, but a newline after every comma. commastack :: [Doc] -> Doc instance Text.PrettyPrint.Mainland.Class.Pretty Numeric.Half.Internal.Half -- | This module provides an efficient value representation as well as -- parsing and comparison functions. module Futhark.Test.Values -- | The structure of a compound value, parameterised over the actual -- values. For most cases you probably want CompoundValue. data Compound v ValueRecord :: Map Text (Compound v) -> Compound v -- | Must not be single value. ValueTuple :: [Compound v] -> Compound v ValueAtom :: v -> Compound v -- | Like a Value, but also grouped in compound ways that are not -- supported by raw values. You cannot parse or read these in standard -- ways, and they cannot be elements of arrays. type CompoundValue = Compound Value -- | Create a tuple for a non-unit list, and otherwise a ValueAtom mkCompound :: [Compound v] -> Compound v -- | If the value is a tuple, extract the components, otherwise return a -- singleton list of the value. unCompound :: Compound v -> [Compound v] instance GHC.Show.Show v => GHC.Show.Show (Futhark.Test.Values.Compound v) instance GHC.Classes.Ord v => GHC.Classes.Ord (Futhark.Test.Values.Compound v) instance GHC.Classes.Eq v => GHC.Classes.Eq (Futhark.Test.Values.Compound v) instance GHC.Base.Functor Futhark.Test.Values.Compound instance Data.Foldable.Foldable Futhark.Test.Values.Compound instance Data.Traversable.Traversable Futhark.Test.Values.Compound instance Text.PrettyPrint.Mainland.Class.Pretty v => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Test.Values.Compound v) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Data.Value instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Data.ValueType -- | FutharkScript is a (tiny) subset of Futhark used to write small -- expressions that are evaluated by server executables. The futhark -- literate command is the main user. module Futhark.Script -- | Like a Server, but keeps a bit more state to make FutharkScript -- more convenient. data ScriptServer -- | Start a server, execute an action, then shut down the server. Similar -- to withServer. withScriptServer :: ServerCfg -> (ScriptServer -> IO a) -> IO a -- | Run an action with a ScriptServer produced by an existing -- Server, without shutting it down at the end. withScriptServer' :: MonadIO m => Server -> (ScriptServer -> m a) -> m a -- | A function called in a Call expression can be either a Futhark -- function or a builtin function. data Func FuncFut :: EntryName -> Func FuncBuiltin :: Text -> Func -- | A FutharkScript expression. This is a simple AST that might not -- correspond exactly to what the user wrote (e.g. no parentheses or -- source locations). This is fine for small expressions, which is all -- this is meant for. data Exp Call :: Func -> [Exp] -> Exp Const :: Value -> Exp Tuple :: [Exp] -> Exp Record :: [(Text, Exp)] -> Exp StringLit :: Text -> Exp Let :: [VarName] -> Exp -> Exp -> Exp -- | Server-side variable, *not* Futhark variable (these are handled in -- Call). ServerVar :: TypeName -> VarName -> Exp -- | Parse a FutharkScript expression. parseExp :: Parser () -> Parser Exp -- | The set of Futhark variables that are referenced by the expression - -- these will have to be entry points in the Futhark program. varsInExp :: Exp -> Set EntryName -- | The type of a ScriptValue - either a value type or a function -- type. data ScriptValueType STValue :: TypeName -> ScriptValueType -- | Ins, then outs. STFun :: [TypeName] -> [TypeName] -> ScriptValueType -- | A ScriptValue is either a base value or a partially applied function. -- We don't have real first-class functions in FutharkScript, but we sort -- of have closures. data ScriptValue v SValue :: TypeName -> v -> ScriptValue v -- | Ins, then outs. Yes, this is the opposite of more or less everywhere -- else. SFun :: EntryName -> [TypeName] -> [TypeName] -> [ScriptValue v] -> ScriptValue v -- | The type of a ScriptValue. scriptValueType :: ScriptValue v -> ScriptValueType -- | The set of server-side variables in the value. serverVarsInValue :: ExpValue -> Set VarName -- | A Haskell-level value or a variable on the server. data ValOrVar VVal :: Value -> ValOrVar VVar :: VarName -> ValOrVar -- | The intermediate values produced by an expression - in particular, -- these may not be on the server. type ExpValue = Compound (ScriptValue ValOrVar) -- | How to evaluate a builtin function. type EvalBuiltin m = Text -> [CompoundValue] -> m CompoundValue -- | Evaluate a FutharkScript expression relative to some running server. evalExp :: forall m. (MonadError Text m, MonadIO m) => EvalBuiltin m -> ScriptServer -> Exp -> m ExpValue -- | Read actual values from the server. Fails for values that have no -- well-defined external representation. getExpValue :: (MonadError Text m, MonadIO m) => ScriptServer -> ExpValue -> m CompoundValue -- | Like evalExp, but requires all values to be non-functional. If -- the value has a bad type, return that type instead. Other evaluation -- problems (e.g. type failures) raise errors. evalExpToGround :: (MonadError Text m, MonadIO m) => EvalBuiltin m -> ScriptServer -> Exp -> m (Either (Compound ScriptValueType) CompoundValue) -- | Convert a value into a corresponding expression. valueToExp :: ExpValue -> Exp -- | Release all the server-side variables in the value. Yes, FutharkScript -- has manual memory management... freeValue :: (MonadError Text m, MonadIO m) => ScriptServer -> ExpValue -> m () instance GHC.Show.Show Futhark.Script.Func instance GHC.Show.Show Futhark.Script.Exp instance GHC.Show.Show v => GHC.Show.Show (Futhark.Script.ScriptValue v) instance GHC.Show.Show Futhark.Script.ScriptValueType instance GHC.Classes.Eq Futhark.Script.ScriptValueType instance GHC.Show.Show Futhark.Script.ValOrVar instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Script.ScriptValueType instance GHC.Base.Functor Futhark.Script.ScriptValue instance Data.Foldable.Foldable Futhark.Script.ScriptValue instance Data.Traversable.Traversable Futhark.Script.ScriptValue instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Script.Exp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Script.Func -- | Facilities for reading Futhark test programs. A Futhark test program -- is an ordinary Futhark program where an initial comment block -- specifies input- and output-sets. module Futhark.Test -- | Read the test specification from the given Futhark program. testSpecFromFile :: FilePath -> IO (Either String ProgramTest) -- | Like testSpecFromFile, but kills the process on error. testSpecFromFileOrDie :: FilePath -> IO ProgramTest -- | Read test specifications from the given paths, which can be a files or -- directories containing .fut files and further directories. testSpecsFromPaths :: [FilePath] -> IO (Either String [(FilePath, ProgramTest)]) -- | Like testSpecsFromPaths, but kills the process on errors. testSpecsFromPathsOrDie :: [FilePath] -> IO [(FilePath, ProgramTest)] -- | Try to parse a several values from a byte string. The String -- parameter is used for error messages. valuesFromByteString :: String -> ByteString -> Either String [Value] -- | The futhark executable we are using. This is merely a wrapper -- around the underlying file path, because we will be using a lot of -- different file paths here, and it is easy to mix them up. newtype FutharkExe FutharkExe :: FilePath -> FutharkExe -- | Get the actual core Futhark values corresponding to a Values -- specification. The first FilePath is the path of the -- futhark executable, and the second is the directory which -- file paths are read relative to. getValues :: (MonadFail m, MonadIO m) => FutharkExe -> FilePath -> Values -> m [Value] -- | Extract a pretty representation of some Values. In the IO monad -- because this might involve reading from a file. There is no guarantee -- that the resulting byte string yields a readable value. getValuesBS :: (MonadFail m, MonadIO m) => FutharkExe -> FilePath -> Values -> m ByteString -- | Make the provided Values available as server-side variables. -- This may involve arbitrary server-side computation. Error detection... -- dubious. valuesAsVars :: (MonadError Text m, MonadIO m) => Server -> [(VarName, TypeName)] -> FutharkExe -> FilePath -> Values -> m () -- | Compare two Futhark values for equality. compareValues :: Tolerance -> Value -> Value -> [Mismatch] -- | Check that the result is as expected, and write files and throw an -- error if not. checkResult :: (MonadError Text m, MonadIO m) => FilePath -> [Value] -> [Value] -> m () -- | When/if generating a reference output file for this run, what should -- it be called? Includes the "data/" folder. testRunReferenceOutput :: FilePath -> Text -> TestRun -> FilePath -- | Get the values corresponding to an expected result, if any. getExpectedResult :: (MonadFail m, MonadIO m) => FutharkExe -> FilePath -> Text -> TestRun -> m (ExpectedResult [Value]) -- | compileProgram extra_options futhark backend program compiles -- program with the command futhark backend -- extra-options..., and returns stdout and stderr of the compiler. -- Throws an IO exception containing stderr if compilation fails. compileProgram :: (MonadIO m, MonadError [Text] m) => [String] -> FutharkExe -> String -> FilePath -> m (ByteString, ByteString) -- | runProgram futhark runner extra_options prog entry input runs -- the Futhark program prog (which must have the .fut -- suffix), executing the entry entry point and providing -- input on stdin. The program must have been compiled in -- advance with compileProgram. If runner is non-null, -- then it is used as "interpreter" for the compiled program (e.g. -- python when using the Python backends). The -- extra_options are passed to the program. runProgram :: FutharkExe -> FilePath -> [String] -> String -> Text -> Values -> IO (ExitCode, ByteString, ByteString) -- | Read the given variables from a running server. readResults :: (MonadIO m, MonadError Text m) => Server -> [VarName] -> m [Value] -- | Ensure that any reference output files exist, or create them (by -- compiling the program with the reference compiler and running it on -- the input) if necessary. ensureReferenceOutput :: (MonadIO m, MonadError [Text] m) => Maybe Int -> FutharkExe -> String -> FilePath -> [InputOutputs] -> m () -- | Determine the --tuning options to pass to the program. The first -- argument is the extension of the tuning file, or Nothing if -- none should be used. determineTuning :: MonadIO m => Maybe FilePath -> FilePath -> m ([String], String) -- | The name we use for compiled programs. binaryName :: FilePath -> FilePath -- | Create a Futhark server configuration suitable for use when -- testing/benchmarking Futhark programs. futharkServerCfg :: FilePath -> [String] -> ServerCfg -- | Two values differ in some way. The Show instance produces a -- human-readable explanation. data Mismatch -- | Description of a test to be carried out on a Futhark program. The -- Futhark program is stored separately. data ProgramTest ProgramTest :: Text -> [Text] -> TestAction -> ProgramTest [testDescription] :: ProgramTest -> Text [testTags] :: ProgramTest -> [Text] [testAction] :: ProgramTest -> TestAction -- | A structure test specifies a compilation pipeline, as well as metrics -- for the program coming out the other end. data StructureTest StructureTest :: StructurePipeline -> AstMetrics -> StructureTest -- | How a program can be transformed. data StructurePipeline KernelsPipeline :: StructurePipeline SOACSPipeline :: StructurePipeline SequentialCpuPipeline :: StructurePipeline GpuPipeline :: StructurePipeline NoPipeline :: StructurePipeline -- | A warning test requires that a warning matching the regular expression -- is produced. The program must also compile succesfully. data WarningTest ExpectedWarning :: Text -> Regex -> WarningTest -- | How to test a program. data TestAction CompileTimeFailure :: ExpectedError -> TestAction RunCases :: [InputOutputs] -> [StructureTest] -> [WarningTest] -> TestAction -- | The error expected for a negative test. data ExpectedError AnyError :: ExpectedError ThisError :: Text -> Regex -> ExpectedError -- | Input and output pairs for some entry point(s). data InputOutputs InputOutputs :: Text -> [TestRun] -> InputOutputs [iosEntryPoint] :: InputOutputs -> Text [iosTestRuns] :: InputOutputs -> [TestRun] -- | A condition for execution, input, and expected result. data TestRun TestRun :: [String] -> Values -> ExpectedResult Success -> Int -> String -> TestRun [runTags] :: TestRun -> [String] [runInput] :: TestRun -> Values [runExpectedResult] :: TestRun -> ExpectedResult Success [runIndex] :: TestRun -> Int [runDescription] :: TestRun -> String -- | How a test case is expected to terminate. data ExpectedResult values -- | Execution suceeds, with or without expected result values. Succeeds :: Maybe values -> ExpectedResult values -- | Execution fails with this error. RunTimeFailure :: ExpectedError -> ExpectedResult values -- | The result expected from a succesful execution. data Success -- | These values are expected. SuccessValues :: Values -> Success -- | Compute expected values from executing a known-good reference -- implementation. SuccessGenerateValues :: Success -- | Several values - either literally, or by reference to a file, or to be -- generated on demand. All paths are relative to test program. data Values Values :: [Value] -> Values InFile :: FilePath -> Values GenValues :: [GenValue] -> Values ScriptValues :: Exp -> Values ScriptFile :: FilePath -> Values -- | An efficiently represented Futhark value, represented as a shape -- vector and a value vector, which contains elements in row-major order. -- The size of the value vector must be equal to the product of the shape -- vector. This is not enforced by the representation, but consuming -- functions may give unexpected results if this invariant is broken. -- Scalars are represented with an empty shape vector. -- -- Use valueText to get a human-readable representation, and -- put to obtain binary a representation. -- -- The Eq instance is the naive one, meaning that no values -- containing NaNs will be considered equal. Use the functions from -- Futhark.Data.Compare if this is not what you want. data Value -- | Construct a textual representation of the value as a strict text. valueText :: Value -> Text instance GHC.Show.Show Futhark.Test.StructurePipeline instance GHC.Show.Show Futhark.Test.StructureTest instance GHC.Show.Show Futhark.Test.GenValue instance GHC.Show.Show Futhark.Test.Values instance GHC.Show.Show values => GHC.Show.Show (Futhark.Test.ExpectedResult values) instance GHC.Show.Show Futhark.Test.Success instance GHC.Show.Show Futhark.Test.TestRun instance GHC.Show.Show Futhark.Test.InputOutputs instance GHC.Show.Show Futhark.Test.TestAction instance GHC.Show.Show Futhark.Test.ProgramTest instance GHC.Show.Show Futhark.Test.FutharkExe instance GHC.Classes.Ord Futhark.Test.FutharkExe instance GHC.Classes.Eq Futhark.Test.FutharkExe instance GHC.Show.Show Futhark.Test.WarningTest instance GHC.Show.Show Futhark.Test.ExpectedError -- | Facilities for handling Futhark benchmark results. A Futhark benchmark -- program is just like a Futhark test program. module Futhark.Bench -- | The runtime of a single succesful run. newtype RunResult RunResult :: Int -> RunResult [runMicroseconds] :: RunResult -> Int -- | The results for a single named dataset is either an error message, or -- runtime measurements, the number of bytes used, and the stderr that -- was produced. data DataResult DataResult :: String -> Either Text Result -> DataResult -- | The results for all datasets for some benchmark program. data BenchResult BenchResult :: FilePath -> [DataResult] -> BenchResult -- | The measurements resulting from various successful runs of a benchmark -- (same dataset). data Result Result :: [RunResult] -> Map Text Int -> Text -> Result [runResults] :: Result -> [RunResult] [memoryMap] :: Result -> Map Text Int [stdErr] :: Result -> Text -- | Transform benchmark results to a JSON bytestring. encodeBenchResults :: [BenchResult] -> ByteString -- | Decode benchmark results from a JSON bytestring. decodeBenchResults :: ByteString -> Either String [BenchResult] -- | The name we use for compiled programs. binaryName :: FilePath -> FilePath -- | Run the benchmark program on the indicated dataset. benchmarkDataset :: Server -> RunOptions -> FutharkExe -> FilePath -> Text -> Values -> Maybe Success -> FilePath -> IO (Either Text ([RunResult], Text)) -- | How to run a benchmark. data RunOptions RunOptions :: Int -> Int -> Int -> Maybe (Int -> IO ()) -> RunOptions [runRuns] :: RunOptions -> Int [runTimeout] :: RunOptions -> Int [runVerbose] :: RunOptions -> Int -- | Invoked for every runtime measured during the run. Can be used to -- provide a progress bar. [runResultAction] :: RunOptions -> Maybe (Int -> IO ()) -- | Compile and produce reference datasets. prepareBenchmarkProgram :: MonadIO m => Maybe Int -> CompileOptions -> FilePath -> [InputOutputs] -> m (Either (String, Maybe ByteString) ()) -- | How to compile a benchmark. data CompileOptions CompileOptions :: String -> String -> [String] -> CompileOptions [compFuthark] :: CompileOptions -> String [compBackend] :: CompileOptions -> String [compOptions] :: CompileOptions -> [String] instance GHC.Show.Show Futhark.Bench.RunResult instance GHC.Classes.Eq Futhark.Bench.RunResult instance GHC.Show.Show Futhark.Bench.Result instance GHC.Classes.Eq Futhark.Bench.Result instance GHC.Show.Show Futhark.Bench.DataResult instance GHC.Classes.Eq Futhark.Bench.DataResult instance GHC.Show.Show Futhark.Bench.BenchResult instance GHC.Classes.Eq Futhark.Bench.BenchResult instance Data.Aeson.Types.ToJSON.ToJSON Futhark.Bench.BenchResults instance Data.Aeson.Types.FromJSON.FromJSON Futhark.Bench.BenchResults instance Data.Aeson.Types.ToJSON.ToJSON Futhark.Bench.DataResults instance Data.Aeson.Types.FromJSON.FromJSON Futhark.Bench.DataResults instance Data.Aeson.Types.ToJSON.ToJSON Futhark.Bench.Result instance Data.Aeson.Types.FromJSON.FromJSON Futhark.Bench.Result instance Data.Aeson.Types.ToJSON.ToJSON Futhark.Bench.RunResult instance Data.Aeson.Types.FromJSON.FromJSON Futhark.Bench.RunResult -- | Definitions of primitive types, the values that inhabit these types, -- and operations on these values. A primitive value can also be called a -- scalar. -- -- Essentially, this module describes the subset of the (internal) -- Futhark language that operates on primitive types. module Futhark.IR.Primitive -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A floating point type. data FloatType Float16 :: FloatType Float32 :: FloatType Float64 :: FloatType -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType -- | An informationless type - still takes up space! Unit :: PrimType -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 data Half -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue -- | The type of an integer value. intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | A floating-point value. data FloatValue Float16Value :: !Half -> FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue -- | The type of a floating-point value. floatValueType :: FloatValue -> FloatType -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type Unit. UnitValue :: PrimValue -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | What to do in case of arithmetic overflow. Futhark's semantics are -- that overflow does wraparound, but for generated code (like address -- arithmetic), it can be beneficial for overflow to be undefined -- behaviour, as it allows better optimisation of things such as GPU -- kernels. -- -- Note that all values of this type are considered equal for Eq -- and Ord. data Overflow OverflowWrap :: Overflow OverflowUndef :: Overflow -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. -- -- For operations like integer division, a safe division will not explode -- the computer in case of division by zero, but instead return some -- unspecified value. This always involves a run-time check, so generally -- the unsafe variant is what the compiler will insert, but guarded by an -- explicit assertion elsewhere. Safe operations are useful when the -- optimiser wants to move e.g. a division to a location where the -- divisor may be zero, but where the result will only be used when it is -- non-zero (so it doesn't matter what result is provided with a zero -- divisor, as long as the program keeps running). data Safety Unsafe :: Safety Safe :: Safety -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Floating-point sign function. FSignum :: FloatType -> UnOp -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> Overflow -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> Overflow -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> Overflow -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> Safety -> BinOp -- | Unsigned integer division. Rounds towards positive infinity. UDivUp :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards positive infinity. SDivUp :: IntType -> Safety -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Floating-point modulus. FMod :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> Safety -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM and integer division in C. SQuot :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM and integer modulo in C. SRem :: IntType -> Safety -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] -- | Comparison operators are like BinOps, but they always return a -- boolean value. The somewhat ugly constructor names are straight out of -- LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | Apply an UnOp to an operand. Returns Nothing if the -- application is mistyped. doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue -- | Apply a BinOp to an operand. Returns Nothing if the -- application is mistyped, or outside the domain (e.g. division by -- zero). doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue -- | Apply a ConvOp to an operand. Returns Nothing if the -- application is mistyped. doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue -- | Translate an IntValue to Int64. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Turn the conversion the other way around. Note that most conversions -- are lossy, so there is no guarantee the value will round-trip. flipConvOp :: ConvOp -> ConvOp -- | Apply a CmpOp to an operand. Returns Nothing if the -- application is mistyped. doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given integer value kind of zero? zeroIshInt :: IntValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given integer value kind of one? oneIshInt :: IntValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | The size of a value of a given integer type in eight-bit bytes. intByteSize :: Num a => IntType -> a -- | The size of a value of a given floating-point type in eight-bit bytes. floatByteSize :: Num a => FloatType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool -- | The human-readable name for a ConvOp. This is used to expose -- the ConvOp in the intrinsics module of a Futhark -- program. convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String instance GHC.Enum.Bounded Futhark.IR.Primitive.IntType instance GHC.Enum.Enum Futhark.IR.Primitive.IntType instance GHC.Show.Show Futhark.IR.Primitive.IntType instance GHC.Classes.Ord Futhark.IR.Primitive.IntType instance GHC.Classes.Eq Futhark.IR.Primitive.IntType instance GHC.Enum.Bounded Futhark.IR.Primitive.FloatType instance GHC.Enum.Enum Futhark.IR.Primitive.FloatType instance GHC.Show.Show Futhark.IR.Primitive.FloatType instance GHC.Classes.Ord Futhark.IR.Primitive.FloatType instance GHC.Classes.Eq Futhark.IR.Primitive.FloatType instance GHC.Show.Show Futhark.IR.Primitive.PrimType instance GHC.Classes.Ord Futhark.IR.Primitive.PrimType instance GHC.Classes.Eq Futhark.IR.Primitive.PrimType instance GHC.Show.Show Futhark.IR.Primitive.IntValue instance GHC.Classes.Ord Futhark.IR.Primitive.IntValue instance GHC.Classes.Eq Futhark.IR.Primitive.IntValue instance GHC.Show.Show Futhark.IR.Primitive.FloatValue instance GHC.Show.Show Futhark.IR.Primitive.PrimValue instance GHC.Classes.Ord Futhark.IR.Primitive.PrimValue instance GHC.Classes.Eq Futhark.IR.Primitive.PrimValue instance GHC.Show.Show Futhark.IR.Primitive.UnOp instance GHC.Classes.Ord Futhark.IR.Primitive.UnOp instance GHC.Classes.Eq Futhark.IR.Primitive.UnOp instance GHC.Show.Show Futhark.IR.Primitive.Overflow instance GHC.Show.Show Futhark.IR.Primitive.Safety instance GHC.Classes.Ord Futhark.IR.Primitive.Safety instance GHC.Classes.Eq Futhark.IR.Primitive.Safety instance GHC.Show.Show Futhark.IR.Primitive.BinOp instance GHC.Classes.Ord Futhark.IR.Primitive.BinOp instance GHC.Classes.Eq Futhark.IR.Primitive.BinOp instance GHC.Show.Show Futhark.IR.Primitive.CmpOp instance GHC.Classes.Ord Futhark.IR.Primitive.CmpOp instance GHC.Classes.Eq Futhark.IR.Primitive.CmpOp instance GHC.Show.Show Futhark.IR.Primitive.ConvOp instance GHC.Classes.Ord Futhark.IR.Primitive.ConvOp instance GHC.Classes.Eq Futhark.IR.Primitive.ConvOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.ConvOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.CmpOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.BinOp instance GHC.Classes.Eq Futhark.IR.Primitive.Overflow instance GHC.Classes.Ord Futhark.IR.Primitive.Overflow instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.UnOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.PrimValue instance GHC.Classes.Eq Futhark.IR.Primitive.FloatValue instance GHC.Classes.Ord Futhark.IR.Primitive.FloatValue instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.FloatValue instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.IntValue instance GHC.Enum.Enum Futhark.IR.Primitive.PrimType instance GHC.Enum.Bounded Futhark.IR.Primitive.PrimType instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.PrimType instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.FloatType instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Primitive.IntType module Futhark.IR.Primitive.Parse -- | Defined in this module for convenience. pPrimValue :: Parser PrimValue pPrimType :: Parser PrimType pFloatType :: Parser FloatType pIntType :: Parser IntType constituent :: Char -> Bool lexeme :: Parser a -> Parser a keyword :: Text -> Parser () whitespace :: Parser () -- | Futhark error definitions. module Futhark.Error -- | A compiler error. data CompilerError -- | An error that happened due to something the user did, such as provide -- incorrect code or options. ExternalError :: Doc -> CompilerError -- | An internal compiler error. The second text is extra data for -- debugging, which can be written to a file. InternalError :: Text -> Text -> ErrorClass -> CompilerError -- | There are two classes of internal errors: actual bugs, and -- implementation limitations. The latter are already known and need not -- be reported. data ErrorClass CompilerBug :: ErrorClass CompilerLimitation :: ErrorClass -- | Raise an ExternalError based on a prettyprinting result. externalError :: MonadError CompilerError m => Doc -> m a -- | Raise an ExternalError based on a string. externalErrorS :: MonadError CompilerError m => String -> m a -- | An error that is not the users fault, but a bug (or limitation) in the -- compiler. Compiler passes should only ever report this error - any -- problems after the type checker are *our* fault, not the users. These -- are generally thrown as IO exceptions, and caught at the top level. data InternalError Error :: ErrorClass -> Text -> InternalError -- | Throw an InternalError that is a CompilerBug. compilerBug :: Text -> a -- | Like compilerBug, but with a String. compilerBugS :: String -> a -- | Throw an InternalError that is a CompilerLimitation. compilerLimitation :: Text -> a -- | Like compilerLimitation, but with a String. compilerLimitationS :: String -> a -- | Raise an InternalError based on a prettyprinting result. internalErrorS :: MonadError CompilerError m => String -> Doc -> m a instance GHC.Show.Show Futhark.Error.ErrorClass instance GHC.Classes.Ord Futhark.Error.ErrorClass instance GHC.Classes.Eq Futhark.Error.ErrorClass instance GHC.Show.Show Futhark.Error.InternalError instance GHC.Exception.Type.Exception Futhark.Error.InternalError instance GHC.Show.Show Futhark.Error.CompilerError -- | Basic table building for prettier futhark-test output. module Futhark.Util.Table -- | Builds a table from a list of entries and a padding amount that -- determines padding from the right side of the widest entry in each -- column. buildTable :: [[Entry]] -> Int -> String -- | Makes a table entry with the default SGR mode. mkEntry :: String -> (String, [SGR]) -- | A table entry. Consists of the content as well a list of SGR commands -- to color/stylelize the entry. type Entry = (String, [SGR]) instance GHC.Show.Show Futhark.Util.Table.RowTemplate -- | This module contains very basic definitions for Futhark - so basic, -- that they can be shared between the internal and external -- representation. module Language.Futhark.Core -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | Source location type. Source location are all equal, which allows AST -- nodes to be compared modulo location information. data SrcLoc -- | Location type, consisting of a beginning position and an end position. data Loc -- | Located values have a location. class Located a locOf :: Located a => a -> Loc locOfList :: Located a => [a] -> Loc -- | The SrcLoc of a Located value. srclocOf :: Located a => a -> SrcLoc -- | A human-readable location string, of the form -- filename:lineno:columnno. This follows the GNU coding -- standards for error messages: -- https://www.gnu.org/prep/standards/html_node/Errors.html -- -- This function assumes that both start and end position is in the same -- file (it is not clear what the alternative would even mean). locStr :: Located a => a -> String -- | Like locStr, but locStrRel prev now prints the -- location now with the file name left out if the same as -- prev. This is useful when printing messages that are all in -- the context of some initially printed location (e.g. the first mention -- contains the file name; the rest just line and column name). locStrRel :: (Located a, Located b) => a -> b -> String -- | Given a list of strings representing entries in the stack trace and -- the index of the frame to highlight, produce a final -- newline-terminated string for showing to the user. This string should -- also be preceded by a newline. The most recent stack frame must come -- first in the list. prettyStacktrace :: Int -> [String] -> String -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | Enclose a string in the prefered quotes used in error messages. These -- are picked to not collide with characters permitted in identifiers. quote :: String -> String -- | As quote, but works on prettyprinted representation. pquote :: Doc -> Doc -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 data Half instance GHC.Show.Show Language.Futhark.Core.Uniqueness instance GHC.Classes.Ord Language.Futhark.Core.Uniqueness instance GHC.Classes.Eq Language.Futhark.Core.Uniqueness instance GHC.Base.Semigroup Language.Futhark.Core.Name instance Data.String.IsString Language.Futhark.Core.Name instance GHC.Classes.Ord Language.Futhark.Core.Name instance GHC.Classes.Eq Language.Futhark.Core.Name instance GHC.Show.Show Language.Futhark.Core.Name instance GHC.Show.Show Language.Futhark.Core.VName instance GHC.Classes.Eq Language.Futhark.Core.VName instance GHC.Classes.Ord Language.Futhark.Core.VName instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.Name instance GHC.Base.Semigroup Language.Futhark.Core.Uniqueness instance GHC.Base.Monoid Language.Futhark.Core.Uniqueness instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.Uniqueness -- | The most primitive ("core") aspects of the AST. Split out of -- Futhark.IR.Syntax in order for Futhark.IR.Rep to use -- these definitions. This module is re-exported from -- Futhark.IR.Syntax and there should be no reason to include it -- explicitly. module Futhark.IR.Syntax.Core -- | Whether some operator is commutative or not. The Monoid -- instance returns the least commutative of its arguments. data Commutativity Noncommutative :: Commutativity Commutative :: Commutativity -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | A fancier name for () - encodes no uniqueness information. data NoUniqueness NoUniqueness :: NoUniqueness -- | The size of an array type as a list of its dimension sizes, with the -- type of sizes being parametric. newtype ShapeBase d Shape :: [d] -> ShapeBase d [shapeDims] :: ShapeBase d -> [d] -- | The size of an array as a list of subexpressions. If a variable, that -- variable must be in scope where this array is used. type Shape = ShapeBase SubExp -- | Something that may be existential. data Ext a Ext :: Int -> Ext a Free :: a -> Ext a -- | The size of this dimension. type ExtSize = Ext SubExp -- | Like Shape but some of its elements may be bound in a local -- environment instead. These are denoted with integral indices. type ExtShape = ShapeBase ExtSize -- | The size of an array type as merely the number of dimensions, with no -- further information. newtype Rank Rank :: Int -> Rank -- | A class encompassing types containing array shape information. class (Monoid a, Eq a, Ord a) => ArrayShape a -- | Return the rank of an array with the given size. shapeRank :: ArrayShape a => a -> Int -- | stripDims n shape strips the outer n dimensions from -- shape. stripDims :: ArrayShape a => Int -> a -> a -- | Check whether one shape if a subset of another shape. subShapeOf :: ArrayShape a => a -> a -> Bool -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceId depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A special kind of memory that is a statically sized array of some -- primitive type. Used for private memory on GPUs. ScalarSpace :: [SubExp] -> PrimType -> Space -- | A string representing a specific non-default memory space. type SpaceId = String -- | The type of a value. When comparing types for equality with ==, -- shapes must match. data TypeBase shape u Prim :: PrimType -> TypeBase shape u -- | Token, index space, element type, and uniqueness. Acc :: VName -> Shape -> [Type] -> u -> TypeBase shape u Array :: PrimType -> shape -> u -> TypeBase shape u Mem :: Space -> TypeBase shape u -- | A type with shape information, used for describing the type of -- variables. type Type = TypeBase Shape NoUniqueness -- | A type with existentially quantified shapes - used as part of function -- (and function-like) return types. Generally only makes sense when used -- in a list. type ExtType = TypeBase ExtShape NoUniqueness -- | A type with shape and uniqueness information, used declaring return- -- and parameters types. type DeclType = TypeBase Shape Uniqueness -- | An ExtType with uniqueness information, used for function -- return types. type DeclExtType = TypeBase ExtShape Uniqueness -- | Information about which parts of a value/type are consumed. For -- example, we might say that a function taking three arguments of types -- ([int], *[int], [int]) has diet [Observe, Consume, -- Observe]. data Diet -- | Consumes this value. Consume :: Diet -- | Only observes value in this position, does not consume. A result may -- alias this. Observe :: Diet -- | As Observe, but the result will not alias, because the -- parameter does not carry aliases. ObservePrim :: Diet -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time value. ErrorVal :: PrimType -> a -> ErrorMsgPart a -- | How many non-constant parts does the error message have, and what is -- their type? errorMsgArgTypes :: ErrorMsg a -> [PrimType] -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type Unit. UnitValue :: PrimValue -- | An identifier consists of its name and the type of the value bound to -- the identifier. data Ident Ident :: VName -> Type -> Ident [identName] :: Ident -> VName [identType] :: Ident -> Type -- | A list of names used for certificates in some expressions. newtype Certs Certs :: [VName] -> Certs [unCerts] :: Certs -> [VName] -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A function or lambda parameter. data Param dec Param :: VName -> dec -> Param dec -- | Name of the parameter. [paramName] :: Param dec -> VName -- | Function parameter decoration. [paramDec] :: Param dec -> dec -- | How to index a single dimension of an array. data DimIndex d -- | Fix index in this dimension. DimFix :: d -> DimIndex d -- | DimSlice start_offset num_elems stride. DimSlice :: d -> d -> d -> DimIndex d -- | A list of DimIndexs, indicating how an array should be sliced. -- Whenever a function accepts a Slice, that slice should be -- total, i.e, cover all dimensions of the array. Deviators should be -- indicated by taking a list of DimIndexes instead. newtype Slice d Slice :: [DimIndex d] -> Slice d [unSlice] :: Slice d -> [DimIndex d] -- | If the argument is a DimFix, return its component. dimFix :: DimIndex d -> Maybe d -- | If the slice is all DimFixs, return the components. sliceIndices :: Slice d -> Maybe [d] -- | The dimensions of the array produced by this slice. sliceDims :: Slice d -> [d] -- | A slice with a stride of one. unitSlice :: Num d => d -> d -> DimIndex d -- | Fix the DimSlices of a slice. The number of indexes must equal -- the length of sliceDims for the slice. fixSlice :: Num d => Slice d -> [d] -> [d] -- | Further slice the DimSlices of a slice. The number of slices -- must equal the length of sliceDims for the slice. sliceSlice :: Num d => Slice d -> Slice d -> Slice d -- | An element of a pattern - consisting of a name and an addditional -- parametric decoration. This decoration is what is expected to contain -- the type of the resulting variable. data PatElemT dec PatElem :: VName -> dec -> PatElemT dec -- | The name being bound. [patElemName] :: PatElemT dec -> VName -- | Pat element decoration. [patElemDec] :: PatElemT dec -> dec data FlatSlice d FlatSlice :: d -> [FlatDimIndex d] -> FlatSlice d data FlatDimIndex d FlatDimIndex :: d -> d -> FlatDimIndex d flatSliceDims :: FlatSlice d -> [d] flatSliceStrides :: FlatSlice d -> [d] instance GHC.Show.Show Futhark.IR.Syntax.Core.Commutativity instance GHC.Classes.Ord Futhark.IR.Syntax.Core.Commutativity instance GHC.Classes.Eq Futhark.IR.Syntax.Core.Commutativity instance GHC.Show.Show d => GHC.Show.Show (Futhark.IR.Syntax.Core.ShapeBase d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.IR.Syntax.Core.ShapeBase d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.IR.Syntax.Core.ShapeBase d) instance GHC.Show.Show a => GHC.Show.Show (Futhark.IR.Syntax.Core.Ext a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Futhark.IR.Syntax.Core.Ext a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Futhark.IR.Syntax.Core.Ext a) instance GHC.Classes.Ord Futhark.IR.Syntax.Core.Rank instance GHC.Classes.Eq Futhark.IR.Syntax.Core.Rank instance GHC.Show.Show Futhark.IR.Syntax.Core.Rank instance GHC.Show.Show Futhark.IR.Syntax.Core.NoUniqueness instance GHC.Classes.Ord Futhark.IR.Syntax.Core.NoUniqueness instance GHC.Classes.Eq Futhark.IR.Syntax.Core.NoUniqueness instance GHC.Show.Show Futhark.IR.Syntax.Core.Diet instance GHC.Classes.Ord Futhark.IR.Syntax.Core.Diet instance GHC.Classes.Eq Futhark.IR.Syntax.Core.Diet instance GHC.Show.Show Futhark.IR.Syntax.Core.Certs instance GHC.Classes.Ord Futhark.IR.Syntax.Core.Certs instance GHC.Classes.Eq Futhark.IR.Syntax.Core.Certs instance GHC.Classes.Ord Futhark.IR.Syntax.Core.SubExp instance GHC.Classes.Eq Futhark.IR.Syntax.Core.SubExp instance GHC.Show.Show Futhark.IR.Syntax.Core.SubExp instance GHC.Classes.Ord Futhark.IR.Syntax.Core.Space instance GHC.Classes.Eq Futhark.IR.Syntax.Core.Space instance GHC.Show.Show Futhark.IR.Syntax.Core.Space instance (GHC.Classes.Ord u, GHC.Classes.Ord shape) => GHC.Classes.Ord (Futhark.IR.Syntax.Core.TypeBase shape u) instance (GHC.Classes.Eq u, GHC.Classes.Eq shape) => GHC.Classes.Eq (Futhark.IR.Syntax.Core.TypeBase shape u) instance (GHC.Show.Show u, GHC.Show.Show shape) => GHC.Show.Show (Futhark.IR.Syntax.Core.TypeBase shape u) instance GHC.Show.Show Futhark.IR.Syntax.Core.Ident instance GHC.Classes.Eq dec => GHC.Classes.Eq (Futhark.IR.Syntax.Core.Param dec) instance GHC.Show.Show dec => GHC.Show.Show (Futhark.IR.Syntax.Core.Param dec) instance GHC.Classes.Ord dec => GHC.Classes.Ord (Futhark.IR.Syntax.Core.Param dec) instance GHC.Show.Show d => GHC.Show.Show (Futhark.IR.Syntax.Core.DimIndex d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.IR.Syntax.Core.DimIndex d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.IR.Syntax.Core.DimIndex d) instance GHC.Show.Show d => GHC.Show.Show (Futhark.IR.Syntax.Core.Slice d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.IR.Syntax.Core.Slice d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.IR.Syntax.Core.Slice d) instance GHC.Show.Show d => GHC.Show.Show (Futhark.IR.Syntax.Core.FlatDimIndex d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.IR.Syntax.Core.FlatDimIndex d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.IR.Syntax.Core.FlatDimIndex d) instance GHC.Show.Show d => GHC.Show.Show (Futhark.IR.Syntax.Core.FlatSlice d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.IR.Syntax.Core.FlatSlice d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.IR.Syntax.Core.FlatSlice d) instance GHC.Classes.Eq dec => GHC.Classes.Eq (Futhark.IR.Syntax.Core.PatElemT dec) instance GHC.Show.Show dec => GHC.Show.Show (Futhark.IR.Syntax.Core.PatElemT dec) instance GHC.Classes.Ord dec => GHC.Classes.Ord (Futhark.IR.Syntax.Core.PatElemT dec) instance GHC.Show.Show a => GHC.Show.Show (Futhark.IR.Syntax.Core.ErrorMsgPart a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Futhark.IR.Syntax.Core.ErrorMsgPart a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Futhark.IR.Syntax.Core.ErrorMsgPart a) instance GHC.Show.Show a => GHC.Show.Show (Futhark.IR.Syntax.Core.ErrorMsg a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Futhark.IR.Syntax.Core.ErrorMsg a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Futhark.IR.Syntax.Core.ErrorMsg a) instance Data.String.IsString (Futhark.IR.Syntax.Core.ErrorMsg a) instance GHC.Base.Functor Futhark.IR.Syntax.Core.ErrorMsg instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.ErrorMsg instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.ErrorMsg instance Data.String.IsString (Futhark.IR.Syntax.Core.ErrorMsgPart a) instance GHC.Base.Functor Futhark.IR.Syntax.Core.ErrorMsgPart instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.ErrorMsgPart instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.ErrorMsgPart instance GHC.Base.Functor Futhark.IR.Syntax.Core.PatElemT instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.PatElemT instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.PatElemT instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.FlatSlice instance GHC.Base.Functor Futhark.IR.Syntax.Core.FlatSlice instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.FlatSlice instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.FlatDimIndex instance GHC.Base.Functor Futhark.IR.Syntax.Core.FlatDimIndex instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.FlatDimIndex instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.Slice instance GHC.Base.Functor Futhark.IR.Syntax.Core.Slice instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.Slice instance GHC.Base.Functor Futhark.IR.Syntax.Core.DimIndex instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.DimIndex instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.DimIndex instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.Param instance GHC.Base.Functor Futhark.IR.Syntax.Core.Param instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.Param instance GHC.Classes.Eq Futhark.IR.Syntax.Core.Ident instance GHC.Classes.Ord Futhark.IR.Syntax.Core.Ident instance Data.Bitraversable.Bitraversable Futhark.IR.Syntax.Core.TypeBase instance Data.Bifunctor.Bifunctor Futhark.IR.Syntax.Core.TypeBase instance Data.Bifoldable.Bifoldable Futhark.IR.Syntax.Core.TypeBase instance Futhark.IR.Syntax.Core.ArrayShape (Futhark.IR.Syntax.Core.ShapeBase Futhark.IR.Syntax.Core.ExtSize) instance Futhark.IR.Syntax.Core.ArrayShape (Futhark.IR.Syntax.Core.ShapeBase Futhark.IR.Syntax.Core.SubExp) instance GHC.Base.Semigroup Futhark.IR.Syntax.Core.Certs instance GHC.Base.Monoid Futhark.IR.Syntax.Core.Certs instance GHC.Base.Semigroup Futhark.IR.Syntax.Core.NoUniqueness instance GHC.Base.Monoid Futhark.IR.Syntax.Core.NoUniqueness instance Futhark.IR.Syntax.Core.ArrayShape Futhark.IR.Syntax.Core.Rank instance GHC.Base.Semigroup Futhark.IR.Syntax.Core.Rank instance GHC.Base.Monoid Futhark.IR.Syntax.Core.Rank instance GHC.Base.Functor Futhark.IR.Syntax.Core.Ext instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.Ext instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.Ext instance GHC.Base.Functor Futhark.IR.Syntax.Core.ShapeBase instance Data.Foldable.Foldable Futhark.IR.Syntax.Core.ShapeBase instance Data.Traversable.Traversable Futhark.IR.Syntax.Core.ShapeBase instance GHC.Base.Semigroup (Futhark.IR.Syntax.Core.ShapeBase d) instance GHC.Base.Monoid (Futhark.IR.Syntax.Core.ShapeBase d) instance GHC.Base.Semigroup Futhark.IR.Syntax.Core.Commutativity instance GHC.Base.Monoid Futhark.IR.Syntax.Core.Commutativity -- | Possibly convenient facilities for constructing constants. module Futhark.IR.Prop.Constants -- | If a Haskell type is an instance of IsValue, it means that a -- value of that type can be converted to a Futhark PrimValue. -- This is intended to cut down on boilerplate when writing compiler code -- - for example, you'll quickly grow tired of writing Constant -- (LogVal True) loc. class IsValue a value :: IsValue a => a -> PrimValue -- | Create a Constant SubExp containing the given value. constant :: IsValue v => v -> SubExp -- | Utility definition for reasons of type ambiguity. intConst :: IntType -> Integer -> SubExp -- | Utility definition for reasons of type ambiguity. floatConst :: FloatType -> Double -> SubExp instance Futhark.IR.Prop.Constants.IsValue GHC.Int.Int8 instance Futhark.IR.Prop.Constants.IsValue GHC.Int.Int16 instance Futhark.IR.Prop.Constants.IsValue GHC.Int.Int32 instance Futhark.IR.Prop.Constants.IsValue GHC.Int.Int64 instance Futhark.IR.Prop.Constants.IsValue GHC.Word.Word8 instance Futhark.IR.Prop.Constants.IsValue GHC.Word.Word16 instance Futhark.IR.Prop.Constants.IsValue GHC.Word.Word32 instance Futhark.IR.Prop.Constants.IsValue GHC.Word.Word64 instance Futhark.IR.Prop.Constants.IsValue GHC.Types.Double instance Futhark.IR.Prop.Constants.IsValue GHC.Types.Float instance Futhark.IR.Prop.Constants.IsValue GHC.Types.Bool instance Futhark.IR.Prop.Constants.IsValue Futhark.IR.Primitive.PrimValue instance Futhark.IR.Prop.Constants.IsValue Futhark.IR.Primitive.IntValue instance Futhark.IR.Prop.Constants.IsValue Futhark.IR.Primitive.FloatValue -- | Functions for inspecting and constructing various types. module Futhark.IR.Prop.Types -- | Remove shape information from a type. rankShaped :: ArrayShape shape => TypeBase shape u -> TypeBase Rank u -- | Return the dimensionality of a type. For non-arrays, this is zero. For -- a one-dimensional array it is one, for a two-dimensional it is two, -- and so forth. arrayRank :: ArrayShape shape => TypeBase shape u -> Int -- | Return the shape of a type - for non-arrays, this is the -- mempty. arrayShape :: ArrayShape shape => TypeBase shape u -> shape -- | Set the shape of an array. If the given type is not an array, return -- the type unchanged. setArrayShape :: ArrayShape newshape => TypeBase oldshape u -> newshape -> TypeBase newshape u -- | True if the given type has a dimension that is existentially sized. existential :: ExtType -> Bool -- | Return the uniqueness of a type. uniqueness :: TypeBase shape Uniqueness -> Uniqueness -- | unique t is True if the type of the argument is -- unique. unique :: TypeBase shape Uniqueness -> Bool -- | Convert types with non-existential shapes to types with -- non-existential shapes. Only the representation is changed, so all the -- shapes will be Free. staticShapes :: [TypeBase Shape u] -> [TypeBase ExtShape u] -- | As staticShapes, but on a single type. staticShapes1 :: TypeBase Shape u -> TypeBase ExtShape u -- | A type is a primitive type if it is not an array or memory block. primType :: TypeBase shape u -> Bool -- | arrayOf t s u constructs an array type. The convenience -- compared to using the Array constructor directly is that -- t can itself be an array. If t is an -- n-dimensional array, and s is a list of length -- n, the resulting type is of an n+m dimensions. The -- uniqueness of the new array will be u, no matter the -- uniqueness of t. If the shape s has rank 0, then the -- t will be returned, although if it is an array, with the -- uniqueness changed to u. arrayOf :: ArrayShape shape => TypeBase shape u_unused -> shape -> u -> TypeBase shape u -- | Construct an array whose rows are the given type, and the outer size -- is the given dimension. This is just a convenient wrapper around -- arrayOf. arrayOfRow :: ArrayShape (ShapeBase d) => TypeBase (ShapeBase d) NoUniqueness -> d -> TypeBase (ShapeBase d) NoUniqueness -- | Construct an array whose rows are the given type, and the outer size -- is the given Shape. This is just a convenient wrapper around -- arrayOf. arrayOfShape :: Type -> Shape -> Type -- | Replace the size of the outermost dimension of an array. If the given -- type is not an array, it is returned unchanged. setOuterSize :: ArrayShape (ShapeBase d) => TypeBase (ShapeBase d) u -> d -> TypeBase (ShapeBase d) u -- | Replace the size of the given dimension of an array. If the given type -- is not an array, it is returned unchanged. setDimSize :: ArrayShape (ShapeBase d) => Int -> TypeBase (ShapeBase d) u -> d -> TypeBase (ShapeBase d) u -- | Replace the outermost dimension of an array shape. setOuterDim :: ShapeBase d -> d -> ShapeBase d -- | Replace the specified dimension of an array shape. setDim :: Int -> ShapeBase d -> d -> ShapeBase d -- | Set the dimensions of an array. If the given type is not an array, -- return the type unchanged. setArrayDims :: TypeBase oldshape u -> [SubExp] -> TypeBase Shape u -- | peelArray n t returns the type resulting from peeling the -- first n array dimensions from t. Returns -- Nothing if t has less than n dimensions. peelArray :: ArrayShape shape => Int -> TypeBase shape u -> Maybe (TypeBase shape u) -- | stripArray n t removes the n outermost layers of the -- array. Essentially, it is the type of indexing an array of type -- t with n indexes. stripArray :: ArrayShape shape => Int -> TypeBase shape u -> TypeBase shape u -- | Return the dimensions of a type - for non-arrays, this is the empty -- list. arrayDims :: TypeBase Shape u -> [SubExp] -- | Return the existential dimensions of a type - for non-arrays, this is -- the empty list. arrayExtDims :: TypeBase ExtShape u -> [ExtSize] -- | Return the size of the given dimension. If the dimension does not -- exist, the zero constant is returned. shapeSize :: Int -> Shape -> SubExp -- | Return the size of the given dimension. If the dimension does not -- exist, the zero constant is returned. arraySize :: Int -> TypeBase Shape u -> SubExp -- | Return the size of the given dimension in the first element of the -- given type list. If the dimension does not exist, or no types are -- given, the zero constant is returned. arraysSize :: Int -> [TypeBase Shape u] -> SubExp -- | Returns the bottommost type of an array. For [][]i32, this -- would be i32. If the given type is not an array, it is -- returned. elemType :: TypeBase shape u -> PrimType -- | Return the immediate row-type of an array. For [[int]], this -- would be [int]. rowType :: ArrayShape shape => TypeBase shape u -> TypeBase shape u -- | Swap the two outer dimensions of the type. transposeType :: Type -> Type -- | Rearrange the dimensions of the type. If the length of the permutation -- does not match the rank of the type, the permutation will be extended -- with identity. rearrangeType :: [Int] -> Type -> Type -- | Transform any SubExps in the type. mapOnExtType :: Monad m => (SubExp -> m SubExp) -> TypeBase ExtShape u -> m (TypeBase ExtShape u) -- | Transform any SubExps in the type. mapOnType :: Monad m => (SubExp -> m SubExp) -> TypeBase Shape u -> m (TypeBase Shape u) -- | diet t returns a description of how a function parameter of -- type t might consume its argument. diet :: TypeBase shape Uniqueness -> Diet -- | x `subtypeOf` y is true if x is a subtype of -- y (or equal to y), meaning x is valid -- whenever y is. subtypeOf :: (Ord u, ArrayShape shape) => TypeBase shape u -> TypeBase shape u -> Bool -- | xs `subtypesOf` ys is true if xs is the same size as -- ys, and each element in xs is a subtype of the -- corresponding element in ys.. subtypesOf :: (Ord u, ArrayShape shape) => [TypeBase shape u] -> [TypeBase shape u] -> Bool -- | Add the given uniqueness information to the types. toDecl :: TypeBase shape NoUniqueness -> Uniqueness -> TypeBase shape Uniqueness -- | Remove uniqueness information from the type. fromDecl :: TypeBase shape Uniqueness -> TypeBase shape NoUniqueness -- | If an existential, then return its existential index. isExt :: Ext a -> Maybe Int -- | If a known size, then return that size. isFree :: Ext a -> Maybe a -- | Given the existential return type of a function, and the shapes of the -- values returned by the function, return the existential shape context. -- That is, those sizes that are existential in the return type. extractShapeContext :: [TypeBase ExtShape u] -> [[a]] -> [a] -- | The Ext integers used for existential sizes in the given types. shapeContext :: [TypeBase ExtShape u] -> Set Int -- | If all dimensions of the given ExtShape are statically known, -- change to the corresponding Shape. hasStaticShape :: TypeBase ExtShape u -> Maybe (TypeBase Shape u) -- | Given two lists of ExtTypes of the same length, return a list -- of ExtTypes that is a subtype of the two operands. generaliseExtTypes :: [TypeBase ExtShape u] -> [TypeBase ExtShape u] -> [TypeBase ExtShape u] -- | Given a list of ExtTypes and a list of "forbidden" names, -- modify the dimensions of the ExtTypes such that they are -- Ext where they were previously Free with a variable in -- the set of forbidden names. existentialiseExtTypes :: [VName] -> [ExtType] -> [ExtType] -- | Produce a mapping for the dimensions context. shapeExtMapping :: [TypeBase ExtShape u] -> [TypeBase Shape u1] -> Map Int SubExp -- |
-- IntType Int8 --int8 :: PrimType -- |
-- IntType Int16 --int16 :: PrimType -- |
-- IntType Int32 --int32 :: PrimType -- |
-- IntType Int64 --int64 :: PrimType -- |
-- FloatType Float32 --float32 :: PrimType -- |
-- FloatType Float64 --float64 :: PrimType -- | Typeclass for things that contain Types. class Typed t typeOf :: Typed t => t -> Type -- | Typeclass for things that contain DeclTypes. class DeclTyped t declTypeOf :: DeclTyped t => t -> DeclType -- | Typeclass for things that contain ExtTypes. class FixExt t => ExtTyped t extTypeOf :: ExtTyped t => t -> ExtType -- | Typeclass for things that contain DeclExtTypes. class FixExt t => DeclExtTyped t declExtTypeOf :: DeclExtTyped t => t -> DeclExtType -- | Typeclass for things whose type can be changed. class Typed a => SetType a setType :: SetType a => a -> Type -> a -- | Something with an existential context that can be (partially) fixed. class FixExt t -- | Fix the given existentional variable to the indicated free value. fixExt :: FixExt t => Int -> SubExp -> t -> t instance Futhark.IR.Prop.Types.ExtTyped Futhark.IR.Syntax.Core.ExtType instance Futhark.IR.Prop.Types.DeclExtTyped Futhark.IR.Syntax.Core.DeclExtType instance (Futhark.IR.Prop.Types.FixExt shape, Futhark.IR.Syntax.Core.ArrayShape shape) => Futhark.IR.Prop.Types.FixExt (Futhark.IR.Syntax.Core.TypeBase shape u) instance Futhark.IR.Prop.Types.FixExt d => Futhark.IR.Prop.Types.FixExt (Futhark.IR.Syntax.Core.ShapeBase d) instance Futhark.IR.Prop.Types.FixExt a => Futhark.IR.Prop.Types.FixExt [a] instance Futhark.IR.Prop.Types.FixExt Futhark.IR.Syntax.Core.ExtSize instance Futhark.IR.Prop.Types.FixExt () instance Futhark.IR.Prop.Types.SetType Futhark.IR.Syntax.Core.Type instance Futhark.IR.Prop.Types.SetType b => Futhark.IR.Prop.Types.SetType (a, b) instance Futhark.IR.Prop.Types.SetType dec => Futhark.IR.Prop.Types.SetType (Futhark.IR.Syntax.Core.PatElemT dec) instance Futhark.IR.Prop.Types.DeclTyped Futhark.IR.Syntax.Core.DeclType instance Futhark.IR.Prop.Types.DeclTyped dec => Futhark.IR.Prop.Types.DeclTyped (Futhark.IR.Syntax.Core.Param dec) instance Futhark.IR.Prop.Types.Typed Futhark.IR.Syntax.Core.Type instance Futhark.IR.Prop.Types.Typed Futhark.IR.Syntax.Core.DeclType instance Futhark.IR.Prop.Types.Typed Futhark.IR.Syntax.Core.Ident instance Futhark.IR.Prop.Types.Typed dec => Futhark.IR.Prop.Types.Typed (Futhark.IR.Syntax.Core.Param dec) instance Futhark.IR.Prop.Types.Typed dec => Futhark.IR.Prop.Types.Typed (Futhark.IR.Syntax.Core.PatElemT dec) instance Futhark.IR.Prop.Types.Typed b => Futhark.IR.Prop.Types.Typed (a, b) -- | This module exports a type class covering representations of function -- return types. module Futhark.IR.RetType -- | A type representing the return type of a body. It should contain at -- least the information contained in a list of ExtTypes, but may -- have more, notably an existential context. class (Show rt, Eq rt, Ord rt, ExtTyped rt) => IsBodyType rt -- | Construct a body type from a primitive type. primBodyType :: IsBodyType rt => PrimType -> rt -- | A type representing the return type of a function. In practice, a list -- of these will be used. It should contain at least the information -- contained in an ExtType, but may have more, notably an -- existential context. class (Show rt, Eq rt, Ord rt, DeclExtTyped rt) => IsRetType rt -- | Contruct a return type from a primitive type. primRetType :: IsRetType rt => PrimType -> rt -- | Given a function return type, the parameters of the function, and the -- arguments for a concrete call, return the instantiated return type for -- the concrete call, if valid. applyRetType :: (IsRetType rt, Typed dec) => [rt] -> [Param dec] -> [(SubExp, Type)] -> Maybe [rt] -- | Given shape parameter names and types, produce the types of arguments -- accepted. expectedTypes :: Typed t => [VName] -> [t] -> [SubExp] -> [Type] instance Futhark.IR.RetType.IsRetType Futhark.IR.Syntax.Core.DeclExtType instance Futhark.IR.RetType.IsBodyType Futhark.IR.Syntax.Core.ExtType -- | The core Futhark AST is parameterised by a rep type -- parameter, which is then used to invoke the type families defined -- here. module Futhark.IR.Rep -- | A collection of type families giving various common types for a -- representation, along with constraints specifying that the types they -- map to should satisfy some minimal requirements. class (Show (LetDec l), Show (ExpDec l), Show (BodyDec l), Show (FParamInfo l), Show (LParamInfo l), Show (RetType l), Show (BranchType l), Show (Op l), Eq (LetDec l), Eq (ExpDec l), Eq (BodyDec l), Eq (FParamInfo l), Eq (LParamInfo l), Eq (RetType l), Eq (BranchType l), Eq (Op l), Ord (LetDec l), Ord (ExpDec l), Ord (BodyDec l), Ord (FParamInfo l), Ord (LParamInfo l), Ord (RetType l), Ord (BranchType l), Ord (Op l), IsRetType (RetType l), IsBodyType (BranchType l), Typed (FParamInfo l), Typed (LParamInfo l), Typed (LetDec l), DeclTyped (FParamInfo l)) => RepTypes l where { -- | Decoration for every let-pattern element. type family LetDec l :: Type; -- | Decoration for every expression. type family ExpDec l :: Type; -- | Decoration for every body. type family BodyDec l :: Type; -- | Decoration for every (non-lambda) function parameter. type family FParamInfo l :: Type; -- | Decoration for every lambda function parameter. type family LParamInfo l :: Type; -- | The return type decoration of function calls. type family RetType l :: Type; -- | The return type decoration of branches. type family BranchType l :: Type; -- | Extensible operation. type family Op l :: Type; type LetDec l = Type; type ExpDec l = (); type BodyDec l = (); type FParamInfo l = DeclType; type LParamInfo l = Type; type RetType l = DeclExtType; type BranchType l = ExtType; type Op l = (); } -- |
-- let {a_12} = x_10 + y_11
-- let {b_13} = a_12 - 1
-- in {b_13}
--
--
-- -- replicate([3][2],1) = [[1,1], [1,1], [1,1]] --Replicate :: Shape -> SubExp -> BasicOp -- | Create array of given type and shape, with undefined elements. Scratch :: PrimType -> [SubExp] -> BasicOp -- | 1st arg is the new shape, 2nd arg is the input array *) Reshape :: ShapeChange SubExp -> VName -> BasicOp -- | Permute the dimensions of the input array. The list of integers is a -- list of dimensions (0-indexed), which must be a permutation of -- [0,n-1], where n is the number of dimensions in the -- input array. Rearrange :: [Int] -> VName -> BasicOp -- | Rotate the dimensions of the input array. The list of subexpressions -- specify how much each dimension is rotated. The length of this list -- must be equal to the rank of the array. Rotate :: [SubExp] -> VName -> BasicOp -- | Update an accumulator at the given index with the given value. -- Consumes the accumulator and produces a new one. UpdateAcc :: VName -> [SubExp] -> [SubExp] -> BasicOp -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Floating-point sign function. FSignum :: FloatType -> UnOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> Overflow -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> Overflow -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> Overflow -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> Safety -> BinOp -- | Unsigned integer division. Rounds towards positive infinity. UDivUp :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards positive infinity. SDivUp :: IntType -> Safety -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Floating-point modulus. FMod :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> Safety -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM and integer division in C. SQuot :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM and integer modulo in C. SRem :: IntType -> Safety -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Comparison operators are like BinOps, but they always return a -- boolean value. The somewhat ugly constructor names are straight out of -- LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Apart from being Opaque, what else is going on here? data OpaqueOp -- | No special operation. OpaqueNil :: OpaqueOp -- | Print the argument, prefixed by this string. OpaqueTrace :: String -> OpaqueOp -- | The new dimension in a Reshape-like operation. This allows us -- to disambiguate "real" reshapes, that change the actual shape of the -- array, from type coercions that are just present to make the types -- work out. The two constructors are considered equal for purposes of -- Eq. data DimChange d -- | The new dimension is guaranteed to be numerically equal to the old -- one. DimCoercion :: d -> DimChange d -- | The new dimension is not necessarily numerically equal to the old one. DimNew :: d -> DimChange d -- | A list of DimChanges, indicating the new dimensions of an -- array. type ShapeChange d = [DimChange d] -- | The root Futhark expression type. The Op constructor contains a -- rep-specific operation. Do-loops, branches and function calls are -- special. Everything else is a simple BasicOp. data ExpT rep -- | A simple (non-recursive) operation. BasicOp :: BasicOp -> ExpT rep Apply :: Name -> [(SubExp, Diet)] -> [RetType rep] -> (Safety, SrcLoc, [SrcLoc]) -> ExpT rep If :: SubExp -> BodyT rep -> BodyT rep -> IfDec (BranchType rep) -> ExpT rep -- | loop {a} = {v} (for i < n|while b) do b. DoLoop :: [(FParam rep, SubExp)] -> LoopForm rep -> BodyT rep -> ExpT rep -- | Create accumulators backed by the given arrays (which are consumed) -- and pass them to the lambda, which must return the updated -- accumulators and possibly some extra values. The accumulators are -- turned back into arrays. The Shape is the write index space. -- The corresponding arrays must all have this shape outermost. This -- construct is not part of BasicOp because we need the -- rep parameter. WithAcc :: [(Shape, [VName], Maybe (Lambda rep, [SubExp]))] -> Lambda rep -> ExpT rep Op :: Op rep -> ExpT rep -- | A type alias for namespace control. type Exp = ExpT -- | For-loop or while-loop? data LoopForm rep ForLoop :: VName -> IntType -> SubExp -> [(LParam rep, VName)] -> LoopForm rep WhileLoop :: VName -> LoopForm rep -- | Data associated with a branch. data IfDec rt IfDec :: [rt] -> IfSort -> IfDec rt [ifReturns] :: IfDec rt -> [rt] [ifSort] :: IfDec rt -> IfSort -- | What kind of branch is this? This has no semantic meaning, but -- provides hints to simplifications. data IfSort -- | An ordinary branch. IfNormal :: IfSort -- | A branch where the "true" case is what we are actually interested in, -- and the "false" case is only present as a fallback for when the true -- case cannot be safely evaluated. The compiler is permitted to optimise -- away the branch if the true case contains only safe statements. IfFallback :: IfSort -- | Both of these branches are semantically equivalent, and it is fine to -- eliminate one if it turns out to have problems (e.g. contain things we -- cannot generate code for). IfEquiv :: IfSort -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. -- -- For operations like integer division, a safe division will not explode -- the computer in case of division by zero, but instead return some -- unspecified value. This always involves a run-time check, so generally -- the unsafe variant is what the compiler will insert, but guarded by an -- explicit assertion elsewhere. Safe operations are useful when the -- optimiser wants to move e.g. a division to a location where the -- divisor may be zero, but where the result will only be used when it is -- non-zero (so it doesn't matter what result is provided with a zero -- divisor, as long as the program keeps running). data Safety Unsafe :: Safety Safe :: Safety -- | Anonymous function for use in a SOAC. data LambdaT rep Lambda :: [LParam rep] -> BodyT rep -> [Type] -> LambdaT rep [lambdaParams] :: LambdaT rep -> [LParam rep] [lambdaBody] :: LambdaT rep -> BodyT rep [lambdaReturnType] :: LambdaT rep -> [Type] -- | Type alias for namespacing reasons. type Lambda = LambdaT -- | A function or lambda parameter. data Param dec Param :: VName -> dec -> Param dec -- | Name of the parameter. [paramName] :: Param dec -> VName -- | Function parameter decoration. [paramDec] :: Param dec -> dec -- | A function and loop parameter. type FParam rep = Param (FParamInfo rep) -- | A lambda parameter. type LParam rep = Param (LParamInfo rep) -- | Function Declarations data FunDef rep FunDef :: Maybe EntryPoint -> Attrs -> Name -> [RetType rep] -> [FParam rep] -> BodyT rep -> FunDef rep -- | Contains a value if this function is an entry point. [funDefEntryPoint] :: FunDef rep -> Maybe EntryPoint [funDefAttrs] :: FunDef rep -> Attrs [funDefName] :: FunDef rep -> Name [funDefRetType] :: FunDef rep -> [RetType rep] [funDefParams] :: FunDef rep -> [FParam rep] [funDefBody] :: FunDef rep -> BodyT rep -- | Information about the parameters and return value of an entry point. -- The first element is for parameters, the second for return value. type EntryPoint = (Name, [EntryPointType], [EntryPointType]) -- | Every entry point argument and return value has an annotation -- indicating how it maps to the original source program type. data EntryPointType -- | Is an unsigned integer or array of unsigned integers. TypeUnsigned :: Uniqueness -> EntryPointType -- | A black box type comprising this many core values. The string is a -- human-readable description with no other semantics. TypeOpaque :: Uniqueness -> String -> Int -> EntryPointType -- | Maps directly. TypeDirect :: Uniqueness -> EntryPointType -- | An entire Futhark program. data Prog rep Prog :: Stms rep -> [FunDef rep] -> Prog rep -- | Top-level constants that are computed at program startup, and which -- are in scope inside all functions. [progConsts] :: Prog rep -> Stms rep -- | The functions comprising the program. All funtions are also available -- in scope in the definitions of the constants, so be careful not to -- introduce circular dependencies (not currently checked). [progFuns] :: Prog rep -> [FunDef rep] -- | A single statement. oneStm :: Stm rep -> Stms rep -- | Convert a statement list to a statement sequence. stmsFromList :: [Stm rep] -> Stms rep -- | Convert a statement sequence to a statement list. stmsToList :: Stms rep -> [Stm rep] -- | The first statement in the sequence, if any. stmsHead :: Stms rep -> Maybe (Stm rep, Stms rep) -- | Construct a SubExpRes with no certificates. subExpRes :: SubExp -> SubExpRes -- | Construct a Result from subexpressions. subExpsRes :: [SubExp] -> Result -- | Construct a SubExpRes from a variable name. varRes :: VName -> SubExpRes -- | Construct a Result from variable names. varsRes :: [VName] -> Result instance GHC.Classes.Eq Futhark.IR.Syntax.Attr instance GHC.Show.Show Futhark.IR.Syntax.Attr instance GHC.Classes.Ord Futhark.IR.Syntax.Attr instance GHC.Base.Semigroup Futhark.IR.Syntax.Attrs instance GHC.Base.Monoid Futhark.IR.Syntax.Attrs instance GHC.Classes.Eq Futhark.IR.Syntax.Attrs instance GHC.Show.Show Futhark.IR.Syntax.Attrs instance GHC.Classes.Ord Futhark.IR.Syntax.Attrs instance GHC.Classes.Eq dec => GHC.Classes.Eq (Futhark.IR.Syntax.PatT dec) instance GHC.Show.Show dec => GHC.Show.Show (Futhark.IR.Syntax.PatT dec) instance GHC.Classes.Ord dec => GHC.Classes.Ord (Futhark.IR.Syntax.PatT dec) instance GHC.Classes.Eq dec => GHC.Classes.Eq (Futhark.IR.Syntax.StmAux dec) instance GHC.Show.Show dec => GHC.Show.Show (Futhark.IR.Syntax.StmAux dec) instance GHC.Classes.Ord dec => GHC.Classes.Ord (Futhark.IR.Syntax.StmAux dec) instance GHC.Show.Show Futhark.IR.Syntax.SubExpRes instance GHC.Classes.Ord Futhark.IR.Syntax.SubExpRes instance GHC.Classes.Eq Futhark.IR.Syntax.SubExpRes instance GHC.Show.Show d => GHC.Show.Show (Futhark.IR.Syntax.DimChange d) instance GHC.Classes.Ord d => GHC.Classes.Ord (Futhark.IR.Syntax.DimChange d) instance GHC.Show.Show Futhark.IR.Syntax.OpaqueOp instance GHC.Classes.Ord Futhark.IR.Syntax.OpaqueOp instance GHC.Classes.Eq Futhark.IR.Syntax.OpaqueOp instance GHC.Show.Show Futhark.IR.Syntax.BasicOp instance GHC.Classes.Ord Futhark.IR.Syntax.BasicOp instance GHC.Classes.Eq Futhark.IR.Syntax.BasicOp instance GHC.Classes.Ord Futhark.IR.Syntax.IfSort instance GHC.Show.Show Futhark.IR.Syntax.IfSort instance GHC.Classes.Eq Futhark.IR.Syntax.IfSort instance GHC.Classes.Ord rt => GHC.Classes.Ord (Futhark.IR.Syntax.IfDec rt) instance GHC.Show.Show rt => GHC.Show.Show (Futhark.IR.Syntax.IfDec rt) instance GHC.Classes.Eq rt => GHC.Classes.Eq (Futhark.IR.Syntax.IfDec rt) instance GHC.Classes.Ord Futhark.IR.Syntax.EntryPointType instance GHC.Show.Show Futhark.IR.Syntax.EntryPointType instance GHC.Classes.Eq Futhark.IR.Syntax.EntryPointType instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.Syntax.Prog rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.Syntax.Prog rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.Syntax.Prog rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.Syntax.Stm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.Syntax.Stm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.Syntax.Stm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.Syntax.BodyT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.Syntax.BodyT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.Syntax.BodyT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.Syntax.ExpT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.Syntax.ExpT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.Syntax.ExpT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.Syntax.LoopForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.Syntax.LoopForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.Syntax.LoopForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.Syntax.LambdaT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.Syntax.LambdaT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.Syntax.LambdaT rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.Syntax.FunDef rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.Syntax.FunDef rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.Syntax.FunDef rep) instance GHC.Classes.Eq d => GHC.Classes.Eq (Futhark.IR.Syntax.DimChange d) instance GHC.Base.Functor Futhark.IR.Syntax.DimChange instance Data.Foldable.Foldable Futhark.IR.Syntax.DimChange instance Data.Traversable.Traversable Futhark.IR.Syntax.DimChange instance GHC.Base.Semigroup dec => GHC.Base.Semigroup (Futhark.IR.Syntax.StmAux dec) instance GHC.Base.Semigroup (Futhark.IR.Syntax.PatT dec) instance GHC.Base.Monoid (Futhark.IR.Syntax.PatT dec) instance GHC.Base.Functor Futhark.IR.Syntax.PatT instance Data.Foldable.Foldable Futhark.IR.Syntax.PatT instance Data.Traversable.Traversable Futhark.IR.Syntax.PatT instance Data.String.IsString Futhark.IR.Syntax.Attr -- | Facilities for creating, inspecting, and simplifying reshape and -- coercion operations. module Futhark.IR.Prop.Reshape -- | The new dimension. newDim :: DimChange d -> d -- | The new dimensions resulting from a reshape operation. newDims :: ShapeChange d -> [d] -- | The new shape resulting from a reshape operation. newShape :: ShapeChange SubExp -> Shape -- | Construct a Reshape where all dimension changes are -- DimCoercions. shapeCoerce :: [SubExp] -> VName -> Exp rep -- | reshapeOuter newshape n oldshape returns a Reshape -- expression that replaces the outer n dimensions of -- oldshape with newshape. reshapeOuter :: ShapeChange SubExp -> Int -> Shape -> ShapeChange SubExp -- | reshapeInner newshape n oldshape returns a Reshape -- expression that replaces the inner m-n dimensions (where -- m is the rank of oldshape) of src with -- newshape. reshapeInner :: ShapeChange SubExp -> Int -> Shape -> ShapeChange SubExp -- | If the shape change is nothing but shape coercions, return the new -- dimensions. Otherwise, return Nothing. shapeCoercion :: ShapeChange d -> Maybe [d] -- | fuseReshape s1 s2 creates a new ShapeChange that is -- semantically the same as first applying s1 and then -- s2. This may take advantage of properties of -- DimCoercion versus DimNew to preserve information. fuseReshape :: Eq d => ShapeChange d -> ShapeChange d -> ShapeChange d -- | Given concrete information about the shape of the source array, -- convert some DimNews into DimCoercions. informReshape :: Eq d => [d] -> ShapeChange d -> ShapeChange d -- | reshapeIndex to_dims from_dims is transforms the index list -- is (which is into an array of shape from_dims) into -- an index list is', which is into an array of shape -- to_dims. is must have the same length as -- from_dims, and is' will have the same length as -- to_dims. reshapeIndex :: IntegralExp num => [num] -> [num] -> [num] -> [num] -- | flattenIndex dims is computes the flat index of is -- into an array with dimensions dims. The length of -- dims and is must be the same. flattenIndex :: IntegralExp num => [num] -> [num] -> num -- | unflattenIndex dims i computes a list of indices into an -- array with dimension dims given the flat index i. -- The resulting list will have the same size as dims. unflattenIndex :: IntegralExp num => [num] -> num -> [num] -- | Given a length n list of dimensions dims, -- sizeSizes dims will compute a length n+1 list of the -- size of each possible array slice. The first element of this list will -- be the product of dims, and the last element will be 1. sliceSizes :: IntegralExp num => [num] -> [num] -- | Inspecing and modifying Pats, function parameters and pattern -- elements. module Futhark.IR.Prop.Patterns -- | An Ident corresponding to a parameter. paramIdent :: Typed dec => Param dec -> Ident -- | The Type of a parameter. paramType :: Typed dec => Param dec -> Type -- | The DeclType of a parameter. paramDeclType :: DeclTyped dec => Param dec -> DeclType -- | An Ident corresponding to a pattern element. patElemIdent :: Typed dec => PatElemT dec -> Ident -- | The type of a name bound by a PatElem. patElemType :: Typed dec => PatElemT dec -> Type -- | Set the rep of a PatElem. setPatElemDec :: PatElemT oldattr -> newattr -> PatElemT newattr -- | Return a list of the Idents bound by the Pat. patIdents :: Typed dec => PatT dec -> [Ident] -- | Return a list of the Names bound by the Pat. patNames :: PatT dec -> [VName] -- | Return a list of the typess bound by the pattern. patTypes :: Typed dec => PatT dec -> [Type] -- | Return the number of names bound by the pattern. patSize :: PatT dec -> Int -- | Create a pattern using Type as the attribute. basicPat :: [Ident] -> PatT Type -- | Futhark prettyprinter. This module defines Pretty instances for -- the AST defined in Futhark.IR.Syntax, but also a number of -- convenience functions if you don't want to use the interface from -- Pretty. module Futhark.IR.Pretty -- | Prettyprint a list enclosed in curly braces. prettyTuple :: Pretty a => [a] -> String -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | The class of representations whose annotations can be prettyprinted. class (RepTypes rep, Pretty (RetType rep), Pretty (BranchType rep), Pretty (FParamInfo rep), Pretty (LParamInfo rep), Pretty (LetDec rep), Pretty (Op rep)) => PrettyRep rep ppExpDec :: PrettyRep rep => ExpDec rep -> Exp rep -> Maybe Doc -- | Like prettyTuple, but produces a Doc. ppTuple' :: Pretty a => [a] -> Doc instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Stms rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Body rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Stm rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Exp rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Lambda rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.FunDef rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Prog rep) instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.VName instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.Commutativity instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.NoUniqueness instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.Shape instance Text.PrettyPrint.Mainland.Class.Pretty a => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Ext a) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.ExtShape instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.Space instance Text.PrettyPrint.Mainland.Class.Pretty u => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.TypeBase Futhark.IR.Syntax.Core.Shape u) instance Text.PrettyPrint.Mainland.Class.Pretty u => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.TypeBase Futhark.IR.Syntax.Core.ExtShape u) instance Text.PrettyPrint.Mainland.Class.Pretty u => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.TypeBase Futhark.IR.Syntax.Core.Rank u) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.Ident instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.SubExp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.Certs instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.SubExpRes instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Attr instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Attrs instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.PatElemT dec) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.PatT dec) instance Text.PrettyPrint.Mainland.Class.Pretty t => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.PatElemT t) instance Text.PrettyPrint.Mainland.Class.Pretty t => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Param t) instance Text.PrettyPrint.Mainland.Class.Pretty a => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Slice a) instance Text.PrettyPrint.Mainland.Class.Pretty d => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.FlatDimIndex d) instance Text.PrettyPrint.Mainland.Class.Pretty a => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.FlatSlice a) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.BasicOp instance Text.PrettyPrint.Mainland.Class.Pretty a => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.ErrorMsg a) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.EntryPointType instance Text.PrettyPrint.Mainland.Class.Pretty d => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.DimChange d) instance Text.PrettyPrint.Mainland.Class.Pretty d => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.DimIndex d) -- | The core Futhark AST does not contain type information when we use a -- variable. Therefore, most transformations expect to be able to access -- some kind of symbol table that maps names to their types. -- -- This module defines the concept of a type environment as a mapping -- from variable names to NameInfos. Convenience facilities are -- also provided to communicate that some monad or applicative functor -- maintains type information. module Futhark.IR.Prop.Scope -- | The class of applicative functors (or more common in practice: monads) -- that permit the lookup of variable types. A default method for -- lookupType exists, which is sufficient (if not always maximally -- efficient, and using error to fail) when askScope is -- defined. class (Applicative m, RepTypes rep) => HasScope rep m | m -> rep -- | Return the type of the given variable, or fail if it is not in the -- type environment. lookupType :: HasScope rep m => VName -> m Type -- | Return the info of the given variable, or fail if it is not in the -- type environment. lookupInfo :: HasScope rep m => VName -> m (NameInfo rep) -- | Return the type environment contained in the applicative functor. askScope :: HasScope rep m => m (Scope rep) -- | Return the result of applying some function to the type environment. asksScope :: HasScope rep m => (Scope rep -> a) -> m a -- | How some name in scope was bound. data NameInfo rep LetName :: LetDec rep -> NameInfo rep FParamName :: FParamInfo rep -> NameInfo rep LParamName :: LParamInfo rep -> NameInfo rep IndexName :: IntType -> NameInfo rep -- | The class of monads that not only provide a Scope, but also the -- ability to locally extend it. A Reader containing a -- Scope is the prototypical example of such a monad. class (HasScope rep m, Monad m) => LocalScope rep m -- | Run a computation with an extended type environment. Note that this is -- intended to *add* to the current type environment, it does not replace -- it. localScope :: LocalScope rep m => Scope rep -> m a -> m a -- | A scope is a mapping from variable names to information about that -- name. type Scope rep = Map VName (NameInfo rep) -- | The class of things that can provide a scope. There is no overarching -- rule for what this means. For a Stm, it is the corresponding -- pattern. For a Lambda, is is the parameters. class Scoped rep a | a -> rep scopeOf :: Scoped rep a => a -> Scope rep -- | Extend the monadic scope with the scopeOf the given value. inScopeOf :: (Scoped rep a, LocalScope rep m) => a -> m b -> m b -- | The scope of some lambda parameters. scopeOfLParams :: LParamInfo rep ~ dec => [Param dec] -> Scope rep -- | The scope of some function or loop parameters. scopeOfFParams :: FParamInfo rep ~ dec => [Param dec] -> Scope rep -- | The scope of a pattern. scopeOfPat :: LetDec rep ~ dec => PatT dec -> Scope rep -- | The scope of a pattern element. scopeOfPatElem :: LetDec rep ~ dec => PatElemT dec -> Scope rep -- | A constraint that indicates two representations have the same -- NameInfo representation. type SameScope rep1 rep2 = (LetDec rep1 ~ LetDec rep2, FParamInfo rep1 ~ FParamInfo rep2, LParamInfo rep1 ~ LParamInfo rep2) -- | If two scopes are really the same, then you can convert one to the -- other. castScope :: SameScope fromrep torep => Scope fromrep -> Scope torep -- | A monad transformer that carries around an extended Scope. Its -- lookupType method will first look in the extended Scope, -- and then use the lookupType method of the underlying monad. data ExtendedScope rep m a -- | Run a computation in the extended type environment. extendedScope :: ExtendedScope rep m a -> Scope rep -> m a instance GHC.Base.Monad m => Control.Monad.Reader.Class.MonadReader (Futhark.IR.Prop.Scope.Scope rep) (Futhark.IR.Prop.Scope.ExtendedScope rep m) instance GHC.Base.Monad m => GHC.Base.Monad (Futhark.IR.Prop.Scope.ExtendedScope rep m) instance GHC.Base.Applicative m => GHC.Base.Applicative (Futhark.IR.Prop.Scope.ExtendedScope rep m) instance GHC.Base.Functor m => GHC.Base.Functor (Futhark.IR.Prop.Scope.ExtendedScope rep m) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.Prop.Scope.NameInfo rep) instance (Futhark.IR.Prop.Scope.HasScope rep m, GHC.Base.Monad m) => Futhark.IR.Prop.Scope.HasScope rep (Futhark.IR.Prop.Scope.ExtendedScope rep m) instance Futhark.IR.Prop.Scope.Scoped rep a => Futhark.IR.Prop.Scope.Scoped rep [a] instance Futhark.IR.Prop.Scope.Scoped rep (Futhark.IR.Syntax.Stms rep) instance Futhark.IR.Prop.Scope.Scoped rep (Futhark.IR.Syntax.Stm rep) instance Futhark.IR.Prop.Scope.Scoped rep (Futhark.IR.Syntax.FunDef rep) instance Futhark.IR.Prop.Scope.Scoped rep (Language.Futhark.Core.VName, Futhark.IR.Prop.Scope.NameInfo rep) instance Futhark.IR.Prop.Scope.Scoped rep (Futhark.IR.Syntax.LoopForm rep) instance Futhark.IR.Prop.Scope.Scoped rep (Futhark.IR.Syntax.Lambda rep) instance (GHC.Base.Monad m, Futhark.IR.Prop.Scope.LocalScope rep m) => Futhark.IR.Prop.Scope.LocalScope rep (Control.Monad.Trans.Except.ExceptT e m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, Futhark.IR.Rep.RepTypes rep) => Futhark.IR.Prop.Scope.LocalScope rep (Control.Monad.Trans.Reader.ReaderT (Futhark.IR.Prop.Scope.Scope rep) m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.IR.Rep.RepTypes rep) => Futhark.IR.Prop.Scope.LocalScope rep (Control.Monad.Trans.RWS.Strict.RWST (Futhark.IR.Prop.Scope.Scope rep) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.IR.Rep.RepTypes rep) => Futhark.IR.Prop.Scope.LocalScope rep (Control.Monad.Trans.RWS.Lazy.RWST (Futhark.IR.Prop.Scope.Scope rep) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, Futhark.IR.Rep.RepTypes rep) => Futhark.IR.Prop.Scope.HasScope rep (Control.Monad.Trans.Reader.ReaderT (Futhark.IR.Prop.Scope.Scope rep) m) instance (GHC.Base.Monad m, Futhark.IR.Prop.Scope.HasScope rep m) => Futhark.IR.Prop.Scope.HasScope rep (Control.Monad.Trans.Except.ExceptT e m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.IR.Rep.RepTypes rep) => Futhark.IR.Prop.Scope.HasScope rep (Control.Monad.Trans.RWS.Strict.RWST (Futhark.IR.Prop.Scope.Scope rep) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.IR.Rep.RepTypes rep) => Futhark.IR.Prop.Scope.HasScope rep (Control.Monad.Trans.RWS.Lazy.RWST (Futhark.IR.Prop.Scope.Scope rep) w s m) instance Futhark.IR.Rep.RepTypes rep => Futhark.IR.Prop.Types.Typed (Futhark.IR.Prop.Scope.NameInfo rep) -- | Functions for generic traversals across Futhark syntax trees. The -- motivation for this module came from dissatisfaction with rewriting -- the same trivial tree recursions for every module. A possible -- alternative would be to use normal "Scrap your -- boilerplate"-techniques, but these are rejected for two reasons: -- --
-- instance MonadFreshNames vn MyMonad where -- getNameSource = get -- putNameSource = put --class (Applicative m, Monad m) => MonadFreshNames m getNameSource :: MonadFreshNames m => m VNameSource putNameSource :: MonadFreshNames m => VNameSource -> m () -- | Run a computation needing a fresh name source and returning a new one, -- using getNameSource and putNameSource before and after -- the computation. modifyNameSource :: MonadFreshNames m => (VNameSource -> (a, VNameSource)) -> m a -- | Produce a fresh name, using the given name as a template. newName :: MonadFreshNames m => VName -> m VName -- | As newName, but takes a String for the name template. newNameFromString :: MonadFreshNames m => String -> m VName -- | Produce a fresh VName, using the given base name as a template. newVName :: MonadFreshNames m => String -> m VName -- | Produce a fresh Ident, using the given name as a template. newIdent :: MonadFreshNames m => String -> Type -> m Ident -- | Produce a fresh Ident, using the given Ident as a -- template, but possibly modifying the name. newIdent' :: MonadFreshNames m => (String -> String) -> Ident -> m Ident -- | Produce a fresh Param, using the given name as a template. newParam :: MonadFreshNames m => String -> dec -> m (Param dec) -- | A name source is conceptually an infinite sequence of names with no -- repeating entries. In practice, when asked for a name, the name source -- will return the name along with a new name source, which should then -- be used in place of the original. -- -- The Ord instance is based on how many names have been extracted -- from the name source. data VNameSource -- | A blank name source. blankNameSource :: VNameSource -- | A new name source that starts counting from the given number. newNameSource :: Int -> VNameSource instance (GHC.Base.Applicative im, GHC.Base.Monad im) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.State.Lazy.StateT Futhark.FreshNames.VNameSource im) instance (GHC.Base.Applicative im, GHC.Base.Monad im) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.State.Strict.StateT Futhark.FreshNames.VNameSource im) instance (GHC.Base.Applicative im, GHC.Base.Monad im, GHC.Base.Monoid w) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.RWS.Lazy.RWST r w Futhark.FreshNames.VNameSource im) instance (GHC.Base.Applicative im, GHC.Base.Monad im, GHC.Base.Monoid w) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.RWS.Strict.RWST r w Futhark.FreshNames.VNameSource im) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Reader.ReaderT s m) instance (Futhark.MonadFreshNames.MonadFreshNames m, GHC.Base.Monoid s) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Writer.Lazy.WriterT s m) instance (Futhark.MonadFreshNames.MonadFreshNames m, GHC.Base.Monoid s) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Writer.Strict.WriterT s m) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Maybe.MaybeT m) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.Except.ExceptT e m) -- | This module provides facilities for transforming Futhark programs such -- that names are unique, via the renameProg function. module Futhark.Transform.Rename -- | Rename variables such that each is unique. The semantics of the -- program are unaffected, under the assumption that the program was -- correct to begin with. In particular, the renaming may make an invalid -- program valid. renameProg :: (Renameable rep, MonadFreshNames m) => Prog rep -> m (Prog rep) -- | Rename bound variables such that each is unique. The semantics of the -- expression is unaffected, under the assumption that the expression was -- correct to begin with. Any free variables are left untouched. renameExp :: (Renameable rep, MonadFreshNames m) => Exp rep -> m (Exp rep) -- | Rename bound variables such that each is unique. The semantics of the -- binding is unaffected, under the assumption that the binding was -- correct to begin with. Any free variables are left untouched, as are -- the names in the pattern of the binding. renameStm :: (Renameable rep, MonadFreshNames m) => Stm rep -> m (Stm rep) -- | Rename bound variables such that each is unique. The semantics of the -- body is unaffected, under the assumption that the body was correct to -- begin with. Any free variables are left untouched. renameBody :: (Renameable rep, MonadFreshNames m) => Body rep -> m (Body rep) -- | Rename bound variables such that each is unique. The semantics of the -- lambda is unaffected, under the assumption that the body was correct -- to begin with. Any free variables are left untouched. Note in -- particular that the parameters of the lambda are renamed. renameLambda :: (Renameable rep, MonadFreshNames m) => Lambda rep -> m (Lambda rep) -- | Produce an equivalent pattern but with each pattern element given a -- new name. renamePat :: (Rename dec, MonadFreshNames m) => PatT dec -> m (PatT dec) -- | Rename the bound variables in something (does not affect free -- variables). renameSomething :: (Rename a, MonadFreshNames m) => a -> m a -- | The monad in which renaming is performed. data RenameM a -- | Perform a renaming using the Substitute instance. This only -- works if the argument does not itself perform any name binding, but it -- can save on boilerplate for simple types. substituteRename :: Substitute a => a -> RenameM a -- | Rename some statements, then execute an action with the name -- substitutions induced by the statements active. renamingStms :: Renameable rep => Stms rep -> (Stms rep -> RenameM a) -> RenameM a -- | Members of class Rename can be uniquely renamed. class Rename a -- | Rename the given value such that it does not contain shadowing, and -- has incorporated any substitutions present in the RenameM -- environment. rename :: Rename a => a -> RenameM a -- | Representations in which all decorations are renameable. type Renameable rep = (Rename (LetDec rep), Rename (ExpDec rep), Rename (BodyDec rep), Rename (FParamInfo rep), Rename (LParamInfo rep), Rename (RetType rep), Rename (BranchType rep), Rename (Op rep)) instance Control.Monad.Reader.Class.MonadReader Futhark.Transform.Rename.RenameEnv Futhark.Transform.Rename.RenameM instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Transform.Rename.RenameM instance GHC.Base.Monad Futhark.Transform.Rename.RenameM instance GHC.Base.Applicative Futhark.Transform.Rename.RenameM instance GHC.Base.Functor Futhark.Transform.Rename.RenameM instance Futhark.Transform.Rename.Renameable rep => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.FunDef rep) instance Futhark.Transform.Rename.Renameable rep => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Body rep) instance Futhark.Transform.Rename.Renameable rep => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Stm rep) instance Futhark.Transform.Rename.Renameable rep => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Exp rep) instance Futhark.Transform.Rename.Renameable rep => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Lambda rep) instance Futhark.Transform.Rename.Rename Language.Futhark.Core.VName instance Futhark.Transform.Rename.Rename a => Futhark.Transform.Rename.Rename [a] instance (Futhark.Transform.Rename.Rename a, Futhark.Transform.Rename.Rename b) => Futhark.Transform.Rename.Rename (a, b) instance (Futhark.Transform.Rename.Rename a, Futhark.Transform.Rename.Rename b, Futhark.Transform.Rename.Rename c) => Futhark.Transform.Rename.Rename (a, b, c) instance Futhark.Transform.Rename.Rename a => Futhark.Transform.Rename.Rename (GHC.Maybe.Maybe a) instance Futhark.Transform.Rename.Rename GHC.Types.Bool instance Futhark.Transform.Rename.Rename Futhark.IR.Syntax.Core.Ident instance Futhark.Transform.Rename.Rename Futhark.IR.Syntax.Core.SubExp instance Futhark.Transform.Rename.Rename dec => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Core.Param dec) instance Futhark.Transform.Rename.Rename dec => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.PatT dec) instance Futhark.Transform.Rename.Rename dec => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Core.PatElemT dec) instance Futhark.Transform.Rename.Rename Futhark.IR.Syntax.Core.Certs instance Futhark.Transform.Rename.Rename Futhark.IR.Syntax.Attrs instance Futhark.Transform.Rename.Rename dec => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.StmAux dec) instance Futhark.Transform.Rename.Rename Futhark.IR.Syntax.SubExpRes instance Futhark.Transform.Rename.Rename Futhark.IR.Primitive.PrimType instance Futhark.Transform.Rename.Rename shape => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Core.TypeBase shape u) instance Futhark.Transform.Rename.Rename Futhark.IR.Prop.Names.Names instance Futhark.Transform.Rename.Rename Futhark.IR.Syntax.Core.Rank instance Futhark.Transform.Rename.Rename d => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Core.ShapeBase d) instance Futhark.Transform.Rename.Rename Futhark.IR.Syntax.Core.ExtSize instance Futhark.Transform.Rename.Rename () instance Futhark.Transform.Rename.Rename d => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Core.DimIndex d) -- | This module provides various simple ways to query and manipulate -- fundamental Futhark terms, such as types and values. The intent is to -- keep Futhark.IRrsentation.AST.Syntax simple, and put whatever -- embellishments we need here. This is an internal, desugared -- representation. module Futhark.IR.Prop -- | isBuiltInFunction k is True if k is an -- element of builtInFunctions. isBuiltInFunction :: Name -> Bool -- | A map of all built-in functions and their types. builtInFunctions :: Map Name (PrimType, [PrimType]) -- | If the expression is a BasicOp, return it, otherwise -- Nothing. asBasicOp :: Exp rep -> Maybe BasicOp -- | An expression is safe if it is always well-defined (assuming that any -- required certificates have been checked) in any context. For example, -- array indexing is not safe, as the index may be out of bounds. On the -- other hand, adding two numbers cannot fail. safeExp :: IsOp (Op rep) => Exp rep -> Bool -- | Return the variable names used in Var subexpressions. May -- contain duplicates. subExpVars :: [SubExp] -> [VName] -- | If the SubExp is a Var return the variable name. subExpVar :: SubExp -> Maybe VName -- | Does the given lambda represent a known commutative function? Based on -- pattern matching and checking whether the lambda represents a known -- arithmetic operator; don't expect anything clever here. commutativeLambda :: Lambda rep -> Bool -- | How many value parameters are accepted by this entry point? This is -- used to determine which of the function parameters correspond to the -- parameters of the original function (they must all come at the end). entryPointSize :: EntryPointType -> Int -- | A StmAux with empty Certs. defAux :: dec -> StmAux dec -- | The certificates associated with a statement. stmCerts :: Stm rep -> Certs -- | Add certificates to a statement. certify :: Certs -> Stm rep -> Stm rep -- | Construct the type of an expression that would match the pattern. expExtTypesFromPat :: Typed dec => PatT dec -> [ExtType] -- | Keep only those attributes that are relevant for Assert -- expressions. attrsForAssert :: Attrs -> Attrs -- | Horizontally fission a lambda that models a binary operator. lamIsBinOp :: ASTRep rep => Lambda rep -> Maybe [(BinOp, PrimType, VName, VName)] -- | A handy shorthand for properties that we usually want to things we -- stuff into ASTs. type ASTConstraints a = (Eq a, Ord a, Show a, Rename a, Substitute a, FreeIn a, Pretty a) -- | A type class for operations. class (ASTConstraints op, TypedOp op) => IsOp op -- | Like safeExp, but for arbitrary ops. safeOp :: IsOp op => op -> Bool -- | Should we try to hoist this out of branches? cheapOp :: IsOp op => op -> Bool -- | Representation-specific attributes; also means the rep supports some -- basic facilities. class (RepTypes rep, PrettyRep rep, Renameable rep, Substitutable rep, FreeDec (ExpDec rep), FreeIn (LetDec rep), FreeDec (BodyDec rep), FreeIn (FParamInfo rep), FreeIn (LParamInfo rep), FreeIn (RetType rep), FreeIn (BranchType rep), IsOp (Op rep)) => ASTRep rep -- | Given a pattern, construct the type of a body that would match it. An -- implementation for many representations would be -- expExtTypesFromPat. expTypesFromPat :: (ASTRep rep, HasScope rep m, Monad m) => Pat rep -> m [BranchType rep] instance Futhark.IR.Prop.IsOp () -- | The IR tracks aliases, mostly to ensure the soundness of in-place -- updates, but it can also be used for other things (such as memory -- optimisations). This module contains the raw building blocks for -- determining the aliases of the values produced by expressions. It also -- contains some building blocks for inspecting consumption. -- -- One important caveat is that all aliases computed here are -- local. Thus, they do not take aliases-of-aliases into account. -- See Futhark.Analysis.Alias if this is not what you want. module Futhark.IR.Prop.Aliases -- | The alises of a subexpression. subExpAliases :: SubExp -> Names -- | The aliases of an expression, one per non-context value returned. expAliases :: Aliased rep => Exp rep -> [Names] -- | The aliases of each pattern element (including the context). patAliases :: AliasesOf dec => PatT dec -> [Names] -- | Also includes the name itself. lookupAliases :: AliasesOf (LetDec rep) => VName -> Scope rep -> Names -- | The class of representations that contain aliasing information. class (RepTypes rep, AliasedOp (Op rep), AliasesOf (LetDec rep)) => Aliased rep -- | The aliases of the body results. bodyAliases :: Aliased rep => Body rep -> [Names] -- | The variables consumed in the body. consumedInBody :: Aliased rep => Body rep -> Names -- | Something that contains alias information. class AliasesOf a -- | The alias of the argument element. aliasesOf :: AliasesOf a => a -> Names -- | The variables consumed in this statement. consumedInStm :: Aliased rep => Stm rep -> Names -- | The variables consumed in this expression. consumedInExp :: Aliased rep => Exp rep -> Names -- | The variables consumed by this lambda. consumedByLambda :: Aliased rep => Lambda rep -> Names -- | Pre-existing aliases for variables. Used to add transitive aliases. type AliasTable = Map VName Names -- | The class of operations that can produce aliasing and consumption -- information. class IsOp op => AliasedOp op opAliases :: AliasedOp op => op -> [Names] consumedInOp :: AliasedOp op => op -> Names -- | The class of operations that can be given aliasing information. This -- is a somewhat subtle concept that is only used in the simplifier and -- when using "rep adapters". class AliasedOp (OpWithAliases op) => CanBeAliased op where { -- | The op that results when we add aliases to this op. type family OpWithAliases op :: Type; } -- | Remove aliases from this op. removeOpAliases :: CanBeAliased op => OpWithAliases op -> op -- | Add aliases to this op. addOpAliases :: CanBeAliased op => AliasTable -> op -> OpWithAliases op instance Futhark.IR.Prop.Aliases.CanBeAliased () instance Futhark.IR.Prop.Aliases.AliasedOp () instance Futhark.IR.Prop.Aliases.AliasesOf Futhark.IR.Prop.Names.Names instance Futhark.IR.Prop.Aliases.AliasesOf dec => Futhark.IR.Prop.Aliases.AliasesOf (Futhark.IR.Syntax.Core.PatElemT dec) -- | A convenient re-export of basic AST modules. module Futhark.IR -- | A usage-table is sort of a bottom-up symbol table, describing how (and -- if) a variable is used. module Futhark.Analysis.UsageTable -- | A usage table. data UsageTable -- | Remove these entries from the usage table. without :: UsageTable -> [VName] -> UsageTable -- | Look up a variable in the usage table. lookup :: VName -> UsageTable -> Maybe Usages -- | Is the variable present in the usage table? That is, has it been used? used :: VName -> UsageTable -> Bool -- | Expand the usage table based on aliasing information. expand :: (VName -> Names) -> UsageTable -> UsageTable -- | Has the variable been consumed? isConsumed :: VName -> UsageTable -> Bool -- | Has the variable been used in the Result of a body? isInResult :: VName -> UsageTable -> Bool -- | Has the given name been used directly (i.e. could we rename it or -- remove it without anyone noticing?) isUsedDirectly :: VName -> UsageTable -> Bool -- | Is this name used as the size of something (array or memory block)? isSize :: VName -> UsageTable -> Bool -- | Construct a usage table reflecting that these variables have been -- used. usages :: Names -> UsageTable -- | Construct a usage table where the given variable has been used in this -- specific way. usage :: VName -> Usages -> UsageTable -- | Construct a usage table where the given variable has been consumed. consumedUsage :: VName -> UsageTable -- | Construct a usage table where the given variable has been used in the -- Result of a body. inResultUsage :: VName -> UsageTable -- | Construct a usage table where the given variable has been used as an -- array or memory size. sizeUsage :: VName -> UsageTable -- | Construct a usage table where the given names have been used as an -- array or memory size. sizeUsages :: Names -> UsageTable -- | A description of how a single variable has been used. data Usages -- | Produce a usage table reflecting the use of the free variables in a -- single statement. usageInStm :: (ASTRep rep, Aliased rep) => Stm rep -> UsageTable instance GHC.Show.Show Futhark.Analysis.UsageTable.Usages instance GHC.Classes.Ord Futhark.Analysis.UsageTable.Usages instance GHC.Classes.Eq Futhark.Analysis.UsageTable.Usages instance GHC.Show.Show Futhark.Analysis.UsageTable.UsageTable instance GHC.Classes.Eq Futhark.Analysis.UsageTable.UsageTable instance GHC.Base.Semigroup Futhark.Analysis.UsageTable.UsageTable instance GHC.Base.Monoid Futhark.Analysis.UsageTable.UsageTable instance GHC.Base.Semigroup Futhark.Analysis.UsageTable.Usages instance GHC.Base.Monoid Futhark.Analysis.UsageTable.Usages -- | Facilities for changing the rep of some fragment, with no context. We -- call this "rephrasing", for no deep reason. module Futhark.Analysis.Rephrase -- | Rephrase an entire program. rephraseProg :: Monad m => Rephraser m from to -> Prog from -> m (Prog to) -- | Rephrase a function definition. rephraseFunDef :: Monad m => Rephraser m from to -> FunDef from -> m (FunDef to) -- | Rephrase an expression. rephraseExp :: Monad m => Rephraser m from to -> Exp from -> m (Exp to) -- | Rephrase a body. rephraseBody :: Monad m => Rephraser m from to -> Body from -> m (Body to) -- | Rephrase a statement. rephraseStm :: Monad m => Rephraser m from to -> Stm from -> m (Stm to) -- | Rephrase a lambda. rephraseLambda :: Monad m => Rephraser m from to -> Lambda from -> m (Lambda to) -- | Rephrase a pattern. rephrasePat :: Monad m => (from -> m to) -> PatT from -> m (PatT to) -- | Rephrase a pattern element. rephrasePatElem :: Monad m => (from -> m to) -> PatElemT from -> m (PatElemT to) -- | A collection of functions that together allow us to rephrase some IR -- fragment, in some monad m. If we let m be the -- Maybe monad, we can conveniently do rephrasing that might fail. -- This is useful if you want to see if some IR in e.g. the -- Kernels rep actually uses any Kernels-specific -- operations. data Rephraser m from to Rephraser :: (ExpDec from -> m (ExpDec to)) -> (LetDec from -> m (LetDec to)) -> (FParamInfo from -> m (FParamInfo to)) -> (LParamInfo from -> m (LParamInfo to)) -> (BodyDec from -> m (BodyDec to)) -> (RetType from -> m (RetType to)) -> (BranchType from -> m (BranchType to)) -> (Op from -> m (Op to)) -> Rephraser m from to [rephraseExpDec] :: Rephraser m from to -> ExpDec from -> m (ExpDec to) [rephraseLetBoundDec] :: Rephraser m from to -> LetDec from -> m (LetDec to) [rephraseFParamDec] :: Rephraser m from to -> FParamInfo from -> m (FParamInfo to) [rephraseLParamDec] :: Rephraser m from to -> LParamInfo from -> m (LParamInfo to) [rephraseBodyDec] :: Rephraser m from to -> BodyDec from -> m (BodyDec to) [rephraseRetType] :: Rephraser m from to -> RetType from -> m (RetType to) [rephraseBranchType] :: Rephraser m from to -> BranchType from -> m (BranchType to) [rephraseOp] :: Rephraser m from to -> Op from -> m (Op to) -- | Abstract Syntax Tree metrics. This is used in the futhark -- test program, for the structure stanzas. module Futhark.Analysis.Metrics -- | AST metrics are simply a collection from identifiable node names to -- the number of times that node appears. newtype AstMetrics AstMetrics :: Map Text Int -> AstMetrics -- | Compute the metrics for a program. progMetrics :: OpMetrics (Op rep) => Prog rep -> AstMetrics -- | Compute the metrics for some operation. class OpMetrics op opMetrics :: OpMetrics op => op -> MetricsM () -- | Add this node to the current tally. seen :: Text -> MetricsM () -- | Enclose a metrics counting operation. Most importantly, this prefixes -- the name of the context to all the metrics computed in the enclosed -- operation. inside :: Text -> MetricsM () -> MetricsM () -- | This monad is used for computing metrics. It internally keeps track of -- what we've seen so far. Use seen to add more stuff. data MetricsM a -- | Compute metrics for this statement. stmMetrics :: OpMetrics (Op rep) => Stm rep -> MetricsM () -- | Compute metrics for this lambda. lambdaMetrics :: OpMetrics (Op rep) => Lambda rep -> MetricsM () instance Control.Monad.Writer.Class.MonadWriter Futhark.Analysis.Metrics.CountMetrics Futhark.Analysis.Metrics.MetricsM instance GHC.Base.Functor Futhark.Analysis.Metrics.MetricsM instance GHC.Base.Applicative Futhark.Analysis.Metrics.MetricsM instance GHC.Base.Monad Futhark.Analysis.Metrics.MetricsM instance Futhark.Analysis.Metrics.OpMetrics a => Futhark.Analysis.Metrics.OpMetrics (GHC.Maybe.Maybe a) instance Futhark.Analysis.Metrics.OpMetrics () instance GHC.Base.Semigroup Futhark.Analysis.Metrics.CountMetrics instance GHC.Base.Monoid Futhark.Analysis.Metrics.CountMetrics -- | Facilities for inspecting the data dependencies of a program. module Futhark.Analysis.DataDependencies -- | A mapping from a variable name v, to those variables on which -- the value of v is dependent. The intuition is that we could -- remove all other variables, and v would still be computable. -- This also includes names bound in loops or by lambdas. type Dependencies = Map VName Names -- | Compute the data dependencies for an entire body. dataDependencies :: ASTRep rep => Body rep -> Dependencies -- | findNecessaryForReturned p merge deps computes which of the -- loop parameters (merge) are necessary for the result of the -- loop, where p given a loop parameter indicates whether the -- final value of that parameter is live after the loop. deps is -- the data dependencies of the loop body. This is computed by -- straightforward fixpoint iteration. findNecessaryForReturned :: (Param dec -> Bool) -> [(Param dec, SubExp)] -> Map VName Names -> Names -- | Definition of a polymorphic (generic) pass that can work with programs -- of any rep. module Futhark.Pass -- | The monad in which passes execute. data PassM a -- | Execute a PassM action, yielding logging information and either -- an error text or a result. runPassM :: MonadFreshNames m => PassM a -> m (a, Log) -- | Turn an Either computation into a PassM. If the -- Either is Left, the result is a CompilerBug. liftEither :: Show err => Either err a -> PassM a -- | Turn an Either monadic computation into a PassM. If the -- Either is Left, the result is an exception. liftEitherM :: Show err => PassM (Either err a) -> PassM a -- | A compiler pass transforming a Prog of a given rep to a -- Prog of another rep. data Pass fromrep torep Pass :: String -> String -> (Prog fromrep -> PassM (Prog torep)) -> Pass fromrep torep -- | Name of the pass. Keep this short and simple. It will be used to -- automatically generate a command-line option name via -- passLongOption. [passName] :: Pass fromrep torep -> String -- | A slightly longer description, which will show up in the command-line -- help text. [passDescription] :: Pass fromrep torep -> String [passFunction] :: Pass fromrep torep -> Prog fromrep -> PassM (Prog torep) -- | Take the name of the pass, turn spaces into dashes, and make all -- characters lowercase. passLongOption :: Pass fromrep torep -> String -- | Apply a PassM operation in parallel to multiple elements, -- joining together the name sources and logs, and propagating any error -- properly. parPass :: (a -> PassM b) -> [a] -> PassM [b] -- | Like intraproceduralTransformationWithConsts, but do not change -- the top-level constants, and simply pass along their Scope. intraproceduralTransformation :: (Scope rep -> Stms rep -> PassM (Stms rep)) -> Prog rep -> PassM (Prog rep) -- | Apply some operation to the top-level constants. Then applies an -- operation to all the function function definitions, which are also -- given the transformed constants so they can be brought into scope. The -- function definition transformations are run in parallel (with -- parPass), since they cannot affect each other. intraproceduralTransformationWithConsts :: (Stms fromrep -> PassM (Stms torep)) -> (Stms torep -> FunDef fromrep -> PassM (FunDef torep)) -> Prog fromrep -> PassM (Prog torep) instance GHC.Base.Monad Futhark.Pass.PassM instance GHC.Base.Applicative Futhark.Pass.PassM instance GHC.Base.Functor Futhark.Pass.PassM instance Futhark.Util.Log.MonadLogger Futhark.Pass.PassM instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Pass.PassM -- | This module defines a convenience typeclass for creating normalised -- programs. -- -- See Futhark.Construct for a high-level description. module Futhark.Builder.Class -- | The class of representations that can be constructed solely from an -- expression, within some monad. Very important: the methods should not -- have any significant side effects! They may be called more often than -- you think, and the results thrown away. If used exclusively within a -- MonadBuilder instance, it is acceptable for them to create new -- bindings, however. class (ASTRep rep, FParamInfo rep ~ DeclType, LParamInfo rep ~ Type, RetType rep ~ DeclExtType, BranchType rep ~ ExtType, SetType (LetDec rep)) => Buildable rep mkExpPat :: Buildable rep => [Ident] -> Exp rep -> Pat rep mkExpDec :: Buildable rep => Pat rep -> Exp rep -> ExpDec rep mkBody :: Buildable rep => Stms rep -> Result -> Body rep mkLetNames :: (Buildable rep, MonadFreshNames m, HasScope rep m) => [VName] -> Exp rep -> m (Stm rep) -- | Construct a Stm from identifiers for the context- and value -- part of the pattern, as well as the expression. mkLet :: Buildable rep => [Ident] -> Exp rep -> Stm rep -- | Like mkLet, but also take attributes and certificates from the given -- StmAux. mkLet' :: Buildable rep => [Ident] -> StmAux a -> Exp rep -> Stm rep -- | A monad that supports the creation of bindings from expressions and -- bodies from bindings, with a specific rep. This is the main typeclass -- that a monad must implement in order for it to be useful for -- generating or modifying Futhark code. Most importantly maintains a -- current state of Stms (as well as a Scope) that have -- been added with addStm. -- -- Very important: the methods should not have any significant side -- effects! They may be called more often than you think, and the results -- thrown away. It is acceptable for them to create new bindings, -- however. class (ASTRep (Rep m), MonadFreshNames m, Applicative m, Monad m, LocalScope (Rep m) m) => MonadBuilder m where { type family Rep m :: Type; } mkExpDecM :: MonadBuilder m => Pat (Rep m) -> Exp (Rep m) -> m (ExpDec (Rep m)) mkBodyM :: MonadBuilder m => Stms (Rep m) -> Result -> m (Body (Rep m)) mkLetNamesM :: MonadBuilder m => [VName] -> Exp (Rep m) -> m (Stm (Rep m)) -- | Add a statement to the Stms under construction. addStm :: MonadBuilder m => Stm (Rep m) -> m () -- | Add multiple statements to the Stms under construction. addStms :: MonadBuilder m => Stms (Rep m) -> m () -- | Obtain the statements constructed during a monadic action, instead of -- adding them to the state. collectStms :: MonadBuilder m => m a -> m (a, Stms (Rep m)) -- | Add the provided certificates to any statements added during execution -- of the action. certifying :: MonadBuilder m => Certs -> m a -> m a -- | Add several bindings at the outermost level of a Body. insertStms :: Buildable rep => Stms rep -> Body rep -> Body rep -- | Add a single binding at the outermost level of a Body. insertStm :: Buildable rep => Stm rep -> Body rep -> Body rep -- | Add a statement with the given pattern and expression. letBind :: MonadBuilder m => Pat (Rep m) -> Exp (Rep m) -> m () -- | Add a statement with the given pattern element names and expression. letBindNames :: MonadBuilder m => [VName] -> Exp (Rep m) -> m () -- | As collectStms, but throw away the ordinary result. collectStms_ :: MonadBuilder m => m a -> m (Stms (Rep m)) -- | Add the statements of the body, then return the body result. bodyBind :: MonadBuilder m => Body (Rep m) -> m Result -- | Add the given attributes to any statements added by this action. attributing :: MonadBuilder m => Attrs -> m a -> m a -- | Add the certificates and attributes to any statements added by this -- action. auxing :: MonadBuilder m => StmAux anyrep -> m a -> m a -- | This module defines a convenience monad/typeclass for building ASTs. -- The fundamental building block is BuilderT and its execution -- functions, but it is usually easier to use Builder. -- -- See Futhark.Construct for a high-level description. module Futhark.Builder -- | A monad transformer that tracks statements and provides a -- MonadBuilder instance, assuming that the underlying monad -- provides a name source. In almost all cases, this is what you will use -- for constructing statements (possibly as part of a larger monad -- stack). If you find yourself needing to implement MonadBuilder -- from scratch, then it is likely that you are making a mistake. data BuilderT rep m a -- | Run a binder action given an initial scope, returning a value and the -- statements added (addStm) during the action. runBuilderT :: MonadFreshNames m => BuilderT rep m a -> Scope rep -> m (a, Stms rep) -- | Like runBuilderT, but return only the statements. runBuilderT_ :: MonadFreshNames m => BuilderT rep m () -> Scope rep -> m (Stms rep) -- | Like runBuilderT, but get the initial scope from the current -- monad. runBuilderT' :: (MonadFreshNames m, HasScope somerep m, SameScope somerep rep) => BuilderT rep m a -> m (a, Stms rep) -- | Like runBuilderT_, but get the initial scope from the current -- monad. runBuilderT'_ :: (MonadFreshNames m, HasScope somerep m, SameScope somerep rep) => BuilderT rep m a -> m (Stms rep) -- | A BuilderT (and by extension, a Builder) is only an -- instance of MonadBuilder for representations that implement -- this type class, which contains methods for constructing statements. class ASTRep rep => BuilderOps rep mkExpDecB :: (BuilderOps rep, MonadBuilder m, Rep m ~ rep) => Pat rep -> Exp rep -> m (ExpDec rep) mkBodyB :: (BuilderOps rep, MonadBuilder m, Rep m ~ rep) => Stms rep -> Result -> m (Body rep) mkLetNamesB :: (BuilderOps rep, MonadBuilder m, Rep m ~ rep) => [VName] -> Exp rep -> m (Stm rep) mkExpDecB :: (BuilderOps rep, MonadBuilder m, Buildable rep) => Pat rep -> Exp rep -> m (ExpDec rep) mkBodyB :: (BuilderOps rep, MonadBuilder m, Buildable rep) => Stms rep -> Result -> m (Body rep) mkLetNamesB :: (BuilderOps rep, MonadBuilder m, Rep m ~ rep, Buildable rep) => [VName] -> Exp rep -> m (Stm rep) -- | The most commonly used binder monad. type Builder rep = BuilderT rep (State VNameSource) -- | Run a binder action, returning a value and the statements added -- (addStm) during the action. Assumes that the current monad -- provides initial scope and name source. runBuilder :: (MonadFreshNames m, HasScope somerep m, SameScope somerep rep) => Builder rep a -> m (a, Stms rep) -- | Like runBuilder, but throw away the result and just return the -- added statements. runBuilder_ :: (MonadFreshNames m, HasScope somerep m, SameScope somerep rep) => Builder rep a -> m (Stms rep) -- | Run a binder that produces a Body, and prefix that Body -- by the statements produced during execution of the action. runBodyBuilder :: (Buildable rep, MonadFreshNames m, HasScope somerep m, SameScope somerep rep) => Builder rep (Body rep) -> m (Body rep) instance GHC.Base.Monad m => GHC.Base.Applicative (Futhark.Builder.BuilderT rep m) instance GHC.Base.Monad m => GHC.Base.Monad (Futhark.Builder.BuilderT rep m) instance GHC.Base.Functor m => GHC.Base.Functor (Futhark.Builder.BuilderT rep m) instance Control.Monad.Trans.Class.MonadTrans (Futhark.Builder.BuilderT rep) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Futhark.Builder.BuilderT rep m) instance (Futhark.IR.Prop.ASTRep rep, GHC.Base.Monad m) => Futhark.IR.Prop.Scope.HasScope rep (Futhark.Builder.BuilderT rep m) instance (Futhark.IR.Prop.ASTRep rep, GHC.Base.Monad m) => Futhark.IR.Prop.Scope.LocalScope rep (Futhark.Builder.BuilderT rep m) instance (Futhark.IR.Prop.ASTRep rep, Futhark.MonadFreshNames.MonadFreshNames m, Futhark.Builder.BuilderOps rep) => Futhark.Builder.Class.MonadBuilder (Futhark.Builder.BuilderT rep m) instance Control.Monad.Reader.Class.MonadReader r m => Control.Monad.Reader.Class.MonadReader r (Futhark.Builder.BuilderT rep m) instance Control.Monad.State.Class.MonadState s m => Control.Monad.State.Class.MonadState s (Futhark.Builder.BuilderT rep m) instance Control.Monad.Writer.Class.MonadWriter w m => Control.Monad.Writer.Class.MonadWriter w (Futhark.Builder.BuilderT rep m) instance Control.Monad.Error.Class.MonadError e m => Control.Monad.Error.Class.MonadError e (Futhark.Builder.BuilderT rep m) -- | A representation where all bindings are annotated with aliasing -- information. module Futhark.IR.Aliases -- | The rep for the basic representation. data Aliases rep -- | A wrapper around AliasDec to get around the fact that we need -- an Ord instance, which 'AliasDec does not have. newtype AliasDec AliasDec :: Names -> AliasDec [unAliases] :: AliasDec -> Names -- | The aliases of the let-bound variable. type VarAliases = AliasDec -- | Everything consumed in the expression. type ConsumedInExp = AliasDec -- | The aliases of what is returned by the Body, and what is -- consumed inside of it. type BodyAliasing = ([VarAliases], ConsumedInExp) addAliasesToPat :: (ASTRep rep, CanBeAliased (Op rep), Typed dec) => PatT dec -> Exp (Aliases rep) -> PatT (VarAliases, dec) mkAliasedLetStm :: (ASTRep rep, CanBeAliased (Op rep)) => Pat rep -> StmAux (ExpDec rep) -> Exp (Aliases rep) -> Stm (Aliases rep) mkAliasedBody :: (ASTRep rep, CanBeAliased (Op rep)) => BodyDec rep -> Stms (Aliases rep) -> Result -> Body (Aliases rep) mkPatAliases :: (Aliased rep, Typed dec) => PatT dec -> Exp rep -> [PatElemT (VarAliases, dec)] mkBodyAliases :: Aliased rep => Stms rep -> Result -> BodyAliasing removeProgAliases :: CanBeAliased (Op rep) => Prog (Aliases rep) -> Prog rep removeFunDefAliases :: CanBeAliased (Op rep) => FunDef (Aliases rep) -> FunDef rep removeExpAliases :: CanBeAliased (Op rep) => Exp (Aliases rep) -> Exp rep removeStmAliases :: CanBeAliased (Op rep) => Stm (Aliases rep) -> Stm rep removeLambdaAliases :: CanBeAliased (Op rep) => Lambda (Aliases rep) -> Lambda rep removePatAliases :: PatT (AliasDec, a) -> PatT a removeScopeAliases :: Scope (Aliases rep) -> Scope rep type AliasesAndConsumed = (Map VName Names, Names) trackAliases :: Aliased rep => AliasesAndConsumed -> Stm rep -> AliasesAndConsumed -- | The aliases of the result and everything consumed in the given -- statements. mkStmsAliases :: Aliased rep => Stms rep -> Result -> ([Names], Names) instance GHC.Show.Show Futhark.IR.Aliases.AliasDec instance (Futhark.IR.Rep.RepTypes rep, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep)) => Futhark.IR.Rep.RepTypes (Futhark.IR.Aliases.Aliases rep) instance Futhark.IR.Prop.Aliases.AliasesOf (Futhark.IR.Aliases.VarAliases, dec) instance GHC.Base.Semigroup Futhark.IR.Aliases.AliasDec instance GHC.Base.Monoid Futhark.IR.Aliases.AliasDec instance GHC.Classes.Eq Futhark.IR.Aliases.AliasDec instance GHC.Classes.Ord Futhark.IR.Aliases.AliasDec instance Futhark.Transform.Rename.Rename Futhark.IR.Aliases.AliasDec instance Futhark.Transform.Substitute.Substitute Futhark.IR.Aliases.AliasDec instance Futhark.IR.Prop.Names.FreeIn Futhark.IR.Aliases.AliasDec instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Aliases.AliasDec instance Futhark.IR.Prop.Names.FreeDec Futhark.IR.Aliases.AliasDec instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep)) => Futhark.IR.Prop.Aliases.Aliased (Futhark.IR.Aliases.Aliases rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep)) => Futhark.IR.Pretty.PrettyRep (Futhark.IR.Aliases.Aliases rep) instance (Futhark.Builder.Class.Buildable rep, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep)) => Futhark.Builder.Class.Buildable (Futhark.IR.Aliases.Aliases rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep)) => Futhark.IR.Prop.ASTRep (Futhark.IR.Aliases.Aliases rep) instance (Futhark.IR.Prop.ASTRep (Futhark.IR.Aliases.Aliases rep), Futhark.Builder.Class.Buildable (Futhark.IR.Aliases.Aliases rep)) => Futhark.Builder.BuilderOps (Futhark.IR.Aliases.Aliases rep) -- | Representation used by the simplification engine. module Futhark.Optimise.Simplify.Rep data Wise rep -- | The wisdom of the let-bound variable. newtype VarWisdom VarWisdom :: VarAliases -> VarWisdom [varWisdomAliases] :: VarWisdom -> VarAliases -- | Wisdom about an expression. data ExpWisdom removeStmWisdom :: CanBeWise (Op rep) => Stm (Wise rep) -> Stm rep removeLambdaWisdom :: CanBeWise (Op rep) => Lambda (Wise rep) -> Lambda rep removeFunDefWisdom :: CanBeWise (Op rep) => FunDef (Wise rep) -> FunDef rep removeExpWisdom :: CanBeWise (Op rep) => Exp (Wise rep) -> Exp rep removePatWisdom :: PatT (VarWisdom, a) -> PatT a removeBodyWisdom :: CanBeWise (Op rep) => Body (Wise rep) -> Body rep removeScopeWisdom :: Scope (Wise rep) -> Scope rep addScopeWisdom :: Scope rep -> Scope (Wise rep) addWisdomToPat :: (ASTRep rep, CanBeWise (Op rep)) => Pat rep -> Exp (Wise rep) -> Pat (Wise rep) mkWiseBody :: (ASTRep rep, CanBeWise (Op rep)) => BodyDec rep -> Stms (Wise rep) -> Result -> Body (Wise rep) mkWiseLetStm :: (ASTRep rep, CanBeWise (Op rep)) => Pat rep -> StmAux (ExpDec rep) -> Exp (Wise rep) -> Stm (Wise rep) mkWiseExpDec :: (ASTRep rep, CanBeWise (Op rep)) => Pat (Wise rep) -> ExpDec rep -> Exp (Wise rep) -> ExpDec (Wise rep) class (AliasedOp (OpWithWisdom op), IsOp (OpWithWisdom op)) => CanBeWise op where { type family OpWithWisdom op :: Type; } removeOpWisdom :: CanBeWise op => OpWithWisdom op -> op instance GHC.Show.Show Futhark.Optimise.Simplify.Rep.VarWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Rep.VarWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Rep.VarWisdom instance GHC.Show.Show Futhark.Optimise.Simplify.Rep.ExpWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Rep.ExpWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Rep.ExpWisdom instance GHC.Show.Show Futhark.Optimise.Simplify.Rep.BodyWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Rep.BodyWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Rep.BodyWisdom instance (Futhark.IR.Rep.RepTypes rep, Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Rep.Op rep)) => Futhark.IR.Rep.RepTypes (Futhark.Optimise.Simplify.Rep.Wise rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Rep.Op rep)) => Futhark.IR.Prop.ASTRep (Futhark.Optimise.Simplify.Rep.Wise rep) instance (Futhark.IR.Pretty.PrettyRep rep, Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Rep.Op rep)) => Futhark.IR.Pretty.PrettyRep (Futhark.Optimise.Simplify.Rep.Wise rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Rep.Op rep)) => Futhark.IR.Prop.Aliases.Aliased (Futhark.Optimise.Simplify.Rep.Wise rep) instance (Futhark.Builder.Class.Buildable rep, Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Rep.Op rep)) => Futhark.Builder.Class.Buildable (Futhark.Optimise.Simplify.Rep.Wise rep) instance Futhark.Optimise.Simplify.Rep.CanBeWise () instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Rep.BodyWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Rep.BodyWisdom instance Futhark.IR.Prop.Names.FreeIn Futhark.Optimise.Simplify.Rep.BodyWisdom instance Futhark.IR.Prop.Names.FreeDec Futhark.Optimise.Simplify.Rep.BodyWisdom instance Futhark.IR.Prop.Names.FreeIn Futhark.Optimise.Simplify.Rep.ExpWisdom instance Futhark.IR.Prop.Names.FreeDec Futhark.Optimise.Simplify.Rep.ExpWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Rep.ExpWisdom instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Rep.ExpWisdom instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Rep.VarWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Rep.VarWisdom instance Futhark.IR.Prop.Names.FreeIn Futhark.Optimise.Simplify.Rep.VarWisdom instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Optimise.Simplify.Rep.VarWisdom instance Futhark.IR.Prop.Aliases.AliasesOf (Futhark.Optimise.Simplify.Rep.VarWisdom, dec) -- | Alias analysis of a full Futhark program. Takes as input a program -- with an arbitrary rep and produces one with aliases. This module does -- not implement the aliasing logic itself, and derives its information -- from definitions in Futhark.IR.Prop.Aliases and -- Futhark.IR.Aliases. The alias information computed here will -- include transitive aliases (note that this is not what the building -- blocks do). module Futhark.Analysis.Alias -- | Perform alias analysis on a Futhark program. aliasAnalysis :: (ASTRep rep, CanBeAliased (Op rep)) => Prog rep -> Prog (Aliases rep) analyseFun :: (ASTRep rep, CanBeAliased (Op rep)) => FunDef rep -> FunDef (Aliases rep) analyseStms :: (ASTRep rep, CanBeAliased (Op rep)) => AliasTable -> Stms rep -> (Stms (Aliases rep), AliasesAndConsumed) analyseExp :: (ASTRep rep, CanBeAliased (Op rep)) => AliasTable -> Exp rep -> Exp (Aliases rep) analyseBody :: (ASTRep rep, CanBeAliased (Op rep)) => AliasTable -> Body rep -> Body (Aliases rep) analyseLambda :: (ASTRep rep, CanBeAliased (Op rep)) => AliasTable -> Lambda rep -> Lambda (Aliases rep) -- |
-- z <- letExp "z" $ BasicOp $ BinOp (Add Int32) (Var x) (Var y) ---- --
-- Scatter length lambda inputs outputs ---- -- Scatter maps values from a set of input arrays to indices and values -- of a set of output arrays. It is able to write multiple values to -- multiple outputs each of which may have multiple dimensions. -- -- inputs is a list of input arrays, all having size -- length, elements of which are applied to the lambda -- function. For instance, if there are two arrays, lambda will -- get two values as input, one from each array. -- -- outputs specifies the result of the lambda and which -- arrays to write to. Each element of the list consists of a -- VName specifying which array to scatter to, a Shape -- describing the shape of that array, and an Int describing how -- many elements should be written to that array for each invocation of -- the lambda. -- -- lambda is a function that takes inputs from inputs and -- returns values according to the output-specification in -- outputs. It returns values in the following manner: -- --
-- Hist length dest-arrays-and-ops fun arrays ---- -- The first SubExp is the length of the input arrays. The first list -- describes the operations to perform. The Lambda is the bucket -- function. Finally comes the input images. Hist :: SubExp -> [HistOp rep] -> Lambda rep -> [VName] -> SOAC rep -- | A combination of scan, reduction, and map. The first SubExp is -- the size of the input arrays. Screma :: SubExp -> [VName] -> ScremaForm rep -> SOAC rep -- | Is the stream chunk required to correspond to a contiguous subsequence -- of the original input (InOrder) or not? Disorder streams -- can be more efficient, but not all algorithms work with this. data StreamOrd InOrder :: StreamOrd Disorder :: StreamOrd -- | What kind of stream is this? data StreamForm rep Parallel :: StreamOrd -> Commutativity -> Lambda rep -> StreamForm rep Sequential :: StreamForm rep -- | The essential parts of a Screma factored out (everything except -- the input arrays). data ScremaForm rep ScremaForm :: [Scan rep] -> [Reduce rep] -> Lambda rep -> ScremaForm rep -- | Information about computing a single histogram. data HistOp rep HistOp :: SubExp -> SubExp -> [VName] -> [SubExp] -> Lambda rep -> HistOp rep [histWidth] :: HistOp rep -> SubExp -- | Race factor RF means that only 1/RF bins are used. [histRaceFactor] :: HistOp rep -> SubExp [histDest] :: HistOp rep -> [VName] [histNeutral] :: HistOp rep -> [SubExp] [histOp] :: HistOp rep -> Lambda rep -- | How to compute a single scan result. data Scan rep Scan :: Lambda rep -> [SubExp] -> Scan rep [scanLambda] :: Scan rep -> Lambda rep [scanNeutral] :: Scan rep -> [SubExp] -- | How many reduction results are produced by these Scans? scanResults :: [Scan rep] -> Int -- | Combine multiple scan operators to a single operator. singleScan :: Buildable rep => [Scan rep] -> Scan rep -- | How to compute a single reduction result. data Reduce rep Reduce :: Commutativity -> Lambda rep -> [SubExp] -> Reduce rep [redComm] :: Reduce rep -> Commutativity [redLambda] :: Reduce rep -> Lambda rep [redNeutral] :: Reduce rep -> [SubExp] -- | How many reduction results are produced by these Reduces? redResults :: [Reduce rep] -> Int -- | Combine multiple reduction operators to a single operator. singleReduce :: Buildable rep => [Reduce rep] -> Reduce rep -- | The types produced by a single Screma, given the size of the -- input array. scremaType :: SubExp -> ScremaForm rep -> [Type] -- | The type of a SOAC. soacType :: SOAC rep -> [Type] -- | Type-check a SOAC. typeCheckSOAC :: Checkable rep => SOAC (Aliases rep) -> TypeM rep () -- | Construct a lambda that takes parameters of the given types and simply -- returns them unchanged. mkIdentityLambda :: (Buildable rep, MonadFreshNames m) => [Type] -> m (Lambda rep) -- | Is the given lambda an identity lambda? isIdentityLambda :: Lambda rep -> Bool -- | A lambda with no parameters that returns no values. nilFn :: Buildable rep => Lambda rep -- | Construct a Screma with possibly multiple scans, and the given map -- function. scanomapSOAC :: [Scan rep] -> Lambda rep -> ScremaForm rep -- | Construct a Screma with possibly multiple reductions, and the given -- map function. redomapSOAC :: [Reduce rep] -> Lambda rep -> ScremaForm rep -- | Construct a Screma with possibly multiple scans, and identity map -- function. scanSOAC :: (Buildable rep, MonadFreshNames m) => [Scan rep] -> m (ScremaForm rep) -- | Construct a Screma with possibly multiple reductions, and identity map -- function. reduceSOAC :: (Buildable rep, MonadFreshNames m) => [Reduce rep] -> m (ScremaForm rep) -- | Construct a Screma corresponding to a map. mapSOAC :: Lambda rep -> ScremaForm rep -- | Does this Screma correspond to a scan-map composition? isScanomapSOAC :: ScremaForm rep -> Maybe ([Scan rep], Lambda rep) -- | Does this Screma correspond to a reduce-map composition? isRedomapSOAC :: ScremaForm rep -> Maybe ([Reduce rep], Lambda rep) -- | Does this Screma correspond to pure scan? isScanSOAC :: ScremaForm rep -> Maybe [Scan rep] -- | Does this Screma correspond to a pure reduce? isReduceSOAC :: ScremaForm rep -> Maybe [Reduce rep] -- | Does this Screma correspond to a simple map, without any reduction or -- scan results? isMapSOAC :: ScremaForm rep -> Maybe (Lambda rep) -- | Prettyprint the given Screma. ppScrema :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> ScremaForm rep -> Doc -- | Prettyprint the given histogram operation. ppHist :: (PrettyRep rep, Pretty inp) => SubExp -> [HistOp rep] -> Lambda rep -> [inp] -> Doc -- |
-- groupScatterResults specification results ---- -- Groups the index values and result values of results according -- to the specification. -- -- This function is used for extracting and grouping the results of a -- scatter. In the SOAC representation, the lambda inside a -- Scatter returns all indices and values as one big list. This -- function groups each value with its corresponding indices (as -- determined by the Shape of the output array). -- -- The elements of the resulting list correspond to the shape and name of -- the output parameters, in addition to a list of values written to that -- output parameter, along with the array indices marking where to write -- them to. -- -- See Scatter for more information. groupScatterResults :: [(Shape, Int, array)] -> [a] -> [(Shape, array, [([a], a)])] -- |
-- groupScatterResults' specification results ---- -- Groups the index values and result values of results according -- to the output specification. This is the simpler version of -- groupScatterResults, which doesn't return any information -- about shapes or output arrays. -- -- See groupScatterResults for more information, groupScatterResults' :: [(Shape, Int, array)] -> [a] -> [([a], a)] -- |
-- splitScatterResults specification results ---- -- Splits the results array into indices and values according to the -- output specification. -- -- See groupScatterResults for more information. splitScatterResults :: [(Shape, Int, array)] -> [a] -> ([a], [a]) -- | Like Mapper, but just for SOACs. data SOACMapper frep trep m SOACMapper :: (SubExp -> m SubExp) -> (Lambda frep -> m (Lambda trep)) -> (VName -> m VName) -> SOACMapper frep trep m [mapOnSOACSubExp] :: SOACMapper frep trep m -> SubExp -> m SubExp [mapOnSOACLambda] :: SOACMapper frep trep m -> Lambda frep -> m (Lambda trep) [mapOnSOACVName] :: SOACMapper frep trep m -> VName -> m VName -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper rep rep m -- | Map a monadic action across the immediate children of a SOAC. The -- mapping does not descend recursively into subexpressions and is done -- left-to-right. mapSOACM :: (Applicative m, Monad m) => SOACMapper frep trep m -> SOAC frep -> m (SOAC trep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SOACS.SOAC.HistOp rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.HistOp rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.HistOp rep) instance GHC.Show.Show Futhark.IR.SOACS.SOAC.StreamOrd instance GHC.Classes.Ord Futhark.IR.SOACS.SOAC.StreamOrd instance GHC.Classes.Eq Futhark.IR.SOACS.SOAC.StreamOrd instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SOACS.SOAC.StreamForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.StreamForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.StreamForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SOACS.SOAC.Scan rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.Scan rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.Scan rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SOACS.SOAC.Reduce rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.Reduce rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.Reduce rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SOACS.SOAC.ScremaForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.ScremaForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.ScremaForm rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Prop.ASTRep rep => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Prop.ASTRep rep => Futhark.Transform.Substitute.Substitute (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Prop.ASTRep rep => Futhark.Transform.Rename.Rename (Futhark.IR.SOACS.SOAC.SOAC rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.ASTRep (Futhark.IR.Aliases.Aliases rep), Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep)) => Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.SOACS.SOAC.SOAC rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Rep.Op rep)) => Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Prop.TypeOf.TypedOp (Futhark.IR.SOACS.SOAC.SOAC rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.Aliased rep) => Futhark.IR.Prop.Aliases.AliasedOp (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Prop.ASTRep rep => Futhark.IR.Prop.IsOp (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Rep.RepTypes rep => Futhark.Analysis.SymbolTable.IndexOp (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.Rep.Op rep) => Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SOACS.SOAC.SOAC rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SOACS.SOAC.Reduce rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SOACS.SOAC.Scan rep) -- | An unstructured grab-bag of various tools and inspection functions -- that didn't really fit anywhere else. module Futhark.Tools -- | Turns a binding of a redomap into two seperate bindings, a -- map binding and a reduce binding (returned in that -- order). -- -- Reuses the original pattern for the reduce, and creates a new -- pattern with new Idents for the result of the map. redomapToMapAndReduce :: (MonadFreshNames m, Buildable rep, ExpDec rep ~ (), Op rep ~ SOAC rep) => Pat rep -> (SubExp, [Reduce rep], LambdaT rep, [VName]) -> m (Stm rep, Stm rep) -- | Turn a Screma into a Scanomap (possibly with mapout parts) and a -- Redomap. This is used to handle Scremas that are so complicated that -- we cannot directly generate efficient parallel code for them. In -- essense, what happens is the opposite of horisontal fusion. dissectScrema :: (MonadBuilder m, Op (Rep m) ~ SOAC (Rep m), Buildable (Rep m)) => Pat (Rep m) -> SubExp -> ScremaForm (Rep m) -> [VName] -> m () -- | Turn a stream SOAC into statements that apply the stream lambda to the -- entire input. sequentialStreamWholeArray :: (MonadBuilder m, Buildable (Rep m)) => Pat (Rep m) -> SubExp -> [SubExp] -> LambdaT (Rep m) -> [VName] -> m () -- | Split the parameters of a stream reduction lambda into the chunk size -- parameter, the accumulator parameters, and the input chunk parameters. -- The integer argument is how many accumulators are used. partitionChunkedFoldParameters :: Int -> [Param dec] -> (Param dec, [Param dec], [Param dec]) -- | A simple representation with SOACs and nested parallelism. module Futhark.IR.SOACS -- | The rep for the basic representation. data SOACS type Body = Body SOACS type Stm = Stm SOACS type Pat = Pat SOACS type Exp = Exp SOACS type Lambda = Lambda SOACS type FParam = FParam SOACS type LParam = LParam SOACS type RetType = RetType SOACS type PatElem = PatElem SOACS -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 data Half -- | The SrcLoc of a Located value. srclocOf :: Located a => a -> SrcLoc -- | Location type, consisting of a beginning position and an end position. data Loc -- | Source location type. Source location are all equal, which allows AST -- nodes to be compared modulo location information. data SrcLoc -- | Located values have a location. class Located a locOf :: Located a => a -> Loc locOfList :: Located a => [a] -> Loc -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they always return a -- boolean value. The somewhat ugly constructor names are straight out of -- LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> Overflow -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> Overflow -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> Overflow -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> Safety -> BinOp -- | Unsigned integer division. Rounds towards positive infinity. UDivUp :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards positive infinity. SDivUp :: IntType -> Safety -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Floating-point modulus. FMod :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> Safety -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM and integer division in C. SQuot :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM and integer modulo in C. SRem :: IntType -> Safety -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. -- -- For operations like integer division, a safe division will not explode -- the computer in case of division by zero, but instead return some -- unspecified value. This always involves a run-time check, so generally -- the unsafe variant is what the compiler will insert, but guarded by an -- explicit assertion elsewhere. Safe operations are useful when the -- optimiser wants to move e.g. a division to a location where the -- divisor may be zero, but where the result will only be used when it is -- non-zero (so it doesn't matter what result is provided with a zero -- divisor, as long as the program keeps running). data Safety Unsafe :: Safety Safe :: Safety -- | What to do in case of arithmetic overflow. Futhark's semantics are -- that overflow does wraparound, but for generated code (like address -- arithmetic), it can be beneficial for overflow to be undefined -- behaviour, as it allows better optimisation of things such as GPU -- kernels. -- -- Note that all values of this type are considered equal for Eq -- and Ord. data Overflow OverflowWrap :: Overflow OverflowUndef :: Overflow -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Floating-point sign function. FSignum :: FloatType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type Unit. UnitValue :: PrimValue -- | A floating-point value. data FloatValue Float16Value :: !Half -> FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType -- | An informationless type - still takes up space! Unit :: PrimType -- | A floating point type. data FloatType Float16 :: FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue -- | The type of an integer value. intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue -- | The type of a floating-point value. floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] -- | Apply an UnOp to an operand. Returns Nothing if the -- application is mistyped. doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue -- | Apply a BinOp to an operand. Returns Nothing if the -- application is mistyped, or outside the domain (e.g. division by -- zero). doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue -- | Apply a ConvOp to an operand. Returns Nothing if the -- application is mistyped. doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Turn the conversion the other way around. Note that most conversions -- are lossy, so there is no guarantee the value will round-trip. flipConvOp :: ConvOp -> ConvOp -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue -- | Apply a CmpOp to an operand. Returns Nothing if the -- application is mistyped. doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to Int64. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | Is the given integer value kind of zero? zeroIshInt :: IntValue -> Bool -- | Is the given integer value kind of one? oneIshInt :: IntValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | The size of a value of a given integer type in eight-bit bytes. intByteSize :: Num a => IntType -> a -- | The size of a value of a given floating-point type in eight-bit bytes. floatByteSize :: Num a => FloatType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool -- | The human-readable name for a ConvOp. This is used to expose -- the ConvOp in the intrinsics module of a Futhark -- program. convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. This follows the GNU coding -- standards for error messages: -- https://www.gnu.org/prep/standards/html_node/Errors.html -- -- This function assumes that both start and end position is in the same -- file (it is not clear what the alternative would even mean). locStr :: Located a => a -> String -- | Like locStr, but locStrRel prev now prints the -- location now with the file name left out if the same as -- prev. This is useful when printing messages that are all in -- the context of some initially printed location (e.g. the first mention -- contains the file name; the rest just line and column name). locStrRel :: (Located a, Located b) => a -> b -> String -- | Given a list of strings representing entries in the stack trace and -- the index of the frame to highlight, produce a final -- newline-terminated string for showing to the user. This string should -- also be preceded by a newline. The most recent stack frame must come -- first in the list. prettyStacktrace :: Int -> [String] -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | Enclose a string in the prefered quotes used in error messages. These -- are picked to not collide with characters permitted in identifiers. quote :: String -> String -- | As quote, but works on prettyprinted representation. pquote :: Doc -> Doc -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time value. ErrorVal :: PrimType -> a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | An element of a pattern - consisting of a name and an addditional -- parametric decoration. This decoration is what is expected to contain -- the type of the resulting variable. data PatElemT dec data FlatSlice d FlatSlice :: d -> [FlatDimIndex d] -> FlatSlice d data FlatDimIndex d FlatDimIndex :: d -> d -> FlatDimIndex d -- | A list of DimIndexs, indicating how an array should be sliced. -- Whenever a function accepts a Slice, that slice should be -- total, i.e, cover all dimensions of the array. Deviators should be -- indicated by taking a list of DimIndexes instead. newtype Slice d Slice :: [DimIndex d] -> Slice d [unSlice] :: Slice d -> [DimIndex d] -- | How to index a single dimension of an array. data DimIndex d -- | Fix index in this dimension. DimFix :: d -> DimIndex d -- | DimSlice start_offset num_elems stride. DimSlice :: d -> d -> d -> DimIndex d -- | A function or lambda parameter. data Param dec Param :: VName -> dec -> Param dec -- | Name of the parameter. [paramName] :: Param dec -> VName -- | Function parameter decoration. [paramDec] :: Param dec -> dec -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A list of names used for certificates in some expressions. newtype Certs Certs :: [VName] -> Certs [unCerts] :: Certs -> [VName] -- | An identifier consists of its name and the type of the value bound to -- the identifier. data Ident Ident :: VName -> Type -> Ident [identName] :: Ident -> VName [identType] :: Ident -> Type -- | Information about which parts of a value/type are consumed. For -- example, we might say that a function taking three arguments of types -- ([int], *[int], [int]) has diet [Observe, Consume, -- Observe]. data Diet -- | Consumes this value. Consume :: Diet -- | Only observes value in this position, does not consume. A result may -- alias this. Observe :: Diet -- | As Observe, but the result will not alias, because the -- parameter does not carry aliases. ObservePrim :: Diet -- | An ExtType with uniqueness information, used for function -- return types. type DeclExtType = TypeBase ExtShape Uniqueness -- | A type with shape and uniqueness information, used declaring return- -- and parameters types. type DeclType = TypeBase Shape Uniqueness -- | A type with existentially quantified shapes - used as part of function -- (and function-like) return types. Generally only makes sense when used -- in a list. type ExtType = TypeBase ExtShape NoUniqueness -- | A type with shape information, used for describing the type of -- variables. type Type = TypeBase Shape NoUniqueness -- | The type of a value. When comparing types for equality with ==, -- shapes must match. data TypeBase shape u Prim :: PrimType -> TypeBase shape u -- | Token, index space, element type, and uniqueness. Acc :: VName -> Shape -> [Type] -> u -> TypeBase shape u Array :: PrimType -> shape -> u -> TypeBase shape u Mem :: Space -> TypeBase shape u -- | A fancier name for () - encodes no uniqueness information. data NoUniqueness NoUniqueness :: NoUniqueness -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceId depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A special kind of memory that is a statically sized array of some -- primitive type. Used for private memory on GPUs. ScalarSpace :: [SubExp] -> PrimType -> Space -- | A class encompassing types containing array shape information. class (Monoid a, Eq a, Ord a) => ArrayShape a -- | Return the rank of an array with the given size. shapeRank :: ArrayShape a => a -> Int -- | stripDims n shape strips the outer n dimensions from -- shape. stripDims :: ArrayShape a => Int -> a -> a -- | Check whether one shape if a subset of another shape. subShapeOf :: ArrayShape a => a -> a -> Bool -- | The size of an array type as merely the number of dimensions, with no -- further information. newtype Rank Rank :: Int -> Rank -- | Like Shape but some of its elements may be bound in a local -- environment instead. These are denoted with integral indices. type ExtShape = ShapeBase ExtSize -- | The size of this dimension. type ExtSize = Ext SubExp -- | Something that may be existential. data Ext a Ext :: Int -> Ext a Free :: a -> Ext a -- | The size of an array as a list of subexpressions. If a variable, that -- variable must be in scope where this array is used. type Shape = ShapeBase SubExp -- | The size of an array type as a list of its dimension sizes, with the -- type of sizes being parametric. newtype ShapeBase d Shape :: [d] -> ShapeBase d [shapeDims] :: ShapeBase d -> [d] -- | Whether some operator is commutative or not. The Monoid -- instance returns the least commutative of its arguments. data Commutativity Noncommutative :: Commutativity Commutative :: Commutativity -- | If the argument is a DimFix, return its component. dimFix :: DimIndex d -> Maybe d -- | If the slice is all DimFixs, return the components. sliceIndices :: Slice d -> Maybe [d] -- | The dimensions of the array produced by this slice. sliceDims :: Slice d -> [d] -- | A slice with a stride of one. unitSlice :: Num d => d -> d -> DimIndex d -- | Fix the DimSlices of a slice. The number of indexes must equal -- the length of sliceDims for the slice. fixSlice :: Num d => Slice d -> [d] -> [d] -- | Further slice the DimSlices of a slice. The number of slices -- must equal the length of sliceDims for the slice. sliceSlice :: Num d => Slice d -> Slice d -> Slice d flatSliceDims :: FlatSlice d -> [d] flatSliceStrides :: FlatSlice d -> [d] -- | How many non-constant parts does the error message have, and what is -- their type? errorMsgArgTypes :: ErrorMsg a -> [PrimType] -- | A type representing the return type of a function. In practice, a list -- of these will be used. It should contain at least the information -- contained in an ExtType, but may have more, notably an -- existential context. class (Show rt, Eq rt, Ord rt, DeclExtTyped rt) => IsRetType rt -- | Contruct a return type from a primitive type. primRetType :: IsRetType rt => PrimType -> rt -- | Given a function return type, the parameters of the function, and the -- arguments for a concrete call, return the instantiated return type for -- the concrete call, if valid. applyRetType :: (IsRetType rt, Typed dec) => [rt] -> [Param dec] -> [(SubExp, Type)] -> Maybe [rt] -- | A type representing the return type of a body. It should contain at -- least the information contained in a list of ExtTypes, but may -- have more, notably an existential context. class (Show rt, Eq rt, Ord rt, ExtTyped rt) => IsBodyType rt -- | Construct a body type from a primitive type. primBodyType :: IsBodyType rt => PrimType -> rt -- | Given shape parameter names and types, produce the types of arguments -- accepted. expectedTypes :: Typed t => [VName] -> [t] -> [SubExp] -> [Type] -- | A collection of type families giving various common types for a -- representation, along with constraints specifying that the types they -- map to should satisfy some minimal requirements. class (Show (LetDec l), Show (ExpDec l), Show (BodyDec l), Show (FParamInfo l), Show (LParamInfo l), Show (RetType l), Show (BranchType l), Show (Op l), Eq (LetDec l), Eq (ExpDec l), Eq (BodyDec l), Eq (FParamInfo l), Eq (LParamInfo l), Eq (RetType l), Eq (BranchType l), Eq (Op l), Ord (LetDec l), Ord (ExpDec l), Ord (BodyDec l), Ord (FParamInfo l), Ord (LParamInfo l), Ord (RetType l), Ord (BranchType l), Ord (Op l), IsRetType (RetType l), IsBodyType (BranchType l), Typed (FParamInfo l), Typed (LParamInfo l), Typed (LetDec l), DeclTyped (FParamInfo l)) => RepTypes l where { -- | Decoration for every let-pattern element. type family LetDec l :: Type; -- | Decoration for every expression. type family ExpDec l :: Type; -- | Decoration for every body. type family BodyDec l :: Type; -- | Decoration for every (non-lambda) function parameter. type family FParamInfo l :: Type; -- | Decoration for every lambda function parameter. type family LParamInfo l :: Type; -- | The return type decoration of branches. type family BranchType l :: Type; -- | Extensible operation. type family Op l :: Type; type LetDec l = Type; type ExpDec l = (); type BodyDec l = (); type FParamInfo l = DeclType; type LParamInfo l = Type; type RetType l = DeclExtType; type BranchType l = ExtType; type Op l = (); } -- | An entire Futhark program. data Prog rep Prog :: Stms rep -> [FunDef rep] -> Prog rep -- | Top-level constants that are computed at program startup, and which -- are in scope inside all functions. [progConsts] :: Prog rep -> Stms rep -- | The functions comprising the program. All funtions are also available -- in scope in the definitions of the constants, so be careful not to -- introduce circular dependencies (not currently checked). [progFuns] :: Prog rep -> [FunDef rep] -- | Every entry point argument and return value has an annotation -- indicating how it maps to the original source program type. data EntryPointType -- | Is an unsigned integer or array of unsigned integers. TypeUnsigned :: Uniqueness -> EntryPointType -- | A black box type comprising this many core values. The string is a -- human-readable description with no other semantics. TypeOpaque :: Uniqueness -> String -> Int -> EntryPointType -- | Maps directly. TypeDirect :: Uniqueness -> EntryPointType -- | Information about the parameters and return value of an entry point. -- The first element is for parameters, the second for return value. type EntryPoint = (Name, [EntryPointType], [EntryPointType]) -- | Function Declarations data FunDef rep FunDef :: Maybe EntryPoint -> Attrs -> Name -> [RetType rep] -> [FParam rep] -> BodyT rep -> FunDef rep -- | Contains a value if this function is an entry point. [funDefEntryPoint] :: FunDef rep -> Maybe EntryPoint [funDefAttrs] :: FunDef rep -> Attrs [funDefName] :: FunDef rep -> Name [funDefRetType] :: FunDef rep -> [RetType rep] [funDefParams] :: FunDef rep -> [FParam rep] [funDefBody] :: FunDef rep -> BodyT rep -- | Anonymous function for use in a SOAC. data LambdaT rep -- | What kind of branch is this? This has no semantic meaning, but -- provides hints to simplifications. data IfSort -- | An ordinary branch. IfNormal :: IfSort -- | A branch where the "true" case is what we are actually interested in, -- and the "false" case is only present as a fallback for when the true -- case cannot be safely evaluated. The compiler is permitted to optimise -- away the branch if the true case contains only safe statements. IfFallback :: IfSort -- | Both of these branches are semantically equivalent, and it is fine to -- eliminate one if it turns out to have problems (e.g. contain things we -- cannot generate code for). IfEquiv :: IfSort -- | Data associated with a branch. data IfDec rt IfDec :: [rt] -> IfSort -> IfDec rt [ifReturns] :: IfDec rt -> [rt] [ifSort] :: IfDec rt -> IfSort -- | For-loop or while-loop? data LoopForm rep ForLoop :: VName -> IntType -> SubExp -> [(LParam rep, VName)] -> LoopForm rep WhileLoop :: VName -> LoopForm rep -- | The root Futhark expression type. The Op constructor contains a -- rep-specific operation. Do-loops, branches and function calls are -- special. Everything else is a simple BasicOp. data ExpT rep -- | A simple (non-recursive) operation. BasicOp :: BasicOp -> ExpT rep Apply :: Name -> [(SubExp, Diet)] -> [RetType rep] -> (Safety, SrcLoc, [SrcLoc]) -> ExpT rep If :: SubExp -> BodyT rep -> BodyT rep -> IfDec (BranchType rep) -> ExpT rep -- | loop {a} = {v} (for i < n|while b) do b. DoLoop :: [(FParam rep, SubExp)] -> LoopForm rep -> BodyT rep -> ExpT rep -- | Create accumulators backed by the given arrays (which are consumed) -- and pass them to the lambda, which must return the updated -- accumulators and possibly some extra values. The accumulators are -- turned back into arrays. The Shape is the write index space. -- The corresponding arrays must all have this shape outermost. This -- construct is not part of BasicOp because we need the -- rep parameter. WithAcc :: [(Shape, [VName], Maybe (Lambda rep, [SubExp]))] -> Lambda rep -> ExpT rep Op :: Op rep -> ExpT rep -- | A primitive operation that returns something of known size and does -- not itself contain any bindings. data BasicOp -- | A variable or constant. SubExp :: SubExp -> BasicOp -- | Semantically and operationally just identity, but is -- invisible/impenetrable to optimisations (hopefully). This partially a -- hack to avoid optimisation (so, to work around compiler limitations), -- but is also used to implement tracing and other operations that are -- semantically invisible, but have some sort of effect (brrr). Opaque :: OpaqueOp -> SubExp -> BasicOp -- | Array literals, e.g., [ [1+x, 3], [2, 1+4] ]. Second arg is -- the element type of the rows of the array. ArrayLit :: [SubExp] -> Type -> BasicOp -- | Unary operation. UnOp :: UnOp -> SubExp -> BasicOp -- | Binary operation. BinOp :: BinOp -> SubExp -> SubExp -> BasicOp -- | Comparison - result type is always boolean. CmpOp :: CmpOp -> SubExp -> SubExp -> BasicOp -- | Conversion "casting". ConvOp :: ConvOp -> SubExp -> BasicOp -- | Turn a boolean into a certificate, halting the program with the given -- error message if the boolean is false. Assert :: SubExp -> ErrorMsg SubExp -> (SrcLoc, [SrcLoc]) -> BasicOp -- | The certificates for bounds-checking are part of the Stm. Index :: VName -> Slice SubExp -> BasicOp -- | An in-place update of the given array at the given position. Consumes -- the array. If Safe, perform a run-time bounds check and ignore -- the write if out of bounds (like Scatter). Update :: Safety -> VName -> Slice SubExp -> SubExp -> BasicOp FlatIndex :: VName -> FlatSlice SubExp -> BasicOp FlatUpdate :: VName -> FlatSlice SubExp -> VName -> BasicOp -- | concat0([1],[2, 3, 4]) = [1, 2, 3, 4]@. Concat :: Int -> VName -> [VName] -> SubExp -> BasicOp -- | Copy the given array. The result will not alias anything. Copy :: VName -> BasicOp -- | Manifest an array with dimensions represented in the given order. The -- result will not alias anything. Manifest :: [Int] -> VName -> BasicOp -- | iota(n, x, s) = [x,x+s,..,x+(n-1)*s]. -- -- The IntType indicates the type of the array returned and the -- offset/stride arguments, but not the length argument. Iota :: SubExp -> SubExp -> SubExp -> IntType -> BasicOp -- |
-- replicate([3][2],1) = [[1,1], [1,1], [1,1]] --Replicate :: Shape -> SubExp -> BasicOp -- | Create array of given type and shape, with undefined elements. Scratch :: PrimType -> [SubExp] -> BasicOp -- | 1st arg is the new shape, 2nd arg is the input array *) Reshape :: ShapeChange SubExp -> VName -> BasicOp -- | Permute the dimensions of the input array. The list of integers is a -- list of dimensions (0-indexed), which must be a permutation of -- [0,n-1], where n is the number of dimensions in the -- input array. Rearrange :: [Int] -> VName -> BasicOp -- | Rotate the dimensions of the input array. The list of subexpressions -- specify how much each dimension is rotated. The length of this list -- must be equal to the rank of the array. Rotate :: [SubExp] -> VName -> BasicOp -- | Update an accumulator at the given index with the given value. -- Consumes the accumulator and produces a new one. UpdateAcc :: VName -> [SubExp] -> [SubExp] -> BasicOp -- | Apart from being Opaque, what else is going on here? data OpaqueOp -- | No special operation. OpaqueNil :: OpaqueOp -- | Print the argument, prefixed by this string. OpaqueTrace :: String -> OpaqueOp -- | A list of DimChanges, indicating the new dimensions of an -- array. type ShapeChange d = [DimChange d] -- | The new dimension in a Reshape-like operation. This allows us -- to disambiguate "real" reshapes, that change the actual shape of the -- array, from type coercions that are just present to make the types -- work out. The two constructors are considered equal for purposes of -- Eq. data DimChange d -- | The new dimension is guaranteed to be numerically equal to the old -- one. DimCoercion :: d -> DimChange d -- | The new dimension is not necessarily numerically equal to the old one. DimNew :: d -> DimChange d -- | A body consists of a number of bindings, terminating in a result -- (essentially a tuple literal). data BodyT rep -- | The result of a body is a sequence of subexpressions. type Result = [SubExpRes] -- | A pairing of a subexpression and some certificates. data SubExpRes SubExpRes :: Certs -> SubExp -> SubExpRes [resCerts] :: SubExpRes -> Certs [resSubExp] :: SubExpRes -> SubExp -- | A sequence of statements. type Stms rep = Seq (Stm rep) pattern Let :: () => Pat rep -> StmAux (ExpDec rep) -> Exp rep -> Stm rep -- | Expression. stmExp :: Stm rep -> Exp rep -- | Pat. stmPat :: Stm rep -> Pat rep -- | Auxiliary information statement. stmAux :: Stm rep -> StmAux (ExpDec rep) -- | Auxilliary Information associated with a statement. data StmAux dec StmAux :: !Certs -> Attrs -> dec -> StmAux dec [stmAuxCerts] :: StmAux dec -> !Certs [stmAuxAttrs] :: StmAux dec -> Attrs [stmAuxDec] :: StmAux dec -> dec -- | A pattern is conceptually just a list of names and their types. data PatT dec -- | Every statement is associated with a set of attributes, which can have -- various effects throughout the compiler. newtype Attrs Attrs :: Set Attr -> Attrs [unAttrs] :: Attrs -> Set Attr -- | A single attribute. data Attr AttrAtom :: Name -> Attr AttrComp :: Name -> [Attr] -> Attr -- | Construct Attrs from a single Attr. oneAttr :: Attr -> Attrs -- | Is the given attribute to be found in the attribute set? inAttrs :: Attr -> Attrs -> Bool -- | x withoutAttrs y gives x except for any -- attributes also in y. withoutAttrs :: Attrs -> Attrs -> Attrs -- | A single statement. oneStm :: Stm rep -> Stms rep -- | Convert a statement list to a statement sequence. stmsFromList :: [Stm rep] -> Stms rep -- | Convert a statement sequence to a statement list. stmsToList :: Stms rep -> [Stm rep] -- | The first statement in the sequence, if any. stmsHead :: Stms rep -> Maybe (Stm rep, Stms rep) -- | Construct a SubExpRes with no certificates. subExpRes :: SubExp -> SubExpRes -- | Construct a SubExpRes from a variable name. varRes :: VName -> SubExpRes -- | Construct a Result from subexpressions. subExpsRes :: [SubExp] -> Result -- | Construct a Result from variable names. varsRes :: [VName] -> Result -- | Anonymous function for use in a SOAC. data LambdaT rep Lambda :: [LParam rep] -> BodyT rep -> [Type] -> LambdaT rep -- | A body consists of a number of bindings, terminating in a result -- (essentially a tuple literal). data BodyT rep Body :: BodyDec rep -> Stms rep -> Result -> BodyT rep -- | A pattern is conceptually just a list of names and their types. newtype PatT dec Pat :: [PatElemT dec] -> PatT dec -- | An element of a pattern - consisting of a name and an addditional -- parametric decoration. This decoration is what is expected to contain -- the type of the resulting variable. data PatElemT dec PatElem :: VName -> dec -> PatElemT dec instance Futhark.IR.Rep.RepTypes Futhark.IR.SOACS.SOACS instance Futhark.IR.Prop.ASTRep Futhark.IR.SOACS.SOACS instance Futhark.TypeCheck.CheckableOp Futhark.IR.SOACS.SOACS instance Futhark.TypeCheck.Checkable Futhark.IR.SOACS.SOACS instance Futhark.Builder.Class.Buildable Futhark.IR.SOACS.SOACS instance Futhark.Builder.BuilderOps Futhark.IR.SOACS.SOACS instance Futhark.IR.Pretty.PrettyRep Futhark.IR.SOACS.SOACS -- | The code generator cannot handle the array combinators (map -- and friends), so this module was written to transform them into the -- equivalent do-loops. The transformation is currently rather naive, and -- - it's certainly worth considering when we can express such -- transformations in-place. module Futhark.Transform.FirstOrderTransform -- | First-order-transform a single function, with the given scope provided -- by top-level constants. transformFunDef :: (MonadFreshNames m, FirstOrderRep torep) => Scope torep -> FunDef SOACS -> m (FunDef torep) -- | First-order-transform these top-level constants. transformConsts :: (MonadFreshNames m, FirstOrderRep torep) => Stms SOACS -> m (Stms torep) -- | The constraints that must hold for a rep in order to be the target of -- first-order transformation. type FirstOrderRep rep = (Buildable rep, BuilderOps rep, LetDec SOACS ~ LetDec rep, LParamInfo SOACS ~ LParamInfo rep, CanBeAliased (Op rep)) -- | The constraints that a monad must uphold in order to be used for -- first-order transformation. type Transformer m = (MonadBuilder m, LocalScope (Rep m) m, Buildable (Rep m), BuilderOps (Rep m), LParamInfo SOACS ~ LParamInfo (Rep m), CanBeAliased (Op (Rep m))) -- | First transform any nested Body or Lambda elements, then -- apply transformSOAC if the expression is a SOAC. transformStmRecursively :: (Transformer m, LetDec (Rep m) ~ LetDec SOACS) => Stm -> m () -- | Recursively first-order-transform a lambda. transformLambda :: (MonadFreshNames m, Buildable rep, BuilderOps rep, LocalScope somerep m, SameScope somerep rep, LetDec rep ~ LetDec SOACS, CanBeAliased (Op rep)) => Lambda -> m (Lambda rep) -- | Transform a single SOAC into a do-loop. The body of the lambda -- is untouched, and may or may not contain further SOACs -- depending on the given rep. transformSOAC :: Transformer m => Pat (Rep m) -> SOAC (Rep m) -> m () -- | Transform any SOACs to for-loops. -- -- Example: -- --
-- let ys = map (x -> x + 2) xs ---- -- becomes something like: -- --
-- let out = scratch n i32 -- let ys = -- loop (ys' = out) for i < n do -- let x = xs[i] -- let y = x + 2 -- let ys'[i] = y -- in ys' --module Futhark.Pass.FirstOrderTransform -- | The first-order transformation pass. firstOrderTransform :: FirstOrderRep rep => Pass SOACS rep -- | Interchanging scans with inner maps. module Futhark.Pass.ExtractKernels.ISRWIM -- | Interchange Scan With Inner Map. Tries to turn a scan(map) -- into a @map(scan) iswim :: (MonadBuilder m, Rep m ~ SOACS) => Pat -> SubExp -> Lambda -> [(SubExp, VName)] -> Maybe (m ()) -- | Interchange Reduce With Inner Map. Tries to turn a -- reduce(map) into a @map(reduce) irwim :: (MonadBuilder m, Rep m ~ SOACS) => Pat -> SubExp -> Commutativity -> Lambda -> [(SubExp, VName)] -> Maybe (m ()) -- | Does this reduce operator contain an inner map, and if so, what does -- that map look like? rwimPossible :: Lambda -> Maybe (Pat, Certs, SubExp, Lambda) module Futhark.Internalise.Monad data InternaliseM a runInternaliseM :: MonadFreshNames m => Bool -> InternaliseM () -> m (Stms SOACS, [FunDef SOACS]) -- | Is used within a monadic computation to begin exception processing. throwError :: MonadError e m => e -> m a -- | A mapping from external variable names to the corresponding -- internalised subexpressions. type VarSubsts = Map VName [SubExp] data InternaliseEnv InternaliseEnv :: VarSubsts -> Bool -> Bool -> Attrs -> InternaliseEnv [envSubsts] :: InternaliseEnv -> VarSubsts [envDoBoundsChecks] :: InternaliseEnv -> Bool [envSafe] :: InternaliseEnv -> Bool [envAttrs] :: InternaliseEnv -> Attrs type FunInfo = ([VName], [DeclType], [FParam], [(SubExp, Type)] -> Maybe [DeclExtType]) substitutingVars :: VarSubsts -> InternaliseM a -> InternaliseM a lookupSubst :: VName -> InternaliseM (Maybe [SubExp]) -- | Add a function definition to the program being constructed. addFunDef :: FunDef SOACS -> InternaliseM () lookupFunction :: VName -> InternaliseM FunInfo lookupFunction' :: VName -> InternaliseM (Maybe FunInfo) lookupConst :: VName -> InternaliseM (Maybe [SubExp]) bindFunction :: VName -> FunDef SOACS -> FunInfo -> InternaliseM () bindConstant :: VName -> FunDef SOACS -> InternaliseM () localConstsScope :: InternaliseM a -> InternaliseM a -- | Construct an Assert statement, but taking attributes into -- account. Always use this function, and never construct Assert -- directly in the internaliser! assert :: String -> SubExp -> ErrorMsg SubExp -> SrcLoc -> InternaliseM Certs instance Futhark.IR.Prop.Scope.LocalScope Futhark.IR.SOACS.SOACS Futhark.Internalise.Monad.InternaliseM instance Futhark.IR.Prop.Scope.HasScope Futhark.IR.SOACS.SOACS Futhark.Internalise.Monad.InternaliseM instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Internalise.Monad.InternaliseM instance Control.Monad.State.Class.MonadState Futhark.Internalise.Monad.InternaliseState Futhark.Internalise.Monad.InternaliseM instance Control.Monad.Reader.Class.MonadReader Futhark.Internalise.Monad.InternaliseEnv Futhark.Internalise.Monad.InternaliseM instance GHC.Base.Monad Futhark.Internalise.Monad.InternaliseM instance GHC.Base.Applicative Futhark.Internalise.Monad.InternaliseM instance GHC.Base.Functor Futhark.Internalise.Monad.InternaliseM instance Futhark.Builder.Class.MonadBuilder Futhark.Internalise.Monad.InternaliseM instance Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.State.Lazy.State Futhark.Internalise.Monad.InternaliseState) module Futhark.Internalise.AccurateSizes argShapes :: [VName] -> [FParam] -> [Type] -> InternaliseM [SubExp] ensureResultShape :: ErrorMsg SubExp -> SrcLoc -> [Type] -> Result -> InternaliseM Result ensureResultExtShape :: ErrorMsg SubExp -> SrcLoc -> [ExtType] -> Result -> InternaliseM Result ensureExtShape :: ErrorMsg SubExp -> SrcLoc -> ExtType -> String -> SubExp -> InternaliseM SubExp ensureShape :: ErrorMsg SubExp -> SrcLoc -> Type -> String -> SubExp -> InternaliseM SubExp -- | Reshape the arguments to a function so that they fit the expected -- shape declarations. Not used to change rank of arguments. Assumes -- everything is otherwise type-correct. ensureArgShapes :: Typed (TypeBase Shape u) => ErrorMsg SubExp -> SrcLoc -> [VName] -> [TypeBase Shape u] -> [SubExp] -> InternaliseM [SubExp] module Futhark.IR.SOACS.Simplify simplifySOACS :: Prog SOACS -> PassM (Prog SOACS) simplifyLambda :: (HasScope SOACS m, MonadFreshNames m) => Lambda -> m Lambda simplifyFun :: MonadFreshNames m => SymbolTable (Wise SOACS) -> FunDef SOACS -> m (FunDef SOACS) simplifyStms :: (HasScope SOACS m, MonadFreshNames m) => Stms SOACS -> m (SymbolTable (Wise SOACS), Stms SOACS) simplifyConsts :: MonadFreshNames m => Stms SOACS -> m (SymbolTable (Wise SOACS), Stms SOACS) simpleSOACS :: SimpleOps SOACS simplifySOAC :: SimplifiableRep rep => SimplifyOp rep (SOAC rep) soacRules :: RuleBook (Wise SOACS) -- | Does this rep contain SOACs in its Ops? A rep must be an -- instance of this class for the simplification rules to work. class HasSOAC rep asSOAC :: HasSOAC rep => Op rep -> Maybe (SOAC rep) soacOp :: HasSOAC rep => SOAC rep -> Op rep simplifyKnownIterationSOAC :: (Buildable rep, SimplifiableRep rep, HasSOAC (Wise rep)) => TopDownRuleOp (Wise rep) -- | Remove all arguments to the map that are simply replicates. These can -- be turned into free variables instead. removeReplicateMapping :: (Buildable rep, SimplifiableRep rep, HasSOAC (Wise rep)) => TopDownRuleOp (Wise rep) liftIdentityMapping :: forall rep. (Buildable rep, SimplifiableRep rep, HasSOAC (Wise rep)) => TopDownRuleOp (Wise rep) -- | The rep for the basic representation. data SOACS instance GHC.Show.Show Futhark.IR.SOACS.Simplify.ArrayOp instance GHC.Classes.Ord Futhark.IR.SOACS.Simplify.ArrayOp instance GHC.Classes.Eq Futhark.IR.SOACS.Simplify.ArrayOp instance Futhark.IR.SOACS.Simplify.HasSOAC (Futhark.Optimise.Simplify.Rep.Wise Futhark.IR.SOACS.SOACS) instance Futhark.Builder.BuilderOps (Futhark.Optimise.Simplify.Rep.Wise Futhark.IR.SOACS.SOACS) -- | This module exports functionality for generating a call graph of an -- Futhark program. module Futhark.Analysis.CallGraph -- | The call graph is a mapping from a function name, i.e., the caller, to -- a record of the names of functions called *directly* (not -- transitively!) by the function. -- -- We keep track separately of the functions called by constants. data CallGraph -- | buildCallGraph prog build the program's call graph. buildCallGraph :: Prog SOACS -> CallGraph -- | Is the given function known to the call graph? isFunInCallGraph :: Name -> CallGraph -> Bool -- | Does the first function call the second? calls :: Name -> Name -> CallGraph -> Bool -- | Is the function called in any of the constants? calledByConsts :: Name -> CallGraph -> Bool -- | All functions called by this function. allCalledBy :: Name -> CallGraph -> Set Name -- | Produce a mapping of the number of occurences in the call graph of -- each function. Only counts functions that are called at least once. numOccurences :: CallGraph -> Map Name Int -- | The set of all functions that are called noinline somewhere, or have a -- noinline attribute on their definition. findNoninlined :: Prog SOACS -> Set Name instance GHC.Show.Show Futhark.Analysis.CallGraph.FunCalls instance GHC.Classes.Ord Futhark.Analysis.CallGraph.FunCalls instance GHC.Classes.Eq Futhark.Analysis.CallGraph.FunCalls instance GHC.Show.Show Futhark.Analysis.CallGraph.CallGraph instance GHC.Classes.Ord Futhark.Analysis.CallGraph.CallGraph instance GHC.Classes.Eq Futhark.Analysis.CallGraph.CallGraph instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Analysis.CallGraph.CallGraph instance GHC.Base.Monoid Futhark.Analysis.CallGraph.FunCalls instance GHC.Base.Semigroup Futhark.Analysis.CallGraph.FunCalls instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Analysis.CallGraph.FunCalls -- | Building blocks for defining representations where every array is -- given information about which memory block is it based in, and how -- array elements map to memory block offsets. -- -- There are two primary concepts you will need to understand: -- --
-- f(i,j) = i * m + j ---- -- When we want to know the location of element a[2,3], we -- simply call the index function as f(2,3) and obtain -- 2*m+3. We could also have chosen another index function, one -- that represents the array in column-major (or "transposed") format: -- --
-- f(i,j) = j * n + i ---- -- Index functions are not Futhark-level functions, but a special -- construct that the final code generator will eventually use to -- generate concrete access code. By modifying the index functions we can -- change how an array is represented in memory, which can permit memory -- access pattern optimisations. -- -- Every time we bind an array, whether in a let-binding, -- loop merge parameter, or lambda parameter, we have -- an annotation specifying a memory block and an index function. In some -- cases, such as let-bindings for many expressions, we are free -- to specify an arbitrary index function and memory block - for example, -- we get to decide where Copy stores its result - but in other -- cases the type rules of the expression chooses for us. For example, -- Index always produces an array in the same memory block as its -- input, and with the same index function, except with some indices -- fixed. module Futhark.IR.Mem type LetDecMem = MemInfo SubExp NoUniqueness MemBind type FParamMem = MemInfo SubExp Uniqueness MemBind type LParamMem = MemInfo SubExp NoUniqueness MemBind type RetTypeMem = FunReturns type BranchTypeMem = BodyReturns data MemOp inner -- | Allocate a memory block. Alloc :: SubExp -> Space -> MemOp inner Inner :: inner -> MemOp inner -- | A summary of the memory information for every let-bound identifier, -- function parameter, and return value. Parameterisered over uniqueness, -- dimension, and auxiliary array information. data MemInfo d u ret -- | A primitive value. MemPrim :: PrimType -> MemInfo d u ret -- | A memory block. MemMem :: Space -> MemInfo d u ret -- | The array is stored in the named memory block, and with the given -- index function. The index function maps indices in the array to -- element offset, not byte offsets! To translate to byte -- offsets, multiply the offset with the size of the array element type. MemArray :: PrimType -> ShapeBase d -> u -> ret -> MemInfo d u ret -- | An accumulator, which is not stored anywhere. MemAcc :: VName -> Shape -> [Type] -> u -> MemInfo d u ret type MemBound u = MemInfo SubExp u MemBind -- | Memory information for an array bound somewhere in the program. data MemBind -- | Located in this memory block with this index function. ArrayIn :: VName -> IxFun -> MemBind -- | A description of the memory properties of an array being returned by -- an operation. data MemReturn -- | The array is located in a memory block that is already in scope. ReturnsInBlock :: VName -> ExtIxFun -> MemReturn -- | The operation returns a new (existential) memory block. ReturnsNewBlock :: Space -> Int -> ExtIxFun -> MemReturn -- | The index function representation used for memory annotations. type IxFun = IxFun (TPrimExp Int64 VName) -- | An index function that may contain existential variables. type ExtIxFun = IxFun (TPrimExp Int64 (Ext VName)) isStaticIxFun :: ExtIxFun -> Maybe IxFun -- | The memory return of an expression. An array is annotated with -- Maybe MemReturn, which can be interpreted as the expression -- either dictating exactly where the array is located when it is -- returned (if Just), or able to put it whereever the binding -- prefers (if Nothing). -- -- This is necessary to capture the difference between an expression that -- is just an array-typed variable, in which the array being "returned" -- is located where it already is, and a copy expression, whose -- entire purpose is to store an existing array in some arbitrary -- location. This is a consequence of the design decision never to have -- implicit memory copies. type ExpReturns = MemInfo ExtSize NoUniqueness (Maybe MemReturn) -- | The return of a body, which must always indicate where returned arrays -- are located. type BodyReturns = MemInfo ExtSize NoUniqueness MemReturn -- | The memory return of a function, which must always indicate where -- returned arrays are located. type FunReturns = MemInfo ExtSize Uniqueness MemReturn noUniquenessReturns :: MemInfo d u r -> MemInfo d NoUniqueness r bodyReturnsToExpReturns :: BodyReturns -> ExpReturns type Mem rep inner = (FParamInfo rep ~ FParamMem, LParamInfo rep ~ LParamMem, HasLetDecMem (LetDec rep), RetType rep ~ RetTypeMem, BranchType rep ~ BranchTypeMem, ASTRep rep, OpReturns inner, Op rep ~ MemOp inner) -- | The class of pattern element decorators that contain memory -- information. class HasLetDecMem t letDecMem :: HasLetDecMem t => t -> LetDecMem class TypedOp op => OpReturns op opReturns :: (OpReturns op, Mem rep inner, Monad m, HasScope rep m) => op -> m [ExpReturns] varReturns :: (HasScope rep m, Monad m, Mem rep inner) => VName -> m ExpReturns -- | The return information of an expression. This can be seen as the -- "return type with memory annotations" of the expression. expReturns :: (Monad m, LocalScope rep m, Mem rep inner) => Exp rep -> m [ExpReturns] extReturns :: [ExtType] -> [ExpReturns] lookupMemInfo :: (HasScope rep m, Mem rep inner) => VName -> m (MemInfo SubExp NoUniqueness MemBind) subExpMemInfo :: (HasScope rep m, Monad m, Mem rep inner) => SubExp -> m (MemInfo SubExp NoUniqueness MemBind) lookupArraySummary :: (Mem rep inner, HasScope rep m, Monad m) => VName -> m (VName, IxFun (TPrimExp Int64 VName)) existentialiseIxFun :: [VName] -> IxFun -> ExtIxFun matchBranchReturnType :: (Mem rep inner, Checkable rep) => [BodyReturns] -> Body (Aliases rep) -> TypeM rep () matchPatToExp :: (Mem rep inner, LetDec rep ~ LetDecMem, Checkable rep) => Pat (Aliases rep) -> Exp (Aliases rep) -> TypeM rep () matchFunctionReturnType :: (Mem rep inner, Checkable rep) => [FunReturns] -> Result -> TypeM rep () matchLoopResultMem :: (Mem rep inner, Checkable rep) => [FParam (Aliases rep)] -> Result -> TypeM rep () bodyReturnsFromPat :: PatT (MemBound NoUniqueness) -> [(VName, BodyReturns)] checkMemInfo :: Checkable rep => VName -> MemInfo SubExp u MemBind -> TypeM rep () instance GHC.Show.Show inner => GHC.Show.Show (Futhark.IR.Mem.MemOp inner) instance GHC.Classes.Ord inner => GHC.Classes.Ord (Futhark.IR.Mem.MemOp inner) instance GHC.Classes.Eq inner => GHC.Classes.Eq (Futhark.IR.Mem.MemOp inner) instance (GHC.Classes.Ord d, GHC.Classes.Ord u, GHC.Classes.Ord ret) => GHC.Classes.Ord (Futhark.IR.Mem.MemInfo d u ret) instance (GHC.Show.Show d, GHC.Show.Show u, GHC.Show.Show ret) => GHC.Show.Show (Futhark.IR.Mem.MemInfo d u ret) instance (GHC.Classes.Eq d, GHC.Classes.Eq u, GHC.Classes.Eq ret) => GHC.Classes.Eq (Futhark.IR.Mem.MemInfo d u ret) instance GHC.Show.Show Futhark.IR.Mem.MemBind instance GHC.Show.Show Futhark.IR.Mem.MemReturn instance Futhark.IR.Mem.OpReturns inner => Futhark.IR.Mem.OpReturns (Futhark.IR.Mem.MemOp inner) instance Futhark.IR.Mem.OpReturns () instance Futhark.IR.RetType.IsRetType Futhark.IR.Mem.FunReturns instance Futhark.Optimise.Simplify.Engine.Simplifiable [Futhark.IR.Mem.FunReturns] instance Futhark.IR.RetType.IsBodyType Futhark.IR.Mem.BodyReturns instance GHC.Classes.Eq Futhark.IR.Mem.MemReturn instance GHC.Classes.Ord Futhark.IR.Mem.MemReturn instance Futhark.Transform.Rename.Rename Futhark.IR.Mem.MemReturn instance Futhark.Transform.Substitute.Substitute Futhark.IR.Mem.MemReturn instance Futhark.IR.Prop.Types.FixExt Futhark.IR.Mem.MemReturn instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Mem.MemReturn instance Futhark.IR.Prop.Names.FreeIn Futhark.IR.Mem.MemReturn instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.IR.Mem.MemReturn instance Futhark.IR.Mem.HasLetDecMem Futhark.IR.Mem.LetDecMem instance Futhark.IR.Mem.HasLetDecMem b => Futhark.IR.Mem.HasLetDecMem (a, b) instance GHC.Classes.Eq Futhark.IR.Mem.MemBind instance GHC.Classes.Ord Futhark.IR.Mem.MemBind instance Futhark.Transform.Rename.Rename Futhark.IR.Mem.MemBind instance Futhark.Transform.Substitute.Substitute Futhark.IR.Mem.MemBind instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Mem.MemBind instance Futhark.IR.Prop.Names.FreeIn Futhark.IR.Mem.MemBind instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.IR.Mem.MemBind instance Futhark.IR.Prop.Types.FixExt ret => Futhark.IR.Prop.Types.DeclExtTyped (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.ExtSize Language.Futhark.Core.Uniqueness ret) instance Futhark.IR.Prop.Types.FixExt ret => Futhark.IR.Prop.Types.ExtTyped (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.ExtSize Futhark.IR.Syntax.Core.NoUniqueness ret) instance Futhark.IR.Prop.Types.FixExt ret => Futhark.IR.Prop.Types.FixExt (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.ExtSize u ret) instance Futhark.IR.Prop.Types.Typed (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.SubExp Language.Futhark.Core.Uniqueness ret) instance Futhark.IR.Prop.Types.Typed (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.SubExp Futhark.IR.Syntax.Core.NoUniqueness ret) instance Futhark.IR.Prop.Types.DeclTyped (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.SubExp Language.Futhark.Core.Uniqueness ret) instance (Futhark.IR.Prop.Names.FreeIn d, Futhark.IR.Prop.Names.FreeIn ret) => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.Mem.MemInfo d u ret) instance (Futhark.Transform.Substitute.Substitute d, Futhark.Transform.Substitute.Substitute ret) => Futhark.Transform.Substitute.Substitute (Futhark.IR.Mem.MemInfo d u ret) instance (Futhark.Transform.Substitute.Substitute d, Futhark.Transform.Substitute.Substitute ret) => Futhark.Transform.Rename.Rename (Futhark.IR.Mem.MemInfo d u ret) instance (Futhark.Optimise.Simplify.Engine.Simplifiable d, Futhark.Optimise.Simplify.Engine.Simplifiable ret) => Futhark.Optimise.Simplify.Engine.Simplifiable (Futhark.IR.Mem.MemInfo d u ret) instance (Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.ShapeBase d), Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.TypeBase (Futhark.IR.Syntax.Core.ShapeBase d) u), Text.PrettyPrint.Mainland.Class.Pretty d, Text.PrettyPrint.Mainland.Class.Pretty u, Text.PrettyPrint.Mainland.Class.Pretty ret) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Mem.MemInfo d u ret) instance Futhark.IR.Prop.Names.FreeIn inner => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.Mem.MemOp inner) instance Futhark.IR.Prop.TypeOf.TypedOp inner => Futhark.IR.Prop.TypeOf.TypedOp (Futhark.IR.Mem.MemOp inner) instance Futhark.IR.Prop.Aliases.AliasedOp inner => Futhark.IR.Prop.Aliases.AliasedOp (Futhark.IR.Mem.MemOp inner) instance Futhark.IR.Prop.Aliases.CanBeAliased inner => Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Mem.MemOp inner) instance Futhark.Transform.Rename.Rename inner => Futhark.Transform.Rename.Rename (Futhark.IR.Mem.MemOp inner) instance Futhark.Transform.Substitute.Substitute inner => Futhark.Transform.Substitute.Substitute (Futhark.IR.Mem.MemOp inner) instance Text.PrettyPrint.Mainland.Class.Pretty inner => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Mem.MemOp inner) instance Futhark.Analysis.Metrics.OpMetrics inner => Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.Mem.MemOp inner) instance Futhark.IR.Prop.IsOp inner => Futhark.IR.Prop.IsOp (Futhark.IR.Mem.MemOp inner) instance Futhark.Optimise.Simplify.Rep.CanBeWise inner => Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Mem.MemOp inner) instance Futhark.Analysis.SymbolTable.IndexOp inner => Futhark.Analysis.SymbolTable.IndexOp (Futhark.IR.Mem.MemOp inner) -- | A generic transformation for adding memory allocations to a Futhark -- program. Specialised by specific representations in submodules. module Futhark.Pass.ExplicitAllocations explicitAllocationsGeneric :: Allocable fromrep torep inner => (Op fromrep -> AllocM fromrep torep (Op torep)) -> (Exp torep -> AllocM fromrep torep [ExpHint]) -> Pass fromrep torep explicitAllocationsInStmsGeneric :: (MonadFreshNames m, HasScope torep m, Allocable fromrep torep inner) => (Op fromrep -> AllocM fromrep torep (Op torep)) -> (Exp torep -> AllocM fromrep torep [ExpHint]) -> Stms fromrep -> m (Stms torep) data ExpHint NoHint :: ExpHint Hint :: IxFun -> Space -> ExpHint defaultExpHints :: (Monad m, ASTRep rep) => Exp rep -> m [ExpHint] type Allocable fromrep torep inner = (PrettyRep fromrep, PrettyRep torep, Mem torep inner, LetDec torep ~ LetDecMem, FParamInfo fromrep ~ DeclType, LParamInfo fromrep ~ Type, BranchType fromrep ~ ExtType, RetType fromrep ~ DeclExtType, BodyDec fromrep ~ (), BodyDec torep ~ (), ExpDec torep ~ (), SizeSubst inner, BuilderOps torep) -- | Monad for adding allocations to an entire program. data AllocM fromrep torep a data AllocEnv fromrep torep AllocEnv :: ChunkMap -> Bool -> Space -> Set VName -> (Op fromrep -> AllocM fromrep torep (Op torep)) -> (Exp torep -> AllocM fromrep torep [ExpHint]) -> AllocEnv fromrep torep [chunkMap] :: AllocEnv fromrep torep -> ChunkMap -- | Aggressively try to reuse memory in do-loops - should be True inside -- kernels, False outside. [aggressiveReuse] :: AllocEnv fromrep torep -> Bool -- | When allocating memory, put it in this memory space. This is primarily -- used to ensure that group-wide statements store their results in local -- memory. [allocSpace] :: AllocEnv fromrep torep -> Space -- | The set of names that are known to be constants at kernel compile -- time. [envConsts] :: AllocEnv fromrep torep -> Set VName [allocInOp] :: AllocEnv fromrep torep -> Op fromrep -> AllocM fromrep torep (Op torep) [envExpHints] :: AllocEnv fromrep torep -> Exp torep -> AllocM fromrep torep [ExpHint] class SizeSubst op opSizeSubst :: SizeSubst op => PatT dec -> op -> ChunkMap opIsConst :: SizeSubst op => op -> Bool allocInStms :: Allocable fromrep torep inner => Stms fromrep -> AllocM fromrep torep a -> AllocM fromrep torep a -- | Allocate memory for a value of the given type. allocForArray :: Allocable fromrep torep inner => Type -> Space -> AllocM fromrep torep VName simplifiable :: (SimplifiableRep rep, ExpDec rep ~ (), BodyDec rep ~ (), Mem rep inner) => (OpWithWisdom inner -> UsageTable) -> (inner -> SimpleM rep (OpWithWisdom inner, Stms (Wise rep))) -> SimpleOps rep arraySizeInBytesExp :: Type -> PrimExp VName mkLetNamesB' :: (LetDec (Rep m) ~ LetDecMem, Mem (Rep m) inner, MonadBuilder m, ExpDec (Rep m) ~ ()) => ExpDec (Rep m) -> [VName] -> Exp (Rep m) -> m (Stm (Rep m)) mkLetNamesB'' :: (BuilderOps rep, Mem rep inner, LetDec rep ~ LetDecMem, OpReturns (OpWithWisdom inner), ExpDec rep ~ (), Rep m ~ Wise rep, HasScope (Wise rep) m, MonadBuilder m, CanBeWise inner) => [VName] -> Exp (Wise rep) -> m (Stm (Wise rep)) -- | The subexpression giving the number of elements we should allocate -- space for. See ChunkMap comment. dimAllocationSize :: ChunkMap -> SubExp -> SubExp -- | A mapping from chunk names to their maximum size. XXX FIXME HACK: This -- is part of a hack to add loop-invariant allocations to reduce kernels, -- because memory expansion does not use range analysis yet (it should). type ChunkMap = Map VName SubExp instance Control.Monad.Reader.Class.MonadReader (Futhark.Pass.ExplicitAllocations.AllocEnv fromrep torep) (Futhark.Pass.ExplicitAllocations.AllocM fromrep torep) instance Futhark.IR.Prop.ASTRep torep => Futhark.IR.Prop.Scope.LocalScope torep (Futhark.Pass.ExplicitAllocations.AllocM fromrep torep) instance Futhark.IR.Prop.ASTRep torep => Futhark.IR.Prop.Scope.HasScope torep (Futhark.Pass.ExplicitAllocations.AllocM fromrep torep) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.Pass.ExplicitAllocations.AllocM fromrep torep) instance GHC.Base.Monad (Futhark.Pass.ExplicitAllocations.AllocM fromrep torep) instance GHC.Base.Functor (Futhark.Pass.ExplicitAllocations.AllocM fromrep torep) instance GHC.Base.Applicative (Futhark.Pass.ExplicitAllocations.AllocM fromrep torep) instance Futhark.Pass.ExplicitAllocations.Allocable fromrep torep inner => Futhark.Builder.Class.MonadBuilder (Futhark.Pass.ExplicitAllocations.AllocM fromrep torep) instance Futhark.Pass.ExplicitAllocations.SizeSubst () instance Futhark.Pass.ExplicitAllocations.SizeSubst op => Futhark.Pass.ExplicitAllocations.SizeSubst (Futhark.IR.Mem.MemOp op) -- | Segmented operations. These correspond to perfect map nests -- on top of something, except that the maps are -- conceptually only over iotas (so there will be explicit -- indexing inside them). module Futhark.IR.SegOp -- | A SegOp is semantically a perfectly nested stack of maps, on -- top of some bottommost computation (scalar computation, reduction, -- scan, or histogram). The SegSpace encodes the original map -- structure. -- -- All SegOps are parameterised by the representation of their -- body, as well as a *level*. The *level* is a representation-specific -- bit of information. For example, in GPU backends, it is used to -- indicate whether the SegOp is expected to run at the -- thread-level or the group-level. data SegOp lvl rep SegMap :: lvl -> SegSpace -> [Type] -> KernelBody rep -> SegOp lvl rep -- | The KernelSpace must always have at least two dimensions, implying -- that the result of a SegRed is always an array. SegRed :: lvl -> SegSpace -> [SegBinOp rep] -> [Type] -> KernelBody rep -> SegOp lvl rep SegScan :: lvl -> SegSpace -> [SegBinOp rep] -> [Type] -> KernelBody rep -> SegOp lvl rep SegHist :: lvl -> SegSpace -> [HistOp rep] -> [Type] -> KernelBody rep -> SegOp lvl rep -- | Do we need group-virtualisation when generating code for the segmented -- operation? In most cases, we do, but for some simple kernels, we -- compute the full number of groups in advance, and then virtualisation -- is an unnecessary (but generally very small) overhead. This only -- really matters for fairly trivial but very wide map kernels -- where each thread performs constant-time work on scalars. data SegVirt SegVirt :: SegVirt SegNoVirt :: SegVirt -- | Not only do we not need virtualisation, but we _guarantee_ that all -- physical threads participate in the work. This can save some checks in -- code generation. SegNoVirtFull :: SegVirt -- | The level of a SegOp. segLevel :: SegOp lvl rep -> lvl -- | The body of a SegOp. segBody :: SegOp lvl rep -> KernelBody rep -- | The space of a SegOp. segSpace :: SegOp lvl rep -> SegSpace -- | Type check a SegOp, given a checker for its level. typeCheckSegOp :: Checkable rep => (lvl -> TypeM rep ()) -> SegOp lvl (Aliases rep) -> TypeM rep () -- | Index space of a SegOp. data SegSpace SegSpace :: VName -> [(VName, SubExp)] -> SegSpace -- | Flat physical index corresponding to the dimensions (at code -- generation used for a thread ID or similar). [segFlat] :: SegSpace -> VName [unSegSpace] :: SegSpace -> [(VName, SubExp)] -- | A Scope containing all the identifiers brought into scope by -- this SegSpace. scopeOfSegSpace :: SegSpace -> Scope rep -- | The sizes spanned by the indexes of the SegSpace. segSpaceDims :: SegSpace -> [SubExp] -- | An operator for SegHist. data HistOp rep HistOp :: SubExp -> SubExp -> [VName] -> [SubExp] -> Shape -> Lambda rep -> HistOp rep [histWidth] :: HistOp rep -> SubExp [histRaceFactor] :: HistOp rep -> SubExp [histDest] :: HistOp rep -> [VName] [histNeutral] :: HistOp rep -> [SubExp] -- | In case this operator is semantically a vectorised operator -- (corresponding to a perfect map nest in the SOACS representation), -- these are the logical "dimensions". This is used to generate more -- efficient code. [histShape] :: HistOp rep -> Shape [histOp] :: HistOp rep -> Lambda rep -- | The type of a histogram produced by a HistOp. This can be -- different from the type of the histDests in case we are dealing -- with a segmented histogram. histType :: HistOp rep -> [Type] -- | An operator for SegScan and SegRed. data SegBinOp rep SegBinOp :: Commutativity -> Lambda rep -> [SubExp] -> Shape -> SegBinOp rep [segBinOpComm] :: SegBinOp rep -> Commutativity [segBinOpLambda] :: SegBinOp rep -> Lambda rep [segBinOpNeutral] :: SegBinOp rep -> [SubExp] -- | In case this operator is semantically a vectorised operator -- (corresponding to a perfect map nest in the SOACS representation), -- these are the logical "dimensions". This is used to generate more -- efficient code. [segBinOpShape] :: SegBinOp rep -> Shape -- | How many reduction results are produced by these SegBinOps? segBinOpResults :: [SegBinOp rep] -> Int -- | Split some list into chunks equal to the number of values returned by -- each SegBinOp segBinOpChunks :: [SegBinOp rep] -> [a] -> [[a]] -- | The body of a SegOp. data KernelBody rep KernelBody :: BodyDec rep -> Stms rep -> [KernelResult] -> KernelBody rep [kernelBodyDec] :: KernelBody rep -> BodyDec rep [kernelBodyStms] :: KernelBody rep -> Stms rep [kernelBodyResult] :: KernelBody rep -> [KernelResult] -- | Perform alias analysis on a KernelBody. aliasAnalyseKernelBody :: (ASTRep rep, CanBeAliased (Op rep)) => AliasTable -> KernelBody rep -> KernelBody (Aliases rep) -- | The variables consumed in the kernel body. consumedInKernelBody :: Aliased rep => KernelBody rep -> Names -- | Metadata about whether there is a subtle point to this -- KernelResult. This is used to protect things like tiling, which -- might otherwise be removed by the simplifier because they're -- semantically redundant. This has no semantic effect and can be ignored -- at code generation. data ResultManifest -- | Don't simplify this one! ResultNoSimplify :: ResultManifest -- | Go nuts. ResultMaySimplify :: ResultManifest -- | The results produced are only used within the same physical thread -- later on, and can thus be kept in registers. ResultPrivate :: ResultManifest -- | A KernelBody does not return an ordinary Result. -- Instead, it returns a list of these. data KernelResult -- | Each "worker" in the kernel returns this. Whether this is a -- result-per-thread or a result-per-group depends on where the -- SegOp occurs. Returns :: ResultManifest -> Certs -> SubExp -> KernelResult WriteReturns :: Certs -> Shape -> VName -> [(Slice SubExp, SubExp)] -> KernelResult ConcatReturns :: Certs -> SplitOrdering -> SubExp -> SubExp -> VName -> KernelResult TileReturns :: Certs -> [(SubExp, SubExp)] -> VName -> KernelResult RegTileReturns :: Certs -> [(SubExp, SubExp, SubExp)] -> VName -> KernelResult -- | Get the certs for this KernelResult. kernelResultCerts :: KernelResult -> Certs -- | Get the root SubExp corresponding values for a -- KernelResult. kernelResultSubExp :: KernelResult -> SubExp -- | How an array is split into chunks. data SplitOrdering SplitContiguous :: SplitOrdering SplitStrided :: SubExp -> SplitOrdering -- | Like Mapper, but just for SegOps. data SegOpMapper lvl frep trep m SegOpMapper :: (SubExp -> m SubExp) -> (Lambda frep -> m (Lambda trep)) -> (KernelBody frep -> m (KernelBody trep)) -> (VName -> m VName) -> (lvl -> m lvl) -> SegOpMapper lvl frep trep m [mapOnSegOpSubExp] :: SegOpMapper lvl frep trep m -> SubExp -> m SubExp [mapOnSegOpLambda] :: SegOpMapper lvl frep trep m -> Lambda frep -> m (Lambda trep) [mapOnSegOpBody] :: SegOpMapper lvl frep trep m -> KernelBody frep -> m (KernelBody trep) [mapOnSegOpVName] :: SegOpMapper lvl frep trep m -> VName -> m VName [mapOnSegOpLevel] :: SegOpMapper lvl frep trep m -> lvl -> m lvl -- | A mapper that simply returns the SegOp verbatim. identitySegOpMapper :: Monad m => SegOpMapper lvl rep rep m -- | Apply a SegOpMapper to the given SegOp. mapSegOpM :: (Applicative m, Monad m) => SegOpMapper lvl frep trep m -> SegOp lvl frep -> m (SegOp lvl trep) -- | Simplify the given SegOp. simplifySegOp :: (SimplifiableRep rep, BodyDec rep ~ (), Simplifiable lvl) => SegOp lvl rep -> SimpleM rep (SegOp lvl (Wise rep), Stms (Wise rep)) -- | Does this rep contain SegOps in its Ops? A rep must be -- an instance of this class for the simplification rules to work. class HasSegOp rep where { type family SegOpLevel rep; } asSegOp :: HasSegOp rep => Op rep -> Maybe (SegOp (SegOpLevel rep) rep) segOp :: HasSegOp rep => SegOp (SegOpLevel rep) rep -> Op rep -- | Simplification rules for simplifying SegOps. segOpRules :: (HasSegOp rep, BuilderOps rep, Buildable rep) => RuleBook rep -- | Like segOpType, but for memory representations. segOpReturns :: (Mem rep inner, Monad m, HasScope rep m) => SegOp lvl somerep -> m [ExpReturns] instance GHC.Show.Show Futhark.IR.SegOp.SplitOrdering instance GHC.Classes.Ord Futhark.IR.SegOp.SplitOrdering instance GHC.Classes.Eq Futhark.IR.SegOp.SplitOrdering instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SegOp.HistOp rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SegOp.HistOp rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SegOp.HistOp rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SegOp.SegBinOp rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SegOp.SegBinOp rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SegOp.SegBinOp rep) instance GHC.Classes.Ord Futhark.IR.SegOp.ResultManifest instance GHC.Show.Show Futhark.IR.SegOp.ResultManifest instance GHC.Classes.Eq Futhark.IR.SegOp.ResultManifest instance GHC.Classes.Ord Futhark.IR.SegOp.KernelResult instance GHC.Show.Show Futhark.IR.SegOp.KernelResult instance GHC.Classes.Eq Futhark.IR.SegOp.KernelResult instance GHC.Show.Show Futhark.IR.SegOp.SegVirt instance GHC.Classes.Ord Futhark.IR.SegOp.SegVirt instance GHC.Classes.Eq Futhark.IR.SegOp.SegVirt instance GHC.Show.Show Futhark.IR.SegOp.SegSpace instance GHC.Classes.Ord Futhark.IR.SegOp.SegSpace instance GHC.Classes.Eq Futhark.IR.SegOp.SegSpace instance (Futhark.IR.Rep.RepTypes rep, GHC.Show.Show lvl) => GHC.Show.Show (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.IR.Rep.RepTypes rep, GHC.Classes.Ord lvl) => GHC.Classes.Ord (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.IR.Rep.RepTypes rep, GHC.Classes.Eq lvl) => GHC.Classes.Eq (Futhark.IR.SegOp.SegOp lvl rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Ord (Futhark.IR.SegOp.KernelBody rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.IR.SegOp.KernelBody rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.IR.SegOp.KernelBody rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.Transform.Substitute.Substitute lvl) => Futhark.Transform.Substitute.Substitute (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.ASTConstraints lvl) => Futhark.Transform.Rename.Rename (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Names.FreeIn (Futhark.IR.Rep.LParamInfo rep), Futhark.IR.Prop.Names.FreeIn lvl) => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.ASTRep (Futhark.IR.Aliases.Aliases rep), Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep), Futhark.IR.Prop.ASTConstraints lvl) => Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Rep.Op rep), Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.ASTConstraints lvl) => Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.SegOp.SegOp lvl rep) instance Futhark.IR.Prop.TypeOf.TypedOp (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.Aliased rep, Futhark.IR.Prop.ASTConstraints lvl) => Futhark.IR.Prop.Aliases.AliasedOp (Futhark.IR.SegOp.SegOp lvl rep) instance Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.Rep.Op rep) => Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.IR.Pretty.PrettyRep rep, Text.PrettyPrint.Mainland.Class.Pretty lvl) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SegOp.SegOp lvl rep) instance Futhark.IR.Prop.ASTRep rep => Futhark.Analysis.SymbolTable.IndexOp (Futhark.IR.SegOp.SegOp lvl rep) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.ASTConstraints lvl) => Futhark.IR.Prop.IsOp (Futhark.IR.SegOp.SegOp lvl rep) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.SegOp.SegSpace instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.IR.SegOp.SegSpace instance Futhark.IR.Prop.ASTRep rep => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.SegOp.KernelBody rep) instance Futhark.IR.Prop.ASTRep rep => Futhark.Transform.Substitute.Substitute (Futhark.IR.SegOp.KernelBody rep) instance Futhark.IR.Prop.ASTRep rep => Futhark.Transform.Rename.Rename (Futhark.IR.SegOp.KernelBody rep) instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SegOp.KernelBody rep) instance Futhark.IR.Prop.Names.FreeIn Futhark.IR.SegOp.KernelResult instance Futhark.Transform.Substitute.Substitute Futhark.IR.SegOp.KernelResult instance Futhark.Transform.Rename.Rename Futhark.IR.SegOp.KernelResult instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.SegOp.KernelResult instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.IR.SegOp.KernelResult instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SegOp.SegBinOp rep) instance Futhark.IR.Prop.Names.FreeIn Futhark.IR.SegOp.SplitOrdering instance Futhark.Transform.Substitute.Substitute Futhark.IR.SegOp.SplitOrdering instance Futhark.Transform.Rename.Rename Futhark.IR.SegOp.SplitOrdering instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.IR.SegOp.SplitOrdering module Futhark.Pass.ExtractKernels.BlockedKernel -- | Constraints pertinent to performing distribution/flattening. type DistRep rep = (Buildable rep, HasSegOp rep, BuilderOps rep, LetDec rep ~ Type, ExpDec rep ~ (), BodyDec rep ~ (), CanBeAliased (Op rep)) type MkSegLevel rep m = [SubExp] -> String -> ThreadRecommendation -> BuilderT rep m (SegOpLevel rep) data ThreadRecommendation ManyThreads :: ThreadRecommendation NoRecommendation :: SegVirt -> ThreadRecommendation segRed :: (MonadFreshNames m, DistRep rep, HasScope rep m) => SegOpLevel rep -> Pat rep -> SubExp -> [SegBinOp rep] -> Lambda rep -> [VName] -> [(VName, SubExp)] -> [KernelInput] -> m (Stms rep) nonSegRed :: (MonadFreshNames m, DistRep rep, HasScope rep m) => SegOpLevel rep -> Pat rep -> SubExp -> [SegBinOp rep] -> Lambda rep -> [VName] -> m (Stms rep) segScan :: (MonadFreshNames m, DistRep rep, HasScope rep m) => SegOpLevel rep -> Pat rep -> SubExp -> [SegBinOp rep] -> Lambda rep -> [VName] -> [(VName, SubExp)] -> [KernelInput] -> m (Stms rep) segHist :: (DistRep rep, MonadFreshNames m, HasScope rep m) => SegOpLevel rep -> Pat rep -> SubExp -> [(VName, SubExp)] -> [KernelInput] -> [HistOp rep] -> Lambda rep -> [VName] -> m (Stms rep) segMap :: (MonadFreshNames m, DistRep rep, HasScope rep m) => SegOpLevel rep -> Pat rep -> SubExp -> Lambda rep -> [VName] -> [(VName, SubExp)] -> [KernelInput] -> m (Stms rep) mapKernel :: (DistRep rep, HasScope rep m, MonadFreshNames m) => MkSegLevel rep m -> [(VName, SubExp)] -> [KernelInput] -> [Type] -> KernelBody rep -> m (SegOp (SegOpLevel rep) rep, Stms rep) data KernelInput KernelInput :: VName -> Type -> VName -> [SubExp] -> KernelInput [kernelInputName] :: KernelInput -> VName [kernelInputType] :: KernelInput -> Type [kernelInputArray] :: KernelInput -> VName [kernelInputIndices] :: KernelInput -> [SubExp] readKernelInput :: (DistRep (Rep m), MonadBuilder m) => KernelInput -> m () mkSegSpace :: MonadFreshNames m => [(VName, SubExp)] -> m SegSpace dummyDim :: (MonadFreshNames m, MonadBuilder m, DistRep (Rep m)) => Pat (Rep m) -> m (Pat (Rep m), [(VName, SubExp)], m ()) instance GHC.Show.Show Futhark.Pass.ExtractKernels.BlockedKernel.KernelInput module Futhark.Pass.ExtractKernels.Distribution type Target = (PatT Type, Result) -- | First pair element is the very innermost ("current") target. In the -- list, the outermost target comes first. Invariant: Every element of a -- pattern must be present as the result of the immediately enclosing -- target. This is ensured by pushInnerTarget by removing unused -- pattern elements. data Targets ppTargets :: Targets -> String singleTarget :: Target -> Targets outerTarget :: Targets -> Target innerTarget :: Targets -> Target pushInnerTarget :: Target -> Targets -> Targets popInnerTarget :: Targets -> Maybe (Target, Targets) targetsScope :: DistRep rep => Targets -> Scope rep data LoopNesting MapNesting :: PatT Type -> StmAux () -> SubExp -> [(Param Type, VName)] -> LoopNesting [loopNestingPat] :: LoopNesting -> PatT Type [loopNestingAux] :: LoopNesting -> StmAux () [loopNestingWidth] :: LoopNesting -> SubExp [loopNestingParamsAndArrs] :: LoopNesting -> [(Param Type, VName)] ppLoopNesting :: LoopNesting -> String scopeOfLoopNesting :: DistRep rep => LoopNesting -> Scope rep data Nesting Nesting :: Names -> LoopNesting -> Nesting [nestingLetBound] :: Nesting -> Names [nestingLoop] :: Nesting -> LoopNesting type Nestings = (Nesting, [Nesting]) ppNestings :: Nestings -> String letBindInInnerNesting :: Names -> Nestings -> Nestings singleNesting :: Nesting -> Nestings pushInnerNesting :: Nesting -> Nestings -> Nestings -- | Note: first element is *outermost* nesting. This is different from the -- similar types elsewhere! type KernelNest = (LoopNesting, [LoopNesting]) ppKernelNest :: KernelNest -> String newKernel :: LoopNesting -> KernelNest -- | Retrieve the innermost kernel nesting. innermostKernelNesting :: KernelNest -> LoopNesting -- | Add new outermost nesting, pushing the current outermost to the list, -- also taking care to swap patterns if necessary. pushKernelNesting :: Target -> LoopNesting -> KernelNest -> KernelNest -- | Add new innermost nesting, pushing the current outermost to the list. -- It is important that the Target has the right order -- (non-permuted compared to what is expected by the outer nests). pushInnerKernelNesting :: Target -> LoopNesting -> KernelNest -> KernelNest kernelNestLoops :: KernelNest -> [LoopNesting] kernelNestWidths :: KernelNest -> [SubExp] boundInKernelNest :: KernelNest -> Names boundInKernelNests :: KernelNest -> [Names] -- | Flatten a kernel nesting to: -- --
-- Scatter length lambda inputs outputs ---- -- Scatter maps values from a set of input arrays to indices and values -- of a set of output arrays. It is able to write multiple values to -- multiple outputs each of which may have multiple dimensions. -- -- inputs is a list of input arrays, all having size -- length, elements of which are applied to the lambda -- function. For instance, if there are two arrays, lambda will -- get two values as input, one from each array. -- -- outputs specifies the result of the lambda and which -- arrays to write to. Each element of the list consists of a -- VName specifying which array to scatter to, a Shape -- describing the shape of that array, and an Int describing how -- many elements should be written to that array for each invocation of -- the lambda. -- -- lambda is a function that takes inputs from inputs and -- returns values according to the output-specification in -- outputs. It returns values in the following manner: -- --
-- Hist length dest-arrays-and-ops fun arrays ---- -- The first SubExp is the length of the input arrays. The first list -- describes the operations to perform. The Lambda is the bucket -- function. Finally comes the input images. Hist :: SubExp -> [HistOp rep] -> Lambda rep -> [VName] -> SOAC rep -- | A combination of scan, reduction, and map. The first SubExp is -- the size of the input arrays. Screma :: SubExp -> [VName] -> ScremaForm rep -> SOAC rep -- | How many reduction results are produced by these Scans? scanResults :: [Scan rep] -> Int -- | Combine multiple scan operators to a single operator. singleScan :: Buildable rep => [Scan rep] -> Scan rep -- | How many reduction results are produced by these Reduces? redResults :: [Reduce rep] -> Int -- | Combine multiple reduction operators to a single operator. singleReduce :: Buildable rep => [Reduce rep] -> Reduce rep -- | The types produced by a single Screma, given the size of the -- input array. scremaType :: SubExp -> ScremaForm rep -> [Type] -- | Construct a lambda that takes parameters of the given types and simply -- returns them unchanged. mkIdentityLambda :: (Buildable rep, MonadFreshNames m) => [Type] -> m (Lambda rep) -- | Is the given lambda an identity lambda? isIdentityLambda :: Lambda rep -> Bool -- | A lambda with no parameters that returns no values. nilFn :: Buildable rep => Lambda rep -- | Construct a Screma with possibly multiple scans, and the given map -- function. scanomapSOAC :: [Scan rep] -> Lambda rep -> ScremaForm rep -- | Construct a Screma with possibly multiple reductions, and the given -- map function. redomapSOAC :: [Reduce rep] -> Lambda rep -> ScremaForm rep -- | Construct a Screma with possibly multiple scans, and identity map -- function. scanSOAC :: (Buildable rep, MonadFreshNames m) => [Scan rep] -> m (ScremaForm rep) -- | Construct a Screma with possibly multiple reductions, and identity map -- function. reduceSOAC :: (Buildable rep, MonadFreshNames m) => [Reduce rep] -> m (ScremaForm rep) -- | Construct a Screma corresponding to a map. mapSOAC :: Lambda rep -> ScremaForm rep -- | Does this Screma correspond to a scan-map composition? isScanomapSOAC :: ScremaForm rep -> Maybe ([Scan rep], Lambda rep) -- | Does this Screma correspond to pure scan? isScanSOAC :: ScremaForm rep -> Maybe [Scan rep] -- | Does this Screma correspond to a reduce-map composition? isRedomapSOAC :: ScremaForm rep -> Maybe ([Reduce rep], Lambda rep) -- | Does this Screma correspond to a pure reduce? isReduceSOAC :: ScremaForm rep -> Maybe [Reduce rep] -- | Does this Screma correspond to a simple map, without any reduction or -- scan results? isMapSOAC :: ScremaForm rep -> Maybe (Lambda rep) -- |
-- groupScatterResults specification results ---- -- Groups the index values and result values of results according -- to the specification. -- -- This function is used for extracting and grouping the results of a -- scatter. In the SOAC representation, the lambda inside a -- Scatter returns all indices and values as one big list. This -- function groups each value with its corresponding indices (as -- determined by the Shape of the output array). -- -- The elements of the resulting list correspond to the shape and name of -- the output parameters, in addition to a list of values written to that -- output parameter, along with the array indices marking where to write -- them to. -- -- See Scatter for more information. groupScatterResults :: [(Shape, Int, array)] -> [a] -> [(Shape, array, [([a], a)])] -- |
-- groupScatterResults' specification results ---- -- Groups the index values and result values of results according -- to the output specification. This is the simpler version of -- groupScatterResults, which doesn't return any information -- about shapes or output arrays. -- -- See groupScatterResults for more information, groupScatterResults' :: [(Shape, Int, array)] -> [a] -> [([a], a)] -- |
-- splitScatterResults specification results ---- -- Splits the results array into indices and values according to the -- output specification. -- -- See groupScatterResults for more information. splitScatterResults :: [(Shape, Int, array)] -> [a] -> ([a], [a]) -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper rep rep m -- | Map a monadic action across the immediate children of a SOAC. The -- mapping does not descend recursively into subexpressions and is done -- left-to-right. mapSOACM :: (Applicative m, Monad m) => SOACMapper frep trep m -> SOAC frep -> m (SOAC trep) -- | The type of a SOAC. soacType :: SOAC rep -> [Type] -- | Type-check a SOAC. typeCheckSOAC :: Checkable rep => SOAC (Aliases rep) -> TypeM rep () -- | Prettyprint the given Screma. ppScrema :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> ScremaForm rep -> Doc -- | Prettyprint the given histogram operation. ppHist :: (PrettyRep rep, Pretty inp) => SubExp -> [HistOp rep] -> Lambda rep -> [inp] -> Doc instance Futhark.IR.Rep.RepTypes Futhark.IR.MC.MC instance Futhark.IR.Prop.ASTRep Futhark.IR.MC.MC instance Futhark.TypeCheck.CheckableOp Futhark.IR.MC.MC instance Futhark.TypeCheck.Checkable Futhark.IR.MC.MC instance Futhark.Builder.Class.Buildable Futhark.IR.MC.MC instance Futhark.Builder.BuilderOps Futhark.IR.MC.MC instance Futhark.Builder.BuilderOps (Futhark.Optimise.Simplify.Rep.Wise Futhark.IR.MC.MC) instance Futhark.IR.Pretty.PrettyRep Futhark.IR.MC.MC instance Futhark.IR.SegOp.HasSegOp Futhark.IR.MC.MC instance Futhark.IR.SegOp.HasSegOp (Futhark.Optimise.Simplify.Rep.Wise Futhark.IR.MC.MC) module Futhark.IR.GPU.Op -- | A simple size-level query or computation. data SizeOp -- | SplitSpace o w i elems_per_thread. -- -- Computes how to divide array elements to threads in a kernel. Returns -- the number of elements in the chunk that the current thread should -- take. -- -- w is the length of the outer dimension in the array. -- i is the current thread index. Each thread takes at most -- elems_per_thread elements. -- -- If the order o is SplitContiguous, thread with index -- i should receive elements i*elems_per_tread, -- i*elems_per_thread + 1, ..., i*elems_per_thread + -- (elems_per_thread-1). -- -- If the order o is SplitStrided stride, the -- thread will receive elements i, i+stride, i+2*stride, ..., -- i+(elems_per_thread-1)*stride. SplitSpace :: SplitOrdering -> SubExp -> SubExp -> SubExp -> SizeOp -- | Produce some runtime-configurable size. GetSize :: Name -> SizeClass -> SizeOp -- | The maximum size of some class. GetSizeMax :: SizeClass -> SizeOp -- | Compare size (likely a threshold) with some integer value. CmpSizeLe :: Name -> SizeClass -> SubExp -> SizeOp -- | CalcNumGroups w max_num_groups group_size calculates the -- number of GPU workgroups to use for an input of the given size. The -- Name is a size name. Note that w is an i64 to avoid -- overflow issues. CalcNumGroups :: SubExp -> Name -> SubExp -> SizeOp -- | A host-level operation; parameterised by what else it can do. data HostOp rep op -- | A segmented operation. SegOp :: SegOp SegLevel rep -> HostOp rep op SizeOp :: SizeOp -> HostOp rep op OtherOp :: op -> HostOp rep op typeCheckHostOp :: Checkable rep => (SegLevel -> OpWithAliases (Op rep) -> TypeM rep ()) -> Maybe SegLevel -> (op -> TypeM rep ()) -> HostOp (Aliases rep) op -> TypeM rep () -- | At which level the *body* of a SegOp executes. data SegLevel SegThread :: Count NumGroups SubExp -> Count GroupSize SubExp -> SegVirt -> SegLevel [segNumGroups] :: SegLevel -> Count NumGroups SubExp [segGroupSize] :: SegLevel -> Count GroupSize SubExp [segVirt] :: SegLevel -> SegVirt SegGroup :: Count NumGroups SubExp -> Count GroupSize SubExp -> SegVirt -> SegLevel [segNumGroups] :: SegLevel -> Count NumGroups SubExp [segGroupSize] :: SegLevel -> Count GroupSize SubExp [segVirt] :: SegLevel -> SegVirt instance GHC.Show.Show Futhark.IR.GPU.Op.SegLevel instance GHC.Classes.Ord Futhark.IR.GPU.Op.SegLevel instance GHC.Classes.Eq Futhark.IR.GPU.Op.SegLevel instance GHC.Show.Show Futhark.IR.GPU.Op.SizeOp instance GHC.Classes.Ord Futhark.IR.GPU.Op.SizeOp instance GHC.Classes.Eq Futhark.IR.GPU.Op.SizeOp instance (Futhark.IR.Rep.RepTypes rep, GHC.Show.Show op) => GHC.Show.Show (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Rep.RepTypes rep, GHC.Classes.Ord op) => GHC.Classes.Ord (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Rep.RepTypes rep, GHC.Classes.Eq op) => GHC.Classes.Eq (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Prop.ASTRep rep, Futhark.Transform.Substitute.Substitute op) => Futhark.Transform.Substitute.Substitute (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Prop.ASTRep rep, Futhark.Transform.Rename.Rename op) => Futhark.Transform.Rename.Rename (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.IsOp op) => Futhark.IR.Prop.IsOp (Futhark.IR.GPU.Op.HostOp rep op) instance Futhark.IR.Prop.TypeOf.TypedOp op => Futhark.IR.Prop.TypeOf.TypedOp (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Prop.Aliases.Aliased rep, Futhark.IR.Prop.Aliases.AliasedOp op, Futhark.IR.Prop.ASTRep rep) => Futhark.IR.Prop.Aliases.AliasedOp (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Names.FreeIn op) => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep), Futhark.IR.Prop.Aliases.CanBeAliased op, Futhark.IR.Prop.ASTRep rep) => Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.Rep.Op rep), Futhark.Optimise.Simplify.Rep.CanBeWise op, Futhark.IR.Prop.ASTRep rep) => Futhark.Optimise.Simplify.Rep.CanBeWise (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Prop.ASTRep rep, Futhark.Analysis.SymbolTable.IndexOp op) => Futhark.Analysis.SymbolTable.IndexOp (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Pretty.PrettyRep rep, Text.PrettyPrint.Mainland.Class.Pretty op) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.Rep.Op rep), Futhark.Analysis.Metrics.OpMetrics op) => Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.GPU.Op.HostOp rep op) instance Futhark.Transform.Substitute.Substitute Futhark.IR.GPU.Op.SizeOp instance Futhark.Transform.Rename.Rename Futhark.IR.GPU.Op.SizeOp instance Futhark.IR.Prop.IsOp Futhark.IR.GPU.Op.SizeOp instance Futhark.IR.Prop.TypeOf.TypedOp Futhark.IR.GPU.Op.SizeOp instance Futhark.IR.Prop.Aliases.AliasedOp Futhark.IR.GPU.Op.SizeOp instance Futhark.IR.Prop.Names.FreeIn Futhark.IR.GPU.Op.SizeOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.GPU.Op.SizeOp instance Futhark.Analysis.Metrics.OpMetrics Futhark.IR.GPU.Op.SizeOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.GPU.Op.SegLevel instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.IR.GPU.Op.SegLevel instance Futhark.Transform.Substitute.Substitute Futhark.IR.GPU.Op.SegLevel instance Futhark.Transform.Rename.Rename Futhark.IR.GPU.Op.SegLevel instance Futhark.IR.Prop.Names.FreeIn Futhark.IR.GPU.Op.SegLevel -- | A representation with flat parallelism via GPU-oriented kernels. module Futhark.IR.GPU -- | The phantom data type for the kernels representation. data GPU -- | Like Mapper, but just for SOACs. data SOACMapper frep trep m SOACMapper :: (SubExp -> m SubExp) -> (Lambda frep -> m (Lambda trep)) -> (VName -> m VName) -> SOACMapper frep trep m [mapOnSOACSubExp] :: SOACMapper frep trep m -> SubExp -> m SubExp [mapOnSOACLambda] :: SOACMapper frep trep m -> Lambda frep -> m (Lambda trep) [mapOnSOACVName] :: SOACMapper frep trep m -> VName -> m VName -- | How to compute a single reduction result. data Reduce rep Reduce :: Commutativity -> Lambda rep -> [SubExp] -> Reduce rep [redComm] :: Reduce rep -> Commutativity [redLambda] :: Reduce rep -> Lambda rep [redNeutral] :: Reduce rep -> [SubExp] -- | How to compute a single scan result. data Scan rep Scan :: Lambda rep -> [SubExp] -> Scan rep [scanLambda] :: Scan rep -> Lambda rep [scanNeutral] :: Scan rep -> [SubExp] -- | The essential parts of a Screma factored out (everything except -- the input arrays). data ScremaForm rep ScremaForm :: [Scan rep] -> [Reduce rep] -> Lambda rep -> ScremaForm rep -- | What kind of stream is this? data StreamForm rep Parallel :: StreamOrd -> Commutativity -> Lambda rep -> StreamForm rep Sequential :: StreamForm rep -- | Is the stream chunk required to correspond to a contiguous subsequence -- of the original input (InOrder) or not? Disorder streams -- can be more efficient, but not all algorithms work with this. data StreamOrd InOrder :: StreamOrd Disorder :: StreamOrd -- | A second-order array combinator (SOAC). data SOAC rep Stream :: SubExp -> [VName] -> StreamForm rep -> [SubExp] -> Lambda rep -> SOAC rep -- |
-- Scatter length lambda inputs outputs ---- -- Scatter maps values from a set of input arrays to indices and values -- of a set of output arrays. It is able to write multiple values to -- multiple outputs each of which may have multiple dimensions. -- -- inputs is a list of input arrays, all having size -- length, elements of which are applied to the lambda -- function. For instance, if there are two arrays, lambda will -- get two values as input, one from each array. -- -- outputs specifies the result of the lambda and which -- arrays to write to. Each element of the list consists of a -- VName specifying which array to scatter to, a Shape -- describing the shape of that array, and an Int describing how -- many elements should be written to that array for each invocation of -- the lambda. -- -- lambda is a function that takes inputs from inputs and -- returns values according to the output-specification in -- outputs. It returns values in the following manner: -- --
-- Hist length dest-arrays-and-ops fun arrays ---- -- The first SubExp is the length of the input arrays. The first list -- describes the operations to perform. The Lambda is the bucket -- function. Finally comes the input images. Hist :: SubExp -> [HistOp rep] -> Lambda rep -> [VName] -> SOAC rep -- | A combination of scan, reduction, and map. The first SubExp is -- the size of the input arrays. Screma :: SubExp -> [VName] -> ScremaForm rep -> SOAC rep -- | How many reduction results are produced by these Scans? scanResults :: [Scan rep] -> Int -- | Combine multiple scan operators to a single operator. singleScan :: Buildable rep => [Scan rep] -> Scan rep -- | How many reduction results are produced by these Reduces? redResults :: [Reduce rep] -> Int -- | Combine multiple reduction operators to a single operator. singleReduce :: Buildable rep => [Reduce rep] -> Reduce rep -- | The types produced by a single Screma, given the size of the -- input array. scremaType :: SubExp -> ScremaForm rep -> [Type] -- | Construct a lambda that takes parameters of the given types and simply -- returns them unchanged. mkIdentityLambda :: (Buildable rep, MonadFreshNames m) => [Type] -> m (Lambda rep) -- | Is the given lambda an identity lambda? isIdentityLambda :: Lambda rep -> Bool -- | A lambda with no parameters that returns no values. nilFn :: Buildable rep => Lambda rep -- | Construct a Screma with possibly multiple scans, and the given map -- function. scanomapSOAC :: [Scan rep] -> Lambda rep -> ScremaForm rep -- | Construct a Screma with possibly multiple reductions, and the given -- map function. redomapSOAC :: [Reduce rep] -> Lambda rep -> ScremaForm rep -- | Construct a Screma with possibly multiple scans, and identity map -- function. scanSOAC :: (Buildable rep, MonadFreshNames m) => [Scan rep] -> m (ScremaForm rep) -- | Construct a Screma with possibly multiple reductions, and identity map -- function. reduceSOAC :: (Buildable rep, MonadFreshNames m) => [Reduce rep] -> m (ScremaForm rep) -- | Construct a Screma corresponding to a map. mapSOAC :: Lambda rep -> ScremaForm rep -- | Does this Screma correspond to a scan-map composition? isScanomapSOAC :: ScremaForm rep -> Maybe ([Scan rep], Lambda rep) -- | Does this Screma correspond to pure scan? isScanSOAC :: ScremaForm rep -> Maybe [Scan rep] -- | Does this Screma correspond to a reduce-map composition? isRedomapSOAC :: ScremaForm rep -> Maybe ([Reduce rep], Lambda rep) -- | Does this Screma correspond to a pure reduce? isReduceSOAC :: ScremaForm rep -> Maybe [Reduce rep] -- | Does this Screma correspond to a simple map, without any reduction or -- scan results? isMapSOAC :: ScremaForm rep -> Maybe (Lambda rep) -- |
-- groupScatterResults specification results ---- -- Groups the index values and result values of results according -- to the specification. -- -- This function is used for extracting and grouping the results of a -- scatter. In the SOAC representation, the lambda inside a -- Scatter returns all indices and values as one big list. This -- function groups each value with its corresponding indices (as -- determined by the Shape of the output array). -- -- The elements of the resulting list correspond to the shape and name of -- the output parameters, in addition to a list of values written to that -- output parameter, along with the array indices marking where to write -- them to. -- -- See Scatter for more information. groupScatterResults :: [(Shape, Int, array)] -> [a] -> [(Shape, array, [([a], a)])] -- |
-- groupScatterResults' specification results ---- -- Groups the index values and result values of results according -- to the output specification. This is the simpler version of -- groupScatterResults, which doesn't return any information -- about shapes or output arrays. -- -- See groupScatterResults for more information, groupScatterResults' :: [(Shape, Int, array)] -> [a] -> [([a], a)] -- |
-- splitScatterResults specification results ---- -- Splits the results array into indices and values according to the -- output specification. -- -- See groupScatterResults for more information. splitScatterResults :: [(Shape, Int, array)] -> [a] -> ([a], [a]) -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper rep rep m -- | Map a monadic action across the immediate children of a SOAC. The -- mapping does not descend recursively into subexpressions and is done -- left-to-right. mapSOACM :: (Applicative m, Monad m) => SOACMapper frep trep m -> SOAC frep -> m (SOAC trep) -- | The type of a SOAC. soacType :: SOAC rep -> [Type] -- | Type-check a SOAC. typeCheckSOAC :: Checkable rep => SOAC (Aliases rep) -> TypeM rep () -- | Prettyprint the given Screma. ppScrema :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> ScremaForm rep -> Doc -- | Prettyprint the given histogram operation. ppHist :: (PrettyRep rep, Pretty inp) => SubExp -> [HistOp rep] -> Lambda rep -> [inp] -> Doc instance Futhark.IR.Rep.RepTypes Futhark.IR.GPU.GPU instance Futhark.IR.Prop.ASTRep Futhark.IR.GPU.GPU instance Futhark.TypeCheck.CheckableOp Futhark.IR.GPU.GPU instance Futhark.TypeCheck.Checkable Futhark.IR.GPU.GPU instance Futhark.Builder.Class.Buildable Futhark.IR.GPU.GPU instance Futhark.Builder.BuilderOps Futhark.IR.GPU.GPU instance Futhark.IR.Pretty.PrettyRep Futhark.IR.GPU.GPU instance Futhark.IR.SegOp.HasSegOp Futhark.IR.GPU.GPU -- | Do various kernel optimisations - mostly related to coalescing. module Futhark.Pass.KernelBabysitting -- | The pass definition. babysitKernels :: Pass GPU GPU module Futhark.Pass.ExtractKernels.ToGPU getSize :: (MonadBuilder m, Op (Rep m) ~ HostOp (Rep m) inner) => String -> SizeClass -> m SubExp segThread :: (MonadBuilder m, Op (Rep m) ~ HostOp (Rep m) inner) => String -> m SegLevel soacsLambdaToGPU :: Lambda SOACS -> Lambda GPU soacsStmToGPU :: Stm SOACS -> Stm GPU scopeForGPU :: Scope SOACS -> Scope GPU scopeForSOACs :: Scope GPU -> Scope SOACS injectSOACS :: (Monad m, SameScope from to, ExpDec from ~ ExpDec to, BodyDec from ~ BodyDec to, RetType from ~ RetType to, BranchType from ~ BranchType to, Op from ~ SOAC from) => (SOAC to -> Op to) -> Rephraser m from to -- | Extraction of parallelism from a SOACs program. This generates -- parallel constructs aimed at CPU execution, which in particular may -- involve ad-hoc irregular nested parallelism. module Futhark.Pass.ExtractMulticore -- | Transform a program using SOACs to a program in the MC -- representation, using some amount of flattening. extractMulticore :: Pass SOACS MC instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Pass.ExtractMulticore.ExtractM instance Futhark.IR.Prop.Scope.LocalScope Futhark.IR.MC.MC Futhark.Pass.ExtractMulticore.ExtractM instance Futhark.IR.Prop.Scope.HasScope Futhark.IR.MC.MC Futhark.Pass.ExtractMulticore.ExtractM instance GHC.Base.Monad Futhark.Pass.ExtractMulticore.ExtractM instance GHC.Base.Applicative Futhark.Pass.ExtractMulticore.ExtractM instance GHC.Base.Functor Futhark.Pass.ExtractMulticore.ExtractM instance Futhark.Util.Log.MonadLogger Futhark.Pass.ExtractMulticore.ExtractM module Futhark.Pass.ExtractKernels.StreamKernel -- | Like segThread, but cap the thread count to the input size. -- This is more efficient for small kernels, e.g. summing a small array. segThreadCapped :: MonadFreshNames m => MkSegLevel GPU m streamRed :: (MonadFreshNames m, HasScope GPU m) => MkSegLevel GPU m -> Pat GPU -> SubExp -> Commutativity -> Lambda GPU -> Lambda GPU -> [SubExp] -> [VName] -> m (Stms GPU) streamMap :: (MonadFreshNames m, HasScope GPU m) => MkSegLevel GPU m -> [String] -> [PatElem GPU] -> SubExp -> Commutativity -> Lambda GPU -> [SubExp] -> [VName] -> m ((SubExp, [VName]), Stms GPU) instance GHC.Show.Show Futhark.Pass.ExtractKernels.StreamKernel.KernelSize instance GHC.Classes.Ord Futhark.Pass.ExtractKernels.StreamKernel.KernelSize instance GHC.Classes.Eq Futhark.Pass.ExtractKernels.StreamKernel.KernelSize -- | Extract limited nested parallelism for execution inside individual -- kernel workgroups. module Futhark.Pass.ExtractKernels.Intragroup -- | Convert the statements inside a map nest to kernel statements, -- attempting to parallelise any remaining (top-level) parallel -- statements. Anything that is not a map, scan or reduction will simply -- be sequentialised. This includes sequential loops that contain maps, -- scans or reduction. In the future, we could probably do something more -- clever. Make sure that the amount of parallelism to be exploited does -- not exceed the group size. Further, as a hack we also consider the -- size of all intermediate arrays as "parallelism to be exploited" to -- avoid exploding local memory. -- -- We distinguish between "minimum group size" and "maximum exploitable -- parallelism". intraGroupParallelise :: (MonadFreshNames m, LocalScope GPU m) => KernelNest -> Lambda -> m (Maybe ((SubExp, SubExp), SubExp, Log, Stms GPU, Stms GPU)) instance Futhark.Util.Log.MonadLogger Futhark.Pass.ExtractKernels.Intragroup.IntraGroupM instance GHC.Base.Semigroup Futhark.Pass.ExtractKernels.Intragroup.IntraAcc instance GHC.Base.Monoid Futhark.Pass.ExtractKernels.Intragroup.IntraAcc -- | Kernel extraction. -- -- In the following, I will use the term "width" to denote the amount of -- immediate parallelism in a map - that is, the outer size of the -- array(s) being used as input. -- --
-- map -- map(f) -- stms_a... -- map(g) ---- -- Then we want to distribute to: -- --
-- map -- map(f) -- map -- stms_a -- map -- map(g) ---- -- But for now only if -- --
-- map -- loop -- map -- map ---- -- If we distribute the loop and interchange the outer map into the loop, -- we get this: -- --
-- loop -- map -- map -- map -- map ---- -- Now more parallelism may be available. -- --
-- map -- map(f) -- map(g) -- map ---- -- Presume that map(f) is unbalanced. By the simple rule above, -- we would then fully sequentialise it, resulting in this: -- --
-- map -- loop -- map -- map ---- --
-- loop(f) -- map -- map(g) -- map -- map ---- -- After flattening the two nests we can obtain more parallelism. -- -- When distributing a map, we also need to distribute everything that -- the map depends on - possibly as its own map. When distributing a set -- of scalar bindings, we will need to know which of the binding results -- are used afterwards. Hence, we will need to compute usage information. -- --
-- redomap(op, -- fn (v) => -- map(f) -- map(g), -- e,a) ---- -- distributes to -- --
-- let b = map(fn v => -- let acc = e -- map(f), -- a) -- redomap(op, -- fn (v,dist) => -- map(g), -- e,a,b) ---- -- Note that there may be further kernel extraction opportunities inside -- the map(f). The downside of this approach is that the -- intermediate array (b above) must be written to main memory. -- An often better approach is to just turn the entire redomap -- into a single kernel. module Futhark.Pass.ExtractKernels -- | Transform a program using SOACs to a program using explicit kernels, -- using the kernel extraction transformation. extractKernels :: Pass SOACS GPU instance Futhark.Util.Log.MonadLogger Futhark.Pass.ExtractKernels.DistribM instance Control.Monad.State.Class.MonadState Futhark.Pass.ExtractKernels.State Futhark.Pass.ExtractKernels.DistribM instance Futhark.IR.Prop.Scope.LocalScope Futhark.IR.GPU.GPU Futhark.Pass.ExtractKernels.DistribM instance Futhark.IR.Prop.Scope.HasScope Futhark.IR.GPU.GPU Futhark.Pass.ExtractKernels.DistribM instance GHC.Base.Monad Futhark.Pass.ExtractKernels.DistribM instance GHC.Base.Applicative Futhark.Pass.ExtractKernels.DistribM instance GHC.Base.Functor Futhark.Pass.ExtractKernels.DistribM instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Pass.ExtractKernels.DistribM module Futhark.Optimise.TileLoops.Shared type TileM = ReaderT (Scope GPU) (State VNameSource) segMap1D :: String -> SegLevel -> ResultManifest -> (VName -> Builder GPU Result) -> Builder GPU [VName] segMap2D :: String -> SegLevel -> ResultManifest -> (SubExp, SubExp) -> ((VName, VName) -> Builder GPU Result) -> Builder GPU [VName] segMap3D :: String -> SegLevel -> ResultManifest -> (SubExp, SubExp, SubExp) -> ((VName, VName, VName) -> Builder GPU Result) -> Builder GPU [VName] segScatter2D :: String -> SubExp -> VName -> SegLevel -> (SubExp, SubExp) -> ((VName, VName) -> Builder GPU (SubExp, SubExp)) -> Builder GPU [VName] -- | The variance table keeps a mapping from a variable name (something -- produced by a Stm) to the kernel thread indices that name -- depends on. If a variable is not present in this table, that means it -- is bound outside the kernel (and so can be considered invariant to all -- dimensions). type VarianceTable = Map VName Names varianceInStms :: VarianceTable -> Stms GPU -> VarianceTable isTileableRedomap :: Stm GPU -> Maybe (SubExp, [VName], (Commutativity, Lambda GPU, [SubExp], Lambda GPU)) -- | Sinking is conceptually the opposite of hoisting. The idea is -- to take code that looks like this: -- --
-- x = xs[i]
-- y = ys[i]
-- if x != 0 then {
-- y
-- } else {
-- 0
-- }
--
--
-- and turn it into
--
--
-- x = xs[i]
-- if x != 0 then {
-- y = ys[i]
-- y
-- } else {
-- 0
-- }
--
--
-- The idea is to delay loads from memory until (if) they are actually
-- needed. Code patterns like the above is particularly common in code
-- that makes use of pattern matching on sum types.
--
-- We are currently quite conservative about when we do this. In
-- particular, if any consumption is going on in a body, we don't do
-- anything. This is far too conservative. Also, we are careful never to
-- duplicate work.
--
-- This pass redundantly computes free-variable information a lot. If you
-- ever see this pass as being a compilation speed bottleneck, start by
-- caching that a bit.
--
-- This pass is defined on post-SOACS representations. This is not
-- because we do anything GPU-specific here, but simply because more
-- explicit indexing is going on after SOACs are gone.
module Futhark.Optimise.Sink
-- | Sinking in GPU kernels.
sinkGPU :: Pass GPU GPU
-- | Sinking for multicore.
sinkMC :: Pass MC MC
module Futhark.Optimise.InPlaceLowering.LowerIntoStm
lowerUpdateGPU :: MonadFreshNames m => LowerUpdate GPU m
lowerUpdate :: (MonadFreshNames m, Buildable rep, LetDec rep ~ Type, CanBeAliased (Op rep)) => LowerUpdate rep m
type LowerUpdate rep m = Scope (Aliases rep) -> Stm (Aliases rep) -> [DesiredUpdate (LetDec (Aliases rep))] -> Maybe (m [Stm (Aliases rep)])
data DesiredUpdate dec
DesiredUpdate :: VName -> dec -> Certs -> VName -> Slice SubExp -> VName -> DesiredUpdate dec
-- | Name of result.
[updateName] :: DesiredUpdate dec -> VName
-- | Type of result.
[updateType] :: DesiredUpdate dec -> dec
[updateCerts] :: DesiredUpdate dec -> Certs
[updateSource] :: DesiredUpdate dec -> VName
[updateIndices] :: DesiredUpdate dec -> Slice SubExp
[updateValue] :: DesiredUpdate dec -> VName
instance GHC.Show.Show dec => GHC.Show.Show (Futhark.Optimise.InPlaceLowering.LowerIntoStm.DesiredUpdate dec)
instance GHC.Show.Show dec => GHC.Show.Show (Futhark.Optimise.InPlaceLowering.LowerIntoStm.LoopResultSummary dec)
instance GHC.Base.Functor Futhark.Optimise.InPlaceLowering.LowerIntoStm.DesiredUpdate
-- | This module implements an optimisation that moves in-place updates
-- into/before loops where possible, with the end goal of minimising
-- memory copies. As an example, consider this program:
--
-- -- let r = -- loop (r1 = r0) = for i < n do -- let a = r1[i] -- let r1[i] = a * i -- in r1 -- ... -- let x = y with [k] <- r in -- ... ---- -- We want to turn this into the following: -- --
-- let x0 = y with [k] <- r0 -- loop (x = x0) = for i < n do -- let a = a[k,i] -- let x[k,i] = a * i -- in x -- let r = x[k] in -- ... ---- -- The intent is that we are also going to optimise the new data movement -- (in the x0-binding), possibly by changing how r0 is -- defined. For the above transformation to be valid, a number of -- conditions must be fulfilled: -- --
-- let a = x + y -- let b = x + y ---- -- becomes: -- --
-- let a = x + y -- let b = a ---- -- After which copy propagation in the simplifier will actually remove -- the definition of b. -- -- Our CSE is still rather stupid. No normalisation is performed, so the -- expressions x+y and y+x will be considered distinct. -- Furthermore, no expression with its own binding will be considered -- equal to any other, since the variable names will be distinct. This -- affects SOACs in particular. module Futhark.Optimise.CSE -- | Perform CSE on every function in a program. -- -- If the boolean argument is false, the pass will not perform CSE on -- expressions producing arrays. This should be disabled when the rep has -- memory information, since at that point arrays have identity beyond -- their value. performCSE :: (ASTRep rep, CanBeAliased (Op rep), CSEInOp (OpWithAliases (Op rep))) => Bool -> Pass rep rep -- | Perform CSE on a single function. -- -- If the boolean argument is false, the pass will not perform CSE on -- expressions producing arrays. This should be disabled when the rep has -- memory information, since at that point arrays have identity beyond -- their value. performCSEOnFunDef :: (ASTRep rep, CanBeAliased (Op rep), CSEInOp (OpWithAliases (Op rep))) => Bool -> FunDef rep -> FunDef rep -- | Perform CSE on some statements. -- -- If the boolean argument is false, the pass will not perform CSE on -- expressions producing arrays. This should be disabled when the rep has -- memory information, since at that point arrays have identity beyond -- their value. performCSEOnStms :: (ASTRep rep, CanBeAliased (Op rep), CSEInOp (OpWithAliases (Op rep))) => Bool -> Stms rep -> Stms rep -- | The operations that permit CSE. class CSEInOp op instance Futhark.Optimise.CSE.CSEInOp () instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.Aliased rep, Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Rep.Op rep), Futhark.Optimise.CSE.CSEInOp op) => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.GPU.Op.HostOp rep op) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.Aliased rep, Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Rep.Op rep), Futhark.Optimise.CSE.CSEInOp op) => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.MC.Op.MCOp rep op) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.Aliased rep, Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Rep.Op rep)) => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.SegOp.SegOp lvl rep) instance Futhark.Optimise.CSE.CSEInOp op => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Mem.MemOp op) instance (Futhark.IR.Prop.ASTRep rep, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Rep.Op rep), Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Prop.Aliases.OpWithAliases (Futhark.IR.Rep.Op rep))) => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.SOACS.SOAC.SOAC (Futhark.IR.Aliases.Aliases rep)) -- | This module implements a compiler pass for inlining functions, then -- removing those that have become dead. module Futhark.Optimise.InliningDeadFun -- | Inline all functions and remove the resulting dead functions. inlineAggressively :: Pass SOACS SOACS -- | Inline some functions and remove the resulting dead functions. inlineConservatively :: Pass SOACS SOACS -- | removeDeadFunctions prog removes the functions that are -- unreachable from the main function from the program. removeDeadFunctions :: Pass SOACS SOACS -- | Perform a restricted form of block+register tiling corresponding to -- the following pattern: * a redomap is quasi-perfectly nested inside a -- kernel with at least two parallel dimension (the perfectly nested -- restriction is relaxed a bit to allow for SGEMM); * all streamed -- arrays of redomap are one dimensional; * all streamed arrays are -- variant to exacly one of the two innermost parallel dimensions, and -- conversely for each of the two innermost parallel dimensions, there is -- at least one streamed array variant to it; * the stream's result is a -- tuple of scalar values, which are also the "thread-in-space" return of -- the kernel. * We have further restrictions that in principle can be -- relaxed: the redomap has exactly two array input the redomap produces -- one scalar result the kernel produces one scalar result module Futhark.Optimise.BlkRegTiling mmBlkRegTiling :: Stm GPU -> TileM (Maybe (Stms GPU, Stm GPU)) -- | Expects a kernel statement as argument. CONDITIONS for 3D tiling -- optimization to fire are: 1. a) The kernel body can be broken into -- scalar-code-1 ++ [Redomap stmt] ++ scalar-code-2. b) The kernels has a -- per-thread result, and obviously the result is variant to the 3rd -- dimension (counted from innermost to outermost) 2. For the Redomap: a) -- the streamed arrays are one dimensional b) each of the array arguments -- of Redomap are variant to exactly one of the three innermost-parallel -- dimension of the kernel. This condition can be relaxed by -- interchanging kernel dimensions whenever possible. 3. For -- scalar-code-1: a) each of the statements is a slice that produces one -- of the streamed arrays -- -- mmBlkRegTiling :: Stm GPU -> TileM (Maybe (Stms GPU, Stm GPU)) -- mmBlkRegTiling (Let pat aux (Op (SegOp (SegMap SegThread{} seg_space -- ts old_kbody)))) doRegTiling3D :: Stm GPU -> TileM (Maybe (Stms GPU, Stm GPU)) -- | Perform a restricted form of loop tiling within SegMaps. We only tile -- primitive types, to avoid excessive local memory use. module Futhark.Optimise.TileLoops -- | The pass definition. tileLoops :: Pass GPU GPU instance GHC.Base.Semigroup Futhark.Optimise.TileLoops.PrivStms instance GHC.Base.Monoid Futhark.Optimise.TileLoops.PrivStms module Futhark.IR.GPU.Simplify simplifyGPU :: Prog GPU -> PassM (Prog GPU) simplifyLambda :: (HasScope GPU m, MonadFreshNames m) => Lambda GPU -> m (Lambda GPU) -- | The phantom data type for the kernels representation. data GPU simplifyKernelOp :: (SimplifiableRep rep, BodyDec rep ~ ()) => SimplifyOp rep op -> HostOp rep op -> SimpleM rep (HostOp (Wise rep) (OpWithWisdom op), Stms (Wise rep)) instance Futhark.Builder.BuilderOps (Futhark.Optimise.Simplify.Rep.Wise Futhark.IR.GPU.GPU) instance Futhark.IR.SegOp.HasSegOp (Futhark.Optimise.Simplify.Rep.Wise Futhark.IR.GPU.GPU) instance Futhark.IR.SOACS.Simplify.HasSOAC (Futhark.Optimise.Simplify.Rep.Wise Futhark.IR.GPU.GPU) -- | Sequentialise any remaining SOACs. It is very important that this is -- run *after* any access-pattern-related optimisation, because this pass -- will destroy information. -- -- This pass conceptually contains three subpasses: -- --
-- loop {..., A_mem, ..., A, ...} ... do {
-- ...
-- let A_out_mem = alloc(...) -- stores A_out
-- in {..., A_out_mem, ..., A_out, ...}
-- }
--
--
-- and turns them into
--
--
-- let A_in_mem = alloc(...)
-- let A_out_mem = alloc(...)
-- let A_in = copy A -- in A_in_mem
-- loop {..., A_in_mem, A_out_mem, ..., A=A_in, ...} ... do {
-- ...
-- in {..., A_out_mem, A_mem, ..., A_out, ...}
-- }
--
--
-- The result is essentially "pointer swapping" between the two memory
-- initial blocks A_mem and A_out_mem. The invariant is
-- that the array is always stored in the "first" memory block at the
-- beginning of the loop (and also in the final result). We do need to
-- add an extra element to the pattern, however. The initial copy of
-- A could be elided if A is unique (thus
-- A_in_mem=A_mem). This is because only then is it safe to use
-- A_mem to store loop results. We don't currently do this.
--
-- Unfortunately, not all loops fit the pattern above. In particular, a
-- nested loop that has been transformed as such does not! Therefore we
-- also have another double buffering strategy, that turns
--
--
-- loop {..., A_mem, ..., A, ...} ... do {
-- ...
-- let A_out_mem = alloc(...)
-- -- A in A_out_mem
-- in {..., A_out_mem, ..., A, ...}
-- }
--
--
-- into
--
--
-- let A_res_mem = alloc(...)
-- loop {..., A_mem, ..., A, ...} ... do {
-- ...
-- let A_out_mem = alloc(...)
-- -- A in A_out_mem
-- let A' = copy A
-- -- A' in A_res_mem
-- in {..., A_res_mem, ..., A, ...}
-- }
--
--
-- The allocation of A_out_mem can then be hoisted out because it is dead
-- at the end of the loop. This always works as long as A_out_mem has a
-- loop-invariant allocation size, but requires a copy per iteration (and
-- an initial one, elided above).
module Futhark.Optimise.DoubleBuffer
-- | The pass for GPU kernels.
doubleBufferGPU :: Pass GPUMem GPUMem
-- | The pass for multicore
doubleBufferMC :: Pass MCMem MCMem
instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.Optimise.DoubleBuffer.DoubleBufferM rep)
instance Control.Monad.Reader.Class.MonadReader (Futhark.Optimise.DoubleBuffer.Env rep) (Futhark.Optimise.DoubleBuffer.DoubleBufferM rep)
instance GHC.Base.Monad (Futhark.Optimise.DoubleBuffer.DoubleBufferM rep)
instance GHC.Base.Applicative (Futhark.Optimise.DoubleBuffer.DoubleBufferM rep)
instance GHC.Base.Functor (Futhark.Optimise.DoubleBuffer.DoubleBufferM rep)
instance GHC.Show.Show Futhark.Optimise.DoubleBuffer.DoubleBuffer
instance Futhark.IR.Prop.ASTRep rep => Futhark.IR.Prop.Scope.HasScope rep (Futhark.Optimise.DoubleBuffer.DoubleBufferM rep)
instance Futhark.IR.Prop.ASTRep rep => Futhark.IR.Prop.Scope.LocalScope rep (Futhark.Optimise.DoubleBuffer.DoubleBufferM rep)
-- | Parser for the Futhark core language.
module Futhark.IR.Parse
parseSOACS :: FilePath -> Text -> Either Text (Prog SOACS)
parseGPU :: FilePath -> Text -> Either Text (Prog GPU)
parseGPUMem :: FilePath -> Text -> Either Text (Prog GPUMem)
parseMC :: FilePath -> Text -> Either Text (Prog MC)
parseMCMem :: FilePath -> Text -> Either Text (Prog MCMem)
parseSeq :: FilePath -> Text -> Either Text (Prog Seq)
parseSeqMem :: FilePath -> Text -> Either Text (Prog SeqMem)
-- | Provides last-use analysis for Futhark programs.
module Futhark.Analysis.LastUse
-- | LastUseMap tells which names were last used in a given
-- statement. Statements are uniquely identified by the VName of
-- the first value parameter in the statement pattern. Names is
-- the set of names last used.
type LastUseMap = Map VName Names
-- | Analyses a program to return a last-use map, mapping each simple
-- statement in the program to the values that were last used within that
-- statement, and the set of all VName that were used inside.
analyseProg :: Prog GPUMem -> (LastUseMap, Used)
-- | Interference analysis for Futhark programs.
module Futhark.Analysis.Interference
-- | An interference graph. An element (x, y) in the set means
-- that there is an undirected edge between x and y,
-- and therefore the lifetimes of x and y overlap and
-- they "interfere" with each other. We assume that pairs are always
-- normalized, such that x < y, before inserting.
-- This should prevent any duplicates. We also don't allow any pairs
-- where x == y.
type Graph a = Set (a, a)
-- | Perform interference analysis on the given statements. The result is a
-- triple of the names currently in use, names that hit their last use
-- somewhere within, and the resulting graph.
analyseGPU :: LocalScope GPUMem m => LastUseMap -> Stms GPUMem -> m (Graph VName)
-- | Provides a greedy graph-coloring algorithm.
module Futhark.Optimise.ReuseAllocations.GreedyColoring
-- | Graph coloring that takes into account the space of values.
-- Two values can only share the same color if they live in the same
-- space. The result is map from each color to a space and a map from
-- each value in the input graph to it's new color.
colorGraph :: (Ord a, Ord space) => Map a space -> Graph a -> (Map Int space, Coloring a)
-- | A map of values to their color, identified by an integer.
type Coloring a = Map a Int
-- | This module implements an optimization that tries to statically reuse
-- kernel-level allocations. The goal is to lower the static memory
-- usage, which might allow more programs to run using intra-group
-- parallelism.
module Futhark.Optimise.ReuseAllocations
-- | Perform the reuse-allocations optimization.
optimise :: Pass GPUMem GPUMem
-- | High-level representation of SOACs. When performing
-- SOAC-transformations, operating on normal Exp values is
-- somewhat of a nuisance, as they can represent terms that are not
-- proper SOACs. In contrast, this module exposes a SOAC representation
-- that does not enable invalid representations (except for type errors).
--
-- Furthermore, while standard normalised Futhark requires that the
-- inputs to a SOAC are variables or constants, the representation in
-- this module also supports various index-space transformations, like
-- replicate or rearrange. This is also very convenient
-- when implementing transformations.
--
-- The names exported by this module conflict with the standard Futhark
-- syntax tree constructors, so you are advised to use a qualified
-- import:
--
-- -- import Futhark.Analysis.HORep.SOAC (SOAC) -- import qualified Futhark.Analysis.HORep.SOAC as SOAC --module Futhark.Analysis.HORep.SOAC -- | A definite representation of a SOAC expression. data SOAC rep Stream :: SubExp -> StreamForm rep -> Lambda rep -> [SubExp] -> [Input] -> SOAC rep Scatter :: SubExp -> Lambda rep -> [Input] -> [(Shape, Int, VName)] -> SOAC rep Screma :: SubExp -> ScremaForm rep -> [Input] -> SOAC rep Hist :: SubExp -> [HistOp rep] -> Lambda rep -> [Input] -> SOAC rep -- | The essential parts of a Screma factored out (everything except -- the input arrays). data ScremaForm rep ScremaForm :: [Scan rep] -> [Reduce rep] -> Lambda rep -> ScremaForm rep -- | Returns the inputs used in a SOAC. inputs :: SOAC rep -> [Input] -- | Set the inputs to a SOAC. setInputs :: [Input] -> SOAC rep -> SOAC rep -- | The lambda used in a given SOAC. lambda :: SOAC rep -> Lambda rep -- | Set the lambda used in the SOAC. setLambda :: Lambda rep -> SOAC rep -> SOAC rep -- | The return type of a SOAC. typeOf :: SOAC rep -> [Type] -- | The "width" of a SOAC is the expected outer size of its array inputs -- _after_ input-transforms have been carried out. width :: SOAC rep -> SubExp -- | The reason why some expression cannot be converted to a SOAC -- value. data NotSOAC -- | The expression is not a (tuple-)SOAC at all. NotSOAC :: NotSOAC -- | Either convert an expression to the normalised SOAC representation, or -- a reason why the expression does not have the valid form. fromExp :: (Op rep ~ SOAC rep, HasScope rep m) => Exp rep -> m (Either NotSOAC (SOAC rep)) -- | Convert a SOAC to the corresponding expression. toExp :: (MonadBuilder m, Op (Rep m) ~ SOAC (Rep m)) => SOAC (Rep m) -> m (Exp (Rep m)) -- | Convert a SOAC to a Futhark-level SOAC. toSOAC :: MonadBuilder m => SOAC (Rep m) -> m (SOAC (Rep m)) -- | One array input to a SOAC - a SOAC may have multiple inputs, but all -- are of this form. Only the array inputs are expressed with this type; -- other arguments, such as initial accumulator values, are plain -- expressions. The transforms are done left-to-right, that is, the first -- element of the ArrayTransform list is applied first. data Input Input :: ArrayTransforms -> VName -> Type -> Input -- | Create a plain array variable input with no transformations. varInput :: HasScope t f => VName -> f Input -- | Create a plain array variable input with no transformations, from an -- Ident. identInput :: Ident -> Input -- | If the given input is a plain variable input, with no transforms, -- return the variable. isVarInput :: Input -> Maybe VName -- | If the given input is a plain variable input, with no non-vacuous -- transforms, return the variable. isVarishInput :: Input -> Maybe VName -- | Add a transformation to the end of the transformation list. addTransform :: ArrayTransform -> Input -> Input -- | Add several transformations to the start of the transformation list. addInitialTransforms :: ArrayTransforms -> Input -> Input -- | Return the array name of the input. inputArray :: Input -> VName -- | Return the array rank (dimensionality) of an input. Just a convenient -- alias. inputRank :: Input -> Int -- | Return the type of an input. inputType :: Input -> Type -- | Return the row type of an input. Just a convenient alias. inputRowType :: Input -> Type -- | Apply the transformations to every row of the input. transformRows :: ArrayTransforms -> Input -> Input -- | Add to the input a Rearrange transform that performs an -- (k,n) transposition. The new transform will be at the end of -- the current transformation list. transposeInput :: Int -> Int -> Input -> Input -- | A sequence of array transformations, heavily inspired by -- Data.Seq. You can decompose it using viewf and -- viewl, and grow it by using |> and <|. -- These correspond closely to the similar operations for sequences, -- except that appending will try to normalise and simplify the -- transformation sequence. -- -- The data type is opaque in order to enforce normalisation invariants. -- Basically, when you grow the sequence, the implementation will try to -- coalesce neighboring permutations, for example by composing -- permutations and removing identity transformations. data ArrayTransforms -- | The empty transformation list. noTransforms :: ArrayTransforms -- | Is it an empty transformation list? nullTransforms :: ArrayTransforms -> Bool -- | Add a transform to the end of the transformation list. (|>) :: ArrayTransforms -> ArrayTransform -> ArrayTransforms -- | Add a transform at the beginning of the transformation list. (<|) :: ArrayTransform -> ArrayTransforms -> ArrayTransforms -- | Decompose the input-end of the transformation sequence. viewf :: ArrayTransforms -> ViewF -- | A view of the first transformation to be applied. data ViewF EmptyF :: ViewF (:<) :: ArrayTransform -> ArrayTransforms -> ViewF -- | Decompose the output-end of the transformation sequence. viewl :: ArrayTransforms -> ViewL -- | A view of the last transformation to be applied. data ViewL EmptyL :: ViewL (:>) :: ArrayTransforms -> ArrayTransform -> ViewL -- | A single, simple transformation. If you want several, don't just -- create a list, use ArrayTransforms instead. data ArrayTransform -- | A permutation of an otherwise valid input. Rearrange :: Certs -> [Int] -> ArrayTransform -- | A reshaping of an otherwise valid input. Reshape :: Certs -> ShapeChange SubExp -> ArrayTransform -- | A reshaping of the outer dimension. ReshapeOuter :: Certs -> ShapeChange SubExp -> ArrayTransform -- | A reshaping of everything but the outer dimension. ReshapeInner :: Certs -> ShapeChange SubExp -> ArrayTransform -- | Replicate the rows of the array a number of times. Replicate :: Certs -> Shape -> ArrayTransform -- | Given an expression, determine whether the expression represents an -- input transformation of an array variable. If so, return the variable -- and the transformation. Only Rearrange and Reshape are -- possible to express this way. transformFromExp :: Certs -> Exp rep -> Maybe (VName, ArrayTransform) -- | To-Stream translation of SOACs. Returns the Stream SOAC and the -- extra-accumulator body-result ident if any. soacToStream :: (MonadFreshNames m, Buildable rep, Op rep ~ SOAC rep) => SOAC rep -> m (SOAC rep, [Ident]) instance GHC.Classes.Ord Futhark.Analysis.HORep.SOAC.ArrayTransform instance GHC.Classes.Eq Futhark.Analysis.HORep.SOAC.ArrayTransform instance GHC.Show.Show Futhark.Analysis.HORep.SOAC.ArrayTransform instance GHC.Show.Show Futhark.Analysis.HORep.SOAC.ArrayTransforms instance GHC.Classes.Ord Futhark.Analysis.HORep.SOAC.ArrayTransforms instance GHC.Classes.Eq Futhark.Analysis.HORep.SOAC.ArrayTransforms instance GHC.Classes.Ord Futhark.Analysis.HORep.SOAC.Input instance GHC.Classes.Eq Futhark.Analysis.HORep.SOAC.Input instance GHC.Show.Show Futhark.Analysis.HORep.SOAC.Input instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.Analysis.HORep.SOAC.SOAC rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Classes.Eq (Futhark.Analysis.HORep.SOAC.SOAC rep) instance GHC.Show.Show Futhark.Analysis.HORep.SOAC.NotSOAC instance Futhark.IR.Pretty.PrettyRep rep => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Analysis.HORep.SOAC.SOAC rep) instance Futhark.Transform.Substitute.Substitute Futhark.Analysis.HORep.SOAC.Input instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Analysis.HORep.SOAC.Input instance GHC.Base.Semigroup Futhark.Analysis.HORep.SOAC.ArrayTransforms instance GHC.Base.Monoid Futhark.Analysis.HORep.SOAC.ArrayTransforms instance Futhark.Transform.Substitute.Substitute Futhark.Analysis.HORep.SOAC.ArrayTransforms instance Futhark.Transform.Substitute.Substitute Futhark.Analysis.HORep.SOAC.ArrayTransform -- | Facilities for composing SOAC functions. Mostly intended for use by -- the fusion module, but factored into a separate module for ease of -- testing, debugging and development. Of course, there is nothing -- preventing you from using the exported functions whereever you want. -- -- Important: this module is "dumb" in the sense that it does not check -- the validity of its inputs, and does not have any functionality for -- massaging SOACs to be fusible. It is assumed that the given SOACs are -- immediately compatible. -- -- The module will, however, remove duplicate inputs after fusion. module Futhark.Optimise.Fusion.Composing -- | fuseMaps lam1 inp1 out1 lam2 inp2 fuses the function -- lam1 into lam2. Both functions must be mapping -- functions, although lam2 may have leading reduction -- parameters. inp1 and inp2 are the array inputs to -- the SOACs containing lam1 and lam2 respectively. -- out1 are the identifiers to which the output of the SOAC -- containing lam1 is bound. It is nonsensical to call this -- function unless the intersection of out1 and inp2 is -- non-empty. -- -- If lam2 accepts more parameters than there are elements in -- inp2, it is assumed that the surplus (which are positioned at -- the beginning of the parameter list) are reduction (accumulator) -- parameters, that do not correspond to array elements, and they are -- thus not modified. -- -- The result is the fused function, and a list of the array inputs -- expected by the SOAC containing the fused function. fuseMaps :: Buildable rep => Names -> Lambda rep -> [Input] -> [(VName, Ident)] -> Lambda rep -> [Input] -> (Lambda rep, [Input]) fuseRedomap :: Buildable rep => Names -> [VName] -> Lambda rep -> [SubExp] -> [SubExp] -> [Input] -> [(VName, Ident)] -> Lambda rep -> [SubExp] -> [SubExp] -> [Input] -> (Lambda rep, [Input]) mergeReduceOps :: Lambda rep -> Lambda rep -> Lambda rep module Futhark.Analysis.HORep.MapNest data Nesting rep Nesting :: [VName] -> [VName] -> [Type] -> SubExp -> Nesting rep [nestingParamNames] :: Nesting rep -> [VName] [nestingResult] :: Nesting rep -> [VName] [nestingReturnType] :: Nesting rep -> [Type] [nestingWidth] :: Nesting rep -> SubExp data MapNest rep MapNest :: SubExp -> Lambda rep -> [Nesting rep] -> [Input] -> MapNest rep typeOf :: MapNest rep -> [Type] params :: MapNest rep -> [VName] inputs :: MapNest rep -> [Input] setInputs :: [Input] -> MapNest rep -> MapNest rep fromSOAC :: (Buildable rep, MonadFreshNames m, LocalScope rep m, Op rep ~ SOAC rep) => SOAC rep -> m (Maybe (MapNest rep)) toSOAC :: (MonadFreshNames m, HasScope rep m, Buildable rep, BuilderOps rep, Op rep ~ SOAC rep) => MapNest rep -> m (SOAC rep) instance GHC.Show.Show (Futhark.Analysis.HORep.MapNest.Nesting rep) instance GHC.Classes.Ord (Futhark.Analysis.HORep.MapNest.Nesting rep) instance GHC.Classes.Eq (Futhark.Analysis.HORep.MapNest.Nesting rep) instance Futhark.IR.Rep.RepTypes rep => GHC.Show.Show (Futhark.Analysis.HORep.MapNest.MapNest rep) module Futhark.Optimise.Fusion.LoopKernel data FusedKer FusedKer :: SOAC -> Names -> [VName] -> Names -> Scope SOACS -> ArrayTransforms -> [VName] -> StmAux () -> FusedKer -- | the SOAC expression, e.g., mapT( f(a,b), x, y ) [fsoac] :: FusedKer -> SOAC -- | Variables used in in-place updates in the kernel itself, as well as on -- the path to the kernel from the current position. This is used to -- avoid fusion that would violate in-place restrictions. [inplace] :: FusedKer -> Names -- | whether at least a fusion has been performed. [fusedVars] :: FusedKer -> [VName] -- | The set of variables that were consumed by the SOACs contributing to -- this kernel. Note that, by the type rules, the final SOAC may actually -- consume _more_ than its original contributors, which implies the need -- for Copy expressions. [fusedConsumed] :: FusedKer -> Names -- | The names in scope at the kernel. [kernelScope] :: FusedKer -> Scope SOACS [outputTransform] :: FusedKer -> ArrayTransforms [outNames] :: FusedKer -> [VName] [kerAux] :: FusedKer -> StmAux () newKernel :: StmAux () -> SOAC -> Names -> [VName] -> Scope SOACS -> FusedKer inputs :: FusedKer -> [Input] setInputs :: [Input] -> FusedKer -> FusedKer arrInputs :: FusedKer -> Set VName transformOutput :: ArrayTransforms -> [VName] -> [Ident] -> Builder SOACS () attemptFusion :: MonadFreshNames m => Names -> [VName] -> SOAC -> Names -> FusedKer -> m (Maybe FusedKer) type SOAC = SOAC SOACS type MapNest = MapNest SOACS instance Futhark.IR.Prop.Scope.LocalScope Futhark.IR.SOACS.SOACS Futhark.Optimise.Fusion.LoopKernel.TryFusion instance Futhark.IR.Prop.Scope.HasScope Futhark.IR.SOACS.SOACS Futhark.Optimise.Fusion.LoopKernel.TryFusion instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Optimise.Fusion.LoopKernel.TryFusion instance Control.Monad.Fail.MonadFail Futhark.Optimise.Fusion.LoopKernel.TryFusion instance GHC.Base.Monad Futhark.Optimise.Fusion.LoopKernel.TryFusion instance GHC.Base.Alternative Futhark.Optimise.Fusion.LoopKernel.TryFusion instance GHC.Base.Applicative Futhark.Optimise.Fusion.LoopKernel.TryFusion instance GHC.Base.Functor Futhark.Optimise.Fusion.LoopKernel.TryFusion instance GHC.Show.Show Futhark.Optimise.Fusion.LoopKernel.FusedKer -- | Perform horizontal and vertical fusion of SOACs. See the paper A T2 -- Graph-Reduction Approach To Fusion for the basic idea (some -- extensions discussed in /Design and GPGPU Performance of Futhark’s -- Redomap Construct/). module Futhark.Optimise.Fusion -- | The pass definition. fuseSOACs :: Pass SOACS SOACS instance GHC.Show.Show Futhark.Optimise.Fusion.KernName instance GHC.Classes.Ord Futhark.Optimise.Fusion.KernName instance GHC.Classes.Eq Futhark.Optimise.Fusion.KernName instance Control.Monad.Reader.Class.MonadReader Futhark.Optimise.Fusion.FusionGEnv Futhark.Optimise.Fusion.FusionGM instance Control.Monad.State.Class.MonadState Futhark.FreshNames.VNameSource Futhark.Optimise.Fusion.FusionGM instance Control.Monad.Error.Class.MonadError Futhark.Optimise.Fusion.Error Futhark.Optimise.Fusion.FusionGM instance GHC.Base.Functor Futhark.Optimise.Fusion.FusionGM instance GHC.Base.Applicative Futhark.Optimise.Fusion.FusionGM instance GHC.Base.Monad Futhark.Optimise.Fusion.FusionGM instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Optimise.Fusion.FusionGM instance Futhark.IR.Prop.Scope.HasScope Futhark.IR.SOACS.SOACS Futhark.Optimise.Fusion.FusionGM instance GHC.Base.Semigroup Futhark.Optimise.Fusion.FusedRes instance GHC.Base.Monoid Futhark.Optimise.Fusion.FusedRes instance GHC.Show.Show Futhark.Optimise.Fusion.Error -- | Optimisation pipelines. module Futhark.Passes standardPipeline :: Pipeline SOACS SOACS sequentialPipeline :: Pipeline SOACS Seq kernelsPipeline :: Pipeline SOACS GPU sequentialCpuPipeline :: Pipeline SOACS SeqMem gpuPipeline :: Pipeline SOACS GPUMem mcPipeline :: Pipeline SOACS MC multicorePipeline :: Pipeline SOACS MCMem -- | Imperative intermediate language used as a stepping stone in code -- generation. -- -- This is a generic representation parametrised on an extensible -- arbitrary operation. -- -- Originally inspired by the paper "Defunctionalizing Push Arrays" (FHPC -- '14). module Futhark.CodeGen.ImpCode -- | A collection of imperative functions and constants. data Definitions a Definitions :: Constants a -> Functions a -> Definitions a [defConsts] :: Definitions a -> Constants a [defFuns] :: Definitions a -> Functions a -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a -- | Type alias for namespace control. type Function = FunctionT -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Maybe Name -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a [functionEntry] :: FunctionT a -> Maybe Name [functionOutput] :: FunctionT a -> [Param] [functionInput] :: FunctionT a -> [Param] [functionBody] :: FunctionT a -> Code a [functionResult] :: FunctionT a -> [ExternalValue] [functionArgs] :: FunctionT a -> [ExternalValue] -- | A collection of imperative constants. data Constants a Constants :: [Param] -> Code a -> Constants a -- | The constants that are made available to the functions. [constsDecl] :: Constants a -> [Param] -- | Setting the value of the constants. Note that this must not contain -- declarations of the names defined in constsDecl. [constsInit] :: Constants a -> Code a -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block memory space, element type, signedness of -- element type (if applicable), and shape. ArrayValue :: VName -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc -- | Since the core language does not care for signedness, but the source -- language does, entry point input/output information has metadata for -- integer types (and arrays containing these) that indicate whether they -- are really unsigned integers. data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. We record the uniqueness because it is important to the -- external interface as well. data ExternalValue -- | The string is a human-readable description with no other semantics. -- not matter. OpaqueValue :: Uniqueness -> String -> [ValueDesc] -> ExternalValue TransparentValue :: Uniqueness -> ValueDesc -> ExternalValue -- | An ImpCode function parameter. data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param -- | The name of a parameter. paramName :: Param -> VName -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | The size of a memory block. type MemSize = SubExp -- | The size of an array. type DimSize = SubExp -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceId depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A special kind of memory that is a statically sized array of some -- primitive type. Used for private memory on GPUs. ScalarSpace :: [SubExp] -> PrimType -> Space -- | A string representing a specific non-default memory space. type SpaceId = String -- | A block of imperative code. Parameterised by an Op, which -- allows extensibility. Concrete uses of this type will instantiate the -- type parameter with e.g. a construct for launching GPU kernels. data Code a -- | No-op. Crucial for the Monoid instance. Skip :: Code a -- | Statement composition. Crucial for the Semigroup instance. (:>>:) :: Code a -> Code a -> Code a -- | A for-loop iterating the given number of times. The loop parameter -- starts counting from zero and will have the same (integer) type as the -- bound. The bound is evaluated just once, before the loop is entered. For :: VName -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. While :: TExp Bool -> Code a -> Code a -- | Declare a memory block variable that will point to memory in the given -- memory space. Note that this is distinct from allocation. The memory -- block must be the target of either an Allocate or a -- SetMem before it can be used for reading or writing. DeclareMem :: VName -> Space -> Code a -- | Declare a scalar variable with an initially undefined value. DeclareScalar :: VName -> Volatility -> PrimType -> Code a -- | Create an array containing the given values. The lifetime of the array -- will be the entire application. This is mostly used for constant -- arrays, but also for some bookkeeping data, like the synchronisation -- counts used to implement reduction. DeclareArray :: VName -> Space -> PrimType -> ArrayContents -> Code a -- | Memory space must match the corresponding DeclareMem. Allocate :: VName -> Count Bytes (TExp Int64) -> Space -> Code a -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. Free :: VName -> Space -> Code a -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. Copy :: VName -> Count Bytes (TExp Int64) -> Space -> VName -> Count Bytes (TExp Int64) -> Space -> Count Bytes (TExp Int64) -> Code a -- | Write mem i t space vol v writes the value v to -- mem offset by i elements of type t. The -- Space argument is the memory space of mem (technically -- redundant, but convenient). Note that reading is done with an -- Exp (Index). Write :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -> Code a -- | Set a scalar variable. SetScalar :: VName -> Exp -> Code a -- | Must be in same space. SetMem :: VName -> VName -> Space -> Code a -- | Function call. The results are written to the provided VName -- variables. Call :: [VName] -> Name -> [Arg] -> Code a -- | Conditional execution. If :: TExp Bool -> Code a -> Code a -> Code a -- | Assert that something must be true. Should it turn out not to be true, -- then report a failure along with the given error message. Assert :: Exp -> ErrorMsg Exp -> (SrcLoc, [SrcLoc]) -> Code a -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. Comment :: String -> Code a -> Code a -- | Print the given value to the screen, somehow annotated with the given -- string as a description. If no type/value pair, just print the string. -- This has no semantic meaning, but is used entirely for debugging. Code -- generators are free to ignore this statement. DebugPrint :: String -> Maybe Exp -> Code a -- | Log the given message, *without* a trailing linebreak (unless part of -- the mssage). TracePrint :: ErrorMsg Exp -> Code a -- | Perform an extensible operation. Op :: a -> Code a -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type Unit. UnitValue :: PrimValue -- | The leaves of an Exp. data ExpLeaf -- | A scalar variable. The type is stored in the LeafExp -- constructor itself. ScalarVar :: VName -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> ExpLeaf -- | A side-effect free expression whose execution will produce a single -- primitive value. type Exp = PrimExp ExpLeaf -- | Like Exp, but with a required/known type. type TExp t = TPrimExp t ExpLeaf -- | The volatility of a memory access or variable. Feel free to ignore -- this for backends where it makes no sense (anything but C and similar -- low-level things) data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg -- | Turn a VName into a ScalarVar. var :: VName -> PrimType -> Exp -- | Turn a VName into a Int32 ScalarVar. vi32 :: VName -> TExp Int32 -- | Turn a VName into a Int64 ScalarVar. vi64 :: VName -> TExp Int64 -- | Concise wrapper for using Index. index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time value. ErrorVal :: PrimType -> a -> ErrorMsgPart a -- | How many non-constant parts does the error message have, and what is -- their type? errorMsgArgTypes :: ErrorMsg a -> [PrimType] -- | The contents of a statically declared constant array. Such arrays are -- always unidimensional, and reshaped if necessary in the code that uses -- them. data ArrayContents -- | Precisely these values. ArrayValues :: [PrimValue] -> ArrayContents -- | This many zeroes. ArrayZeros :: Int -> ArrayContents -- | The names declared with DeclareMem, DeclareScalar, and -- DeclareArray in the given code. declaredIn :: Code a -> Names -- | Find those memory blocks that are used only lexically. That is, are -- not used as the source or target of a SetMem, or are the result -- of the function, nor passed as arguments to other functions. This is -- interesting because such memory blocks do not need reference counting, -- but can be managed in a purely stack-like fashion. -- -- We do not look inside any Ops. We assume that no Op is -- going to SetMem a memory block declared outside it. lexicalMemoryUsage :: Function a -> Map VName Space -- | The set of functions that are called by this code. Assumes there are -- no function calls in Ops. calledFuncs :: Code a -> Set Name -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements -- | This expression counts elements. elements :: a -> Count Elements a -- | This expression counts bytes. bytes :: a -> Count Bytes a -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements (TExp Int64) -> PrimType -> Count Bytes (TExp Int64) -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | A wrapper supporting a phantom type for indicating what we are -- counting. newtype Count u e Count :: e -> Count u e [unCount] :: Count u e -> e instance GHC.Show.Show Futhark.CodeGen.ImpCode.Param instance GHC.Show.Show Futhark.CodeGen.ImpCode.Signedness instance GHC.Classes.Ord Futhark.CodeGen.ImpCode.Signedness instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Signedness instance GHC.Show.Show Futhark.CodeGen.ImpCode.ValueDesc instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.ValueDesc instance GHC.Show.Show Futhark.CodeGen.ImpCode.ExternalValue instance GHC.Show.Show Futhark.CodeGen.ImpCode.ArrayContents instance GHC.Show.Show Futhark.CodeGen.ImpCode.Volatility instance GHC.Classes.Ord Futhark.CodeGen.ImpCode.Volatility instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Volatility instance GHC.Show.Show Futhark.CodeGen.ImpCode.ExpLeaf instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.ExpLeaf instance GHC.Show.Show Futhark.CodeGen.ImpCode.Arg instance GHC.Show.Show a => GHC.Show.Show (Futhark.CodeGen.ImpCode.Code a) instance GHC.Show.Show a => GHC.Show.Show (Futhark.CodeGen.ImpCode.FunctionT a) instance GHC.Show.Show a => GHC.Show.Show (Futhark.CodeGen.ImpCode.Functions a) instance GHC.Show.Show a => GHC.Show.Show (Futhark.CodeGen.ImpCode.Constants a) instance GHC.Show.Show a => GHC.Show.Show (Futhark.CodeGen.ImpCode.Definitions a) instance GHC.Base.Functor Futhark.CodeGen.ImpCode.Definitions instance Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.Definitions op) instance GHC.Base.Functor Futhark.CodeGen.ImpCode.Constants instance Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.Constants op) instance GHC.Base.Semigroup (Futhark.CodeGen.ImpCode.Functions a) instance GHC.Base.Monoid (Futhark.CodeGen.ImpCode.Functions a) instance Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.Functions op) instance GHC.Base.Functor Futhark.CodeGen.ImpCode.Functions instance Data.Foldable.Foldable Futhark.CodeGen.ImpCode.Functions instance Data.Traversable.Traversable Futhark.CodeGen.ImpCode.Functions instance Futhark.IR.Prop.Names.FreeIn a => Futhark.IR.Prop.Names.FreeIn (Futhark.CodeGen.ImpCode.Functions a) instance Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.FunctionT op) instance GHC.Base.Functor Futhark.CodeGen.ImpCode.FunctionT instance Data.Foldable.Foldable Futhark.CodeGen.ImpCode.FunctionT instance Data.Traversable.Traversable Futhark.CodeGen.ImpCode.FunctionT instance GHC.Base.Semigroup (Futhark.CodeGen.ImpCode.Code a) instance GHC.Base.Monoid (Futhark.CodeGen.ImpCode.Code a) instance Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.Code op) instance GHC.Base.Functor Futhark.CodeGen.ImpCode.Code instance Data.Foldable.Foldable Futhark.CodeGen.ImpCode.Code instance Data.Traversable.Traversable Futhark.CodeGen.ImpCode.Code instance Futhark.IR.Prop.Names.FreeIn a => Futhark.IR.Prop.Names.FreeIn (Futhark.CodeGen.ImpCode.Code a) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Arg instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Arg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.ExpLeaf instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.ExpLeaf instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.ArrayContents instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.ExternalValue instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.ExternalValue instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.ValueDesc instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.ValueDesc instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Param -- | Change DefaultSpace in a program to some other memory space. -- This is needed because the GPU backends use DefaultSpace to -- refer to GPU memory for most of the pipeline, but final code -- generation assumes that DefaultSpace is CPU memory. module Futhark.CodeGen.SetDefaultSpace -- | Set all uses of DefaultSpace in the given definitions to -- another memory space. setDefaultSpace :: Space -> Definitions op -> Definitions op -- | Like setDefaultSpace, but for Code. setDefaultCodeSpace :: Space -> Code op -> Code op -- | A cache-oblivious sequential transposition for CPU execution. -- Generates a recursive function. module Futhark.CodeGen.ImpGen.Transpose -- | We need to know the name of the function we are generating, as this -- function is recursive. mapTransposeFunction :: Name -> PrimType -> Function op -- | Take well-typed arguments to the transpose function and produce the -- actual argument list. transposeArgs :: PrimType -> VName -> Count Bytes (TExp Int64) -> VName -> Count Bytes (TExp Int64) -> TExp Int64 -> TExp Int64 -> TExp Int64 -> [Arg] -- | Sequential imperative code. module Futhark.CodeGen.ImpCode.Sequential -- | An imperative program. type Program = Definitions Sequential -- | An imperative function. type Function = Function Sequential -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Maybe Name -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a -- | A piece of imperative code. type Code = Code Sequential -- | Phantom type for identifying sequential imperative code. data Sequential -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 data Half -- | The SrcLoc of a Located value. srclocOf :: Located a => a -> SrcLoc -- | Location type, consisting of a beginning position and an end position. data Loc -- | Source location type. Source location are all equal, which allows AST -- nodes to be compared modulo location information. data SrcLoc -- | Located values have a location. class Located a locOf :: Located a => a -> Loc locOfList :: Located a => [a] -> Loc -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they always return a -- boolean value. The somewhat ugly constructor names are straight out of -- LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> Overflow -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> Overflow -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> Overflow -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> Safety -> BinOp -- | Unsigned integer division. Rounds towards positive infinity. UDivUp :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards positive infinity. SDivUp :: IntType -> Safety -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Floating-point modulus. FMod :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> Safety -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM and integer division in C. SQuot :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM and integer modulo in C. SRem :: IntType -> Safety -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. -- -- For operations like integer division, a safe division will not explode -- the computer in case of division by zero, but instead return some -- unspecified value. This always involves a run-time check, so generally -- the unsafe variant is what the compiler will insert, but guarded by an -- explicit assertion elsewhere. Safe operations are useful when the -- optimiser wants to move e.g. a division to a location where the -- divisor may be zero, but where the result will only be used when it is -- non-zero (so it doesn't matter what result is provided with a zero -- divisor, as long as the program keeps running). data Safety Unsafe :: Safety Safe :: Safety -- | What to do in case of arithmetic overflow. Futhark's semantics are -- that overflow does wraparound, but for generated code (like address -- arithmetic), it can be beneficial for overflow to be undefined -- behaviour, as it allows better optimisation of things such as GPU -- kernels. -- -- Note that all values of this type are considered equal for Eq -- and Ord. data Overflow OverflowWrap :: Overflow OverflowUndef :: Overflow -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Floating-point sign function. FSignum :: FloatType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type Unit. UnitValue :: PrimValue -- | A floating-point value. data FloatValue Float16Value :: !Half -> FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType -- | An informationless type - still takes up space! Unit :: PrimType -- | A floating point type. data FloatType Float16 :: FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue -- | The type of an integer value. intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue -- | The type of a floating-point value. floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] -- | Apply an UnOp to an operand. Returns Nothing if the -- application is mistyped. doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue -- | Apply a BinOp to an operand. Returns Nothing if the -- application is mistyped, or outside the domain (e.g. division by -- zero). doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue -- | Apply a ConvOp to an operand. Returns Nothing if the -- application is mistyped. doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Turn the conversion the other way around. Note that most conversions -- are lossy, so there is no guarantee the value will round-trip. flipConvOp :: ConvOp -> ConvOp -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue -- | Apply a CmpOp to an operand. Returns Nothing if the -- application is mistyped. doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to Int64. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | Is the given integer value kind of zero? zeroIshInt :: IntValue -> Bool -- | Is the given integer value kind of one? oneIshInt :: IntValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | The size of a value of a given integer type in eight-bit bytes. intByteSize :: Num a => IntType -> a -- | The size of a value of a given floating-point type in eight-bit bytes. floatByteSize :: Num a => FloatType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool -- | The human-readable name for a ConvOp. This is used to expose -- the ConvOp in the intrinsics module of a Futhark -- program. convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. This follows the GNU coding -- standards for error messages: -- https://www.gnu.org/prep/standards/html_node/Errors.html -- -- This function assumes that both start and end position is in the same -- file (it is not clear what the alternative would even mean). locStr :: Located a => a -> String -- | Like locStr, but locStrRel prev now prints the -- location now with the file name left out if the same as -- prev. This is useful when printing messages that are all in -- the context of some initially printed location (e.g. the first mention -- contains the file name; the rest just line and column name). locStrRel :: (Located a, Located b) => a -> b -> String -- | Given a list of strings representing entries in the stack trace and -- the index of the frame to highlight, produce a final -- newline-terminated string for showing to the user. This string should -- also be preceded by a newline. The most recent stack frame must come -- first in the list. prettyStacktrace :: Int -> [String] -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | Enclose a string in the prefered quotes used in error messages. These -- are picked to not collide with characters permitted in identifiers. quote :: String -> String -- | As quote, but works on prettyprinted representation. pquote :: Doc -> Doc -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time value. ErrorVal :: PrimType -> a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceId depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A special kind of memory that is a statically sized array of some -- primitive type. Used for private memory on GPUs. ScalarSpace :: [SubExp] -> PrimType -> Space -- | How many non-constant parts does the error message have, and what is -- their type? errorMsgArgTypes :: ErrorMsg a -> [PrimType] -- | Either return precomputed free names stored in the attribute, or the -- freshly computed names. Relies on lazy evaluation to avoid the work. class FreeIn dec => FreeDec dec precomputed :: FreeDec dec => dec -> FV -> FV -- | A class indicating that we can obtain free variable information from -- values of this type. class FreeIn a freeIn' :: FreeIn a => a -> FV -- | A computation to build a free variable set. data FV -- | A set of names. Note that the Ord instance is a dummy that -- treats everything as EQ if ==, and otherwise LT. data Names -- | Retrieve the data structure underlying the names representation. namesIntMap :: Names -> IntMap VName -- | Does the set of names contain this name? nameIn :: VName -> Names -> Bool -- | Construct a name set from a list. Slow. namesFromList :: [VName] -> Names -- | Turn a name set into a list of names. Slow. namesToList :: Names -> [VName] -- | Construct a name set from a single name. oneName :: VName -> Names -- | The intersection of two name sets. namesIntersection :: Names -> Names -> Names -- | Do the two name sets intersect? namesIntersect :: Names -> Names -> Bool -- | Subtract the latter name set from the former. namesSubtract :: Names -> Names -> Names -- | Map over the names in a set. mapNames :: (VName -> VName) -> Names -> Names -- | Consider a variable to be bound in the given FV computation. fvBind :: Names -> FV -> FV -- | Take note of a variable reference. fvName :: VName -> FV -- | Take note of a set of variable references. fvNames :: Names -> FV -- | Return the set of variable names that are free in the given statements -- and result. Filters away the names that are bound by the statements. freeInStmsAndRes :: (FreeIn (Op rep), FreeIn (LetDec rep), FreeIn (LParamInfo rep), FreeIn (FParamInfo rep), FreeDec (BodyDec rep), FreeIn (RetType rep), FreeIn (BranchType rep), FreeDec (ExpDec rep)) => Stms rep -> Result -> FV -- | The free variables of some syntactic construct. freeIn :: FreeIn a => a -> Names -- | The names bound by the bindings immediately in a Body. boundInBody :: Body rep -> Names -- | The names bound by a binding. boundByStm :: Stm rep -> Names -- | The names bound by the bindings. boundByStms :: Stms rep -> Names -- | The names of the lambda parameters plus the index parameter. boundByLambda :: Lambda rep -> [VName] -- | The class of floating-point types that can be used for constructing -- TPrimExps. class NumExp t => FloatExp t -- | Construct a typed expression from a rational. fromRational' :: FloatExp t => Rational -> TPrimExp t v -- | The class of integer types that can be used for constructing -- TPrimExps. class NumExp t => IntExp t -- | The class of numeric types that can be used for constructing -- TPrimExps. class NumExp t -- | Construct a typed expression from an integer. fromInteger' :: NumExp t => Integer -> TPrimExp t v -- | Construct a numeric expression from a boolean expression. This can be -- used to encode arithmetic control flow. fromBoolExp :: NumExp t => TPrimExp Bool v -> TPrimExp t v -- | A PrimExp tagged with a phantom type used to provide type-safe -- construction. Does not guarantee that the underlying expression is -- actually type correct. newtype TPrimExp t v TPrimExp :: PrimExp v -> TPrimExp t v [untyped] :: TPrimExp t v -> PrimExp v -- | A primitive expression parametrised over the representation of free -- variables. Note that the Functor, Traversable, and -- Num instances perform automatic (but simple) constant folding. -- -- Note also that the Num instance assumes OverflowUndef -- semantics! data PrimExp v LeafExp :: v -> PrimType -> PrimExp v ValueExp :: PrimValue -> PrimExp v BinOpExp :: BinOp -> PrimExp v -> PrimExp v -> PrimExp v CmpOpExp :: CmpOp -> PrimExp v -> PrimExp v -> PrimExp v UnOpExp :: UnOp -> PrimExp v -> PrimExp v ConvOpExp :: ConvOp -> PrimExp v -> PrimExp v FunExp :: String -> [PrimExp v] -> PrimType -> PrimExp v -- | This expression is of type Int8. isInt8 :: PrimExp v -> TPrimExp Int8 v -- | This expression is of type Int16. isInt16 :: PrimExp v -> TPrimExp Int16 v -- | This expression is of type Int32. isInt32 :: PrimExp v -> TPrimExp Int32 v -- | This expression is of type Int64. isInt64 :: PrimExp v -> TPrimExp Int64 v -- | This is a boolean expression. isBool :: PrimExp v -> TPrimExp Bool v -- | This expression is of type Half. isF16 :: PrimExp v -> TPrimExp Half v -- | This expression is of type Float. isF32 :: PrimExp v -> TPrimExp Float v -- | This expression is of type Double. isF64 :: PrimExp v -> TPrimExp Double v -- | True if the PrimExp has at least this many nodes. This can be -- much more efficient than comparing with length for large -- PrimExps, as this function is lazy. primExpSizeAtLeast :: Int -> PrimExp v -> Bool -- | Perform quick and dirty constant folding on the top level of a -- PrimExp. This is necessary because we want to consider e.g. equality -- modulo constant folding. constFoldPrimExp :: PrimExp v -> PrimExp v -- | Lifted logical conjunction. (.&&.) :: TPrimExp Bool v -> TPrimExp Bool v -> TPrimExp Bool v infixr 3 .&&. -- | Lifted logical conjunction. (.||.) :: TPrimExp Bool v -> TPrimExp Bool v -> TPrimExp Bool v infixr 2 .||. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .<. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<=.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .<=. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.==.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .==. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .>. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>=.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .>=. -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.&.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.|.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.^.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.>>.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.<<.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Untyped smart constructor for sign extension that does a bit of -- constant folding. sExt :: IntType -> PrimExp v -> PrimExp v -- | Untyped smart constructor for zero extension that does a bit of -- constant folding. zExt :: IntType -> PrimExp v -> PrimExp v -- | Evaluate a PrimExp in the given monad. Invokes fail on -- type errors. evalPrimExp :: (Pretty v, MonadFail m) => (v -> m PrimValue) -> PrimExp v -> m PrimValue -- | The type of values returned by a PrimExp. This function -- returning does not imply that the PrimExp is type-correct. primExpType :: PrimExp v -> PrimType -- | If the given PrimExp is a constant of the wrong integer type, -- coerce it to the given integer type. This is a workaround for an issue -- in the Num instance. coerceIntPrimExp :: IntType -> PrimExp v -> PrimExp v -- | Boolean-valued PrimExps. true :: TPrimExp Bool v -- | Boolean-valued PrimExps. false :: TPrimExp Bool v -- | Boolean negation smart constructor. bNot :: TPrimExp Bool v -> TPrimExp Bool v -- | SMax on 32-bit integers. sMax32 :: TPrimExp Int32 v -> TPrimExp Int32 v -> TPrimExp Int32 v -- | SMin on 32-bit integers. sMin32 :: TPrimExp Int32 v -> TPrimExp Int32 v -> TPrimExp Int32 v -- | SMax on 64-bit integers. sMax64 :: TPrimExp Int64 v -> TPrimExp Int64 v -> TPrimExp Int64 v -- | SMin on 64-bit integers. sMin64 :: TPrimExp Int64 v -> TPrimExp Int64 v -> TPrimExp Int64 v -- | Sign-extend to 32 bit integer. sExt32 :: IntExp t => TPrimExp t v -> TPrimExp Int32 v -- | Sign-extend to 64 bit integer. sExt64 :: IntExp t => TPrimExp t v -> TPrimExp Int64 v -- | Zero-extend to 32 bit integer. zExt32 :: IntExp t => TPrimExp t v -> TPrimExp Int32 v -- | Zero-extend to 64 bit integer. zExt64 :: IntExp t => TPrimExp t v -> TPrimExp Int64 v -- | 64-bit float minimum. fMin64 :: TPrimExp Double v -> TPrimExp Double v -> TPrimExp Double v -- | 64-bit float maximum. fMax64 :: TPrimExp Double v -> TPrimExp Double v -> TPrimExp Double v -- | Produce a mapping from the leaves of the PrimExp to their -- designated types. leafExpTypes :: Ord a => PrimExp a -> Set (a, PrimType) -- | A wrapper supporting a phantom type for indicating what we are -- counting. newtype Count u e Count :: e -> Count u e [unCount] :: Count u e -> e -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg -- | Like Exp, but with a required/known type. type TExp t = TPrimExp t ExpLeaf -- | A side-effect free expression whose execution will produce a single -- primitive value. type Exp = PrimExp ExpLeaf -- | The leaves of an Exp. data ExpLeaf -- | A scalar variable. The type is stored in the LeafExp -- constructor itself. ScalarVar :: VName -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> ExpLeaf -- | The volatility of a memory access or variable. Feel free to ignore -- this for backends where it makes no sense (anything but C and similar -- low-level things) data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | Log the given message, *without* a trailing linebreak (unless part of -- the mssage). pattern TracePrint :: () => ErrorMsg Exp -> Code a -- | Print the given value to the screen, somehow annotated with the given -- string as a description. If no type/value pair, just print the string. -- This has no semantic meaning, but is used entirely for debugging. Code -- generators are free to ignore this statement. pattern DebugPrint :: () => String -> Maybe Exp -> Code a -- | Must be in same space. pattern SetMem :: () => VName -> VName -> Space -> Code a -- | Set a scalar variable. pattern SetScalar :: () => VName -> Exp -> Code a -- | Create an array containing the given values. The lifetime of the array -- will be the entire application. This is mostly used for constant -- arrays, but also for some bookkeeping data, like the synchronisation -- counts used to implement reduction. pattern DeclareArray :: () => VName -> Space -> PrimType -> ArrayContents -> Code a -- | Declare a scalar variable with an initially undefined value. pattern DeclareScalar :: () => VName -> Volatility -> PrimType -> Code a -- | Declare a memory block variable that will point to memory in the given -- memory space. Note that this is distinct from allocation. The memory -- block must be the target of either an Allocate or a -- SetMem before it can be used for reading or writing. pattern DeclareMem :: () => VName -> Space -> Code a -- | Statement composition. Crucial for the Semigroup instance. pattern (:>>:) :: () => Code a -> Code a -> Code a -- | Assert that something must be true. Should it turn out not to be true, -- then report a failure along with the given error message. pattern Assert :: () => Exp -> ErrorMsg Exp -> (SrcLoc, [SrcLoc]) -> Code a -- | Function call. The results are written to the provided VName -- variables. pattern Call :: () => [VName] -> Name -> [Arg] -> Code a -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. pattern Copy :: () => VName -> Count Bytes (TExp Int64) -> Space -> VName -> Count Bytes (TExp Int64) -> Space -> Count Bytes (TExp Int64) -> Code a -- | Memory space must match the corresponding DeclareMem. pattern Allocate :: () => VName -> Count Bytes (TExp Int64) -> Space -> Code a -- | No-op. Crucial for the Monoid instance. pattern Skip :: () => Code a -- | A for-loop iterating the given number of times. The loop parameter -- starts counting from zero and will have the same (integer) type as the -- bound. The bound is evaluated just once, before the loop is entered. pattern For :: () => VName -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. pattern While :: () => TExp Bool -> Code a -> Code a -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. pattern Free :: () => VName -> Space -> Code a -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. pattern Comment :: () => String -> Code a -> Code a -- | Write mem i t space vol v writes the value v to -- mem offset by i elements of type t. The -- Space argument is the memory space of mem (technically -- redundant, but convenient). Note that reading is done with an -- Exp (Index). pattern Write :: () => VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -> Code a -- | Conditional execution. pattern If :: () => TExp Bool -> Code a -> Code a -> Code a -- | Perform an extensible operation. pattern Op :: () => a -> Code a -- | The contents of a statically declared constant array. Such arrays are -- always unidimensional, and reshaped if necessary in the code that uses -- them. data ArrayContents -- | Precisely these values. ArrayValues :: [PrimValue] -> ArrayContents -- | This many zeroes. ArrayZeros :: Int -> ArrayContents -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. We record the uniqueness because it is important to the -- external interface as well. data ExternalValue -- | The string is a human-readable description with no other semantics. -- not matter. OpaqueValue :: Uniqueness -> String -> [ValueDesc] -> ExternalValue TransparentValue :: Uniqueness -> ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block memory space, element type, signedness of -- element type (if applicable), and shape. ArrayValue :: VName -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc -- | Since the core language does not care for signedness, but the source -- language does, entry point input/output information has metadata for -- integer types (and arrays containing these) that indicate whether they -- are really unsigned integers. data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | A collection of imperative constants. data Constants a Constants :: [Param] -> Code a -> Constants a -- | The constants that are made available to the functions. [constsDecl] :: Constants a -> [Param] -- | Setting the value of the constants. Note that this must not contain -- declarations of the names defined in constsDecl. [constsInit] :: Constants a -> Code a -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a -- | A collection of imperative functions and constants. data Definitions a Definitions :: Constants a -> Functions a -> Definitions a [defConsts] :: Definitions a -> Constants a [defFuns] :: Definitions a -> Functions a -- | An ImpCode function parameter. data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param -- | The size of an array. type DimSize = SubExp -- | The size of a memory block. type MemSize = SubExp -- | The name of a parameter. paramName :: Param -> VName -- | Find those memory blocks that are used only lexically. That is, are -- not used as the source or target of a SetMem, or are the result -- of the function, nor passed as arguments to other functions. This is -- interesting because such memory blocks do not need reference counting, -- but can be managed in a purely stack-like fashion. -- -- We do not look inside any Ops. We assume that no Op is -- going to SetMem a memory block declared outside it. lexicalMemoryUsage :: Function a -> Map VName Space -- | The set of functions that are called by this code. Assumes there are -- no function calls in Ops. calledFuncs :: Code a -> Set Name -- | This expression counts elements. elements :: a -> Count Elements a -- | This expression counts bytes. bytes :: a -> Count Bytes a -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements (TExp Int64) -> PrimType -> Count Bytes (TExp Int64) -- | Turn a VName into a ScalarVar. var :: VName -> PrimType -> Exp -- | Turn a VName into a Int32 ScalarVar. vi32 :: VName -> TExp Int32 -- | Turn a VName into a Int64 ScalarVar. vi64 :: VName -> TExp Int64 -- | Concise wrapper for using Index. index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -- | The names declared with DeclareMem, DeclareScalar, and -- DeclareArray in the given code. declaredIn :: Code a -> Names instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Sequential.Sequential instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Sequential.Sequential -- | Imperative code with an OpenCL component. -- -- Apart from ordinary imperative code, this also carries around an -- OpenCL program as a string, as well as a list of kernels defined by -- the OpenCL program. -- -- The imperative code has been augmented with a LaunchKernel -- operation that allows one to execute an OpenCL kernel. module Futhark.CodeGen.ImpCode.OpenCL -- | An program calling OpenCL kernels. data Program Program :: Text -> Text -> Map KernelName KernelSafety -> [PrimType] -> Map Name SizeClass -> [FailureMsg] -> Definitions OpenCL -> Program [openClProgram] :: Program -> Text -- | Must be prepended to the program. [openClPrelude] :: Program -> Text [openClKernelNames] :: Program -> Map KernelName KernelSafety -- | So we can detect whether the device is capable. [openClUsedTypes] :: Program -> [PrimType] -- | Runtime-configurable constants. [openClSizes] :: Program -> Map Name SizeClass -- | Assertion failure error messages. [openClFailures] :: Program -> [FailureMsg] [hostDefinitions] :: Program -> Definitions OpenCL -- | A function calling OpenCL kernels. type Function = Function OpenCL -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Maybe Name -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a -- | A piece of code calling OpenCL. type Code = Code OpenCL -- | The name of a kernel. type KernelName = Name -- | An argument to be passed to a kernel. data KernelArg -- | Pass the value of this scalar expression as argument. ValueKArg :: Exp -> PrimType -> KernelArg -- | Pass this pointer as argument. MemKArg :: VName -> KernelArg -- | Create this much local memory per workgroup. SharedMemoryKArg :: Count Bytes Exp -> KernelArg -- | Host-level OpenCL operation. data OpenCL LaunchKernel :: KernelSafety -> KernelName -> [KernelArg] -> [Exp] -> [Exp] -> OpenCL GetSize :: VName -> Name -> OpenCL CmpSizeLe :: VName -> Name -> Exp -> OpenCL GetSizeMax :: VName -> SizeClass -> OpenCL -- | Information about bounds checks and how sensitive it is to errors. -- Ordered by least demanding to most. data KernelSafety -- | Does not need to know if we are in a failing state, and also cannot -- fail. SafetyNone :: KernelSafety -- | Needs to be told if there's a global failure, and that's it, and -- cannot fail. SafetyCheap :: KernelSafety -- | Needs all parameters, may fail itself. SafetyFull :: KernelSafety -- | How many leading failure arguments we must pass when launching a -- kernel with these safety characteristics. numFailureParams :: KernelSafety -> Int -- | The target platform when compiling imperative code to a Program data KernelTarget TargetOpenCL :: KernelTarget TargetCUDA :: KernelTarget -- | Something that can go wrong in a kernel. Part of the machinery for -- reporting error messages from within kernels. data FailureMsg FailureMsg :: ErrorMsg Exp -> String -> FailureMsg [failureError] :: FailureMsg -> ErrorMsg Exp [failureBacktrace] :: FailureMsg -> String -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 data Half -- | The SrcLoc of a Located value. srclocOf :: Located a => a -> SrcLoc -- | Location type, consisting of a beginning position and an end position. data Loc -- | Source location type. Source location are all equal, which allows AST -- nodes to be compared modulo location information. data SrcLoc -- | Located values have a location. class Located a locOf :: Located a => a -> Loc locOfList :: Located a => [a] -> Loc -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they always return a -- boolean value. The somewhat ugly constructor names are straight out of -- LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> Overflow -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> Overflow -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> Overflow -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> Safety -> BinOp -- | Unsigned integer division. Rounds towards positive infinity. UDivUp :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards positive infinity. SDivUp :: IntType -> Safety -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Floating-point modulus. FMod :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> Safety -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM and integer division in C. SQuot :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM and integer modulo in C. SRem :: IntType -> Safety -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. -- -- For operations like integer division, a safe division will not explode -- the computer in case of division by zero, but instead return some -- unspecified value. This always involves a run-time check, so generally -- the unsafe variant is what the compiler will insert, but guarded by an -- explicit assertion elsewhere. Safe operations are useful when the -- optimiser wants to move e.g. a division to a location where the -- divisor may be zero, but where the result will only be used when it is -- non-zero (so it doesn't matter what result is provided with a zero -- divisor, as long as the program keeps running). data Safety Unsafe :: Safety Safe :: Safety -- | What to do in case of arithmetic overflow. Futhark's semantics are -- that overflow does wraparound, but for generated code (like address -- arithmetic), it can be beneficial for overflow to be undefined -- behaviour, as it allows better optimisation of things such as GPU -- kernels. -- -- Note that all values of this type are considered equal for Eq -- and Ord. data Overflow OverflowWrap :: Overflow OverflowUndef :: Overflow -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Floating-point sign function. FSignum :: FloatType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type Unit. UnitValue :: PrimValue -- | A floating-point value. data FloatValue Float16Value :: !Half -> FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType -- | An informationless type - still takes up space! Unit :: PrimType -- | A floating point type. data FloatType Float16 :: FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue -- | The type of an integer value. intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue -- | The type of a floating-point value. floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] -- | Apply an UnOp to an operand. Returns Nothing if the -- application is mistyped. doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue -- | Apply a BinOp to an operand. Returns Nothing if the -- application is mistyped, or outside the domain (e.g. division by -- zero). doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue -- | Apply a ConvOp to an operand. Returns Nothing if the -- application is mistyped. doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Turn the conversion the other way around. Note that most conversions -- are lossy, so there is no guarantee the value will round-trip. flipConvOp :: ConvOp -> ConvOp -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue -- | Apply a CmpOp to an operand. Returns Nothing if the -- application is mistyped. doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to Int64. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | Is the given integer value kind of zero? zeroIshInt :: IntValue -> Bool -- | Is the given integer value kind of one? oneIshInt :: IntValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | The size of a value of a given integer type in eight-bit bytes. intByteSize :: Num a => IntType -> a -- | The size of a value of a given floating-point type in eight-bit bytes. floatByteSize :: Num a => FloatType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool -- | The human-readable name for a ConvOp. This is used to expose -- the ConvOp in the intrinsics module of a Futhark -- program. convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. This follows the GNU coding -- standards for error messages: -- https://www.gnu.org/prep/standards/html_node/Errors.html -- -- This function assumes that both start and end position is in the same -- file (it is not clear what the alternative would even mean). locStr :: Located a => a -> String -- | Like locStr, but locStrRel prev now prints the -- location now with the file name left out if the same as -- prev. This is useful when printing messages that are all in -- the context of some initially printed location (e.g. the first mention -- contains the file name; the rest just line and column name). locStrRel :: (Located a, Located b) => a -> b -> String -- | Given a list of strings representing entries in the stack trace and -- the index of the frame to highlight, produce a final -- newline-terminated string for showing to the user. This string should -- also be preceded by a newline. The most recent stack frame must come -- first in the list. prettyStacktrace :: Int -> [String] -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | Enclose a string in the prefered quotes used in error messages. These -- are picked to not collide with characters permitted in identifiers. quote :: String -> String -- | As quote, but works on prettyprinted representation. pquote :: Doc -> Doc -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time value. ErrorVal :: PrimType -> a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceId depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A special kind of memory that is a statically sized array of some -- primitive type. Used for private memory on GPUs. ScalarSpace :: [SubExp] -> PrimType -> Space -- | How many non-constant parts does the error message have, and what is -- their type? errorMsgArgTypes :: ErrorMsg a -> [PrimType] -- | Either return precomputed free names stored in the attribute, or the -- freshly computed names. Relies on lazy evaluation to avoid the work. class FreeIn dec => FreeDec dec precomputed :: FreeDec dec => dec -> FV -> FV -- | A class indicating that we can obtain free variable information from -- values of this type. class FreeIn a freeIn' :: FreeIn a => a -> FV -- | A computation to build a free variable set. data FV -- | A set of names. Note that the Ord instance is a dummy that -- treats everything as EQ if ==, and otherwise LT. data Names -- | Retrieve the data structure underlying the names representation. namesIntMap :: Names -> IntMap VName -- | Does the set of names contain this name? nameIn :: VName -> Names -> Bool -- | Construct a name set from a list. Slow. namesFromList :: [VName] -> Names -- | Turn a name set into a list of names. Slow. namesToList :: Names -> [VName] -- | Construct a name set from a single name. oneName :: VName -> Names -- | The intersection of two name sets. namesIntersection :: Names -> Names -> Names -- | Do the two name sets intersect? namesIntersect :: Names -> Names -> Bool -- | Subtract the latter name set from the former. namesSubtract :: Names -> Names -> Names -- | Map over the names in a set. mapNames :: (VName -> VName) -> Names -> Names -- | Consider a variable to be bound in the given FV computation. fvBind :: Names -> FV -> FV -- | Take note of a variable reference. fvName :: VName -> FV -- | Take note of a set of variable references. fvNames :: Names -> FV -- | Return the set of variable names that are free in the given statements -- and result. Filters away the names that are bound by the statements. freeInStmsAndRes :: (FreeIn (Op rep), FreeIn (LetDec rep), FreeIn (LParamInfo rep), FreeIn (FParamInfo rep), FreeDec (BodyDec rep), FreeIn (RetType rep), FreeIn (BranchType rep), FreeDec (ExpDec rep)) => Stms rep -> Result -> FV -- | The free variables of some syntactic construct. freeIn :: FreeIn a => a -> Names -- | The names bound by the bindings immediately in a Body. boundInBody :: Body rep -> Names -- | The names bound by a binding. boundByStm :: Stm rep -> Names -- | The names bound by the bindings. boundByStms :: Stms rep -> Names -- | The names of the lambda parameters plus the index parameter. boundByLambda :: Lambda rep -> [VName] -- | The class of floating-point types that can be used for constructing -- TPrimExps. class NumExp t => FloatExp t -- | Construct a typed expression from a rational. fromRational' :: FloatExp t => Rational -> TPrimExp t v -- | The class of integer types that can be used for constructing -- TPrimExps. class NumExp t => IntExp t -- | The class of numeric types that can be used for constructing -- TPrimExps. class NumExp t -- | Construct a typed expression from an integer. fromInteger' :: NumExp t => Integer -> TPrimExp t v -- | Construct a numeric expression from a boolean expression. This can be -- used to encode arithmetic control flow. fromBoolExp :: NumExp t => TPrimExp Bool v -> TPrimExp t v -- | A PrimExp tagged with a phantom type used to provide type-safe -- construction. Does not guarantee that the underlying expression is -- actually type correct. newtype TPrimExp t v TPrimExp :: PrimExp v -> TPrimExp t v [untyped] :: TPrimExp t v -> PrimExp v -- | A primitive expression parametrised over the representation of free -- variables. Note that the Functor, Traversable, and -- Num instances perform automatic (but simple) constant folding. -- -- Note also that the Num instance assumes OverflowUndef -- semantics! data PrimExp v LeafExp :: v -> PrimType -> PrimExp v ValueExp :: PrimValue -> PrimExp v BinOpExp :: BinOp -> PrimExp v -> PrimExp v -> PrimExp v CmpOpExp :: CmpOp -> PrimExp v -> PrimExp v -> PrimExp v UnOpExp :: UnOp -> PrimExp v -> PrimExp v ConvOpExp :: ConvOp -> PrimExp v -> PrimExp v FunExp :: String -> [PrimExp v] -> PrimType -> PrimExp v -- | This expression is of type Int8. isInt8 :: PrimExp v -> TPrimExp Int8 v -- | This expression is of type Int16. isInt16 :: PrimExp v -> TPrimExp Int16 v -- | This expression is of type Int32. isInt32 :: PrimExp v -> TPrimExp Int32 v -- | This expression is of type Int64. isInt64 :: PrimExp v -> TPrimExp Int64 v -- | This is a boolean expression. isBool :: PrimExp v -> TPrimExp Bool v -- | This expression is of type Half. isF16 :: PrimExp v -> TPrimExp Half v -- | This expression is of type Float. isF32 :: PrimExp v -> TPrimExp Float v -- | This expression is of type Double. isF64 :: PrimExp v -> TPrimExp Double v -- | True if the PrimExp has at least this many nodes. This can be -- much more efficient than comparing with length for large -- PrimExps, as this function is lazy. primExpSizeAtLeast :: Int -> PrimExp v -> Bool -- | Perform quick and dirty constant folding on the top level of a -- PrimExp. This is necessary because we want to consider e.g. equality -- modulo constant folding. constFoldPrimExp :: PrimExp v -> PrimExp v -- | Lifted logical conjunction. (.&&.) :: TPrimExp Bool v -> TPrimExp Bool v -> TPrimExp Bool v infixr 3 .&&. -- | Lifted logical conjunction. (.||.) :: TPrimExp Bool v -> TPrimExp Bool v -> TPrimExp Bool v infixr 2 .||. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .<. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<=.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .<=. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.==.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .==. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .>. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>=.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .>=. -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.&.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.|.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.^.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.>>.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.<<.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Untyped smart constructor for sign extension that does a bit of -- constant folding. sExt :: IntType -> PrimExp v -> PrimExp v -- | Untyped smart constructor for zero extension that does a bit of -- constant folding. zExt :: IntType -> PrimExp v -> PrimExp v -- | Evaluate a PrimExp in the given monad. Invokes fail on -- type errors. evalPrimExp :: (Pretty v, MonadFail m) => (v -> m PrimValue) -> PrimExp v -> m PrimValue -- | The type of values returned by a PrimExp. This function -- returning does not imply that the PrimExp is type-correct. primExpType :: PrimExp v -> PrimType -- | If the given PrimExp is a constant of the wrong integer type, -- coerce it to the given integer type. This is a workaround for an issue -- in the Num instance. coerceIntPrimExp :: IntType -> PrimExp v -> PrimExp v -- | Boolean-valued PrimExps. true :: TPrimExp Bool v -- | Boolean-valued PrimExps. false :: TPrimExp Bool v -- | Boolean negation smart constructor. bNot :: TPrimExp Bool v -> TPrimExp Bool v -- | SMax on 32-bit integers. sMax32 :: TPrimExp Int32 v -> TPrimExp Int32 v -> TPrimExp Int32 v -- | SMin on 32-bit integers. sMin32 :: TPrimExp Int32 v -> TPrimExp Int32 v -> TPrimExp Int32 v -- | SMax on 64-bit integers. sMax64 :: TPrimExp Int64 v -> TPrimExp Int64 v -> TPrimExp Int64 v -- | SMin on 64-bit integers. sMin64 :: TPrimExp Int64 v -> TPrimExp Int64 v -> TPrimExp Int64 v -- | Sign-extend to 32 bit integer. sExt32 :: IntExp t => TPrimExp t v -> TPrimExp Int32 v -- | Sign-extend to 64 bit integer. sExt64 :: IntExp t => TPrimExp t v -> TPrimExp Int64 v -- | Zero-extend to 32 bit integer. zExt32 :: IntExp t => TPrimExp t v -> TPrimExp Int32 v -- | Zero-extend to 64 bit integer. zExt64 :: IntExp t => TPrimExp t v -> TPrimExp Int64 v -- | 64-bit float minimum. fMin64 :: TPrimExp Double v -> TPrimExp Double v -> TPrimExp Double v -- | 64-bit float maximum. fMax64 :: TPrimExp Double v -> TPrimExp Double v -> TPrimExp Double v -- | Produce a mapping from the leaves of the PrimExp to their -- designated types. leafExpTypes :: Ord a => PrimExp a -> Set (a, PrimType) -- | A wrapper supporting a phantom type for indicating what we are -- counting. newtype Count u e Count :: e -> Count u e [unCount] :: Count u e -> e -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg -- | Like Exp, but with a required/known type. type TExp t = TPrimExp t ExpLeaf -- | A side-effect free expression whose execution will produce a single -- primitive value. type Exp = PrimExp ExpLeaf -- | The leaves of an Exp. data ExpLeaf -- | A scalar variable. The type is stored in the LeafExp -- constructor itself. ScalarVar :: VName -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> ExpLeaf -- | The volatility of a memory access or variable. Feel free to ignore -- this for backends where it makes no sense (anything but C and similar -- low-level things) data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | Log the given message, *without* a trailing linebreak (unless part of -- the mssage). pattern TracePrint :: () => ErrorMsg Exp -> Code a -- | Print the given value to the screen, somehow annotated with the given -- string as a description. If no type/value pair, just print the string. -- This has no semantic meaning, but is used entirely for debugging. Code -- generators are free to ignore this statement. pattern DebugPrint :: () => String -> Maybe Exp -> Code a -- | Must be in same space. pattern SetMem :: () => VName -> VName -> Space -> Code a -- | Set a scalar variable. pattern SetScalar :: () => VName -> Exp -> Code a -- | Create an array containing the given values. The lifetime of the array -- will be the entire application. This is mostly used for constant -- arrays, but also for some bookkeeping data, like the synchronisation -- counts used to implement reduction. pattern DeclareArray :: () => VName -> Space -> PrimType -> ArrayContents -> Code a -- | Declare a scalar variable with an initially undefined value. pattern DeclareScalar :: () => VName -> Volatility -> PrimType -> Code a -- | Declare a memory block variable that will point to memory in the given -- memory space. Note that this is distinct from allocation. The memory -- block must be the target of either an Allocate or a -- SetMem before it can be used for reading or writing. pattern DeclareMem :: () => VName -> Space -> Code a -- | Statement composition. Crucial for the Semigroup instance. pattern (:>>:) :: () => Code a -> Code a -> Code a -- | Assert that something must be true. Should it turn out not to be true, -- then report a failure along with the given error message. pattern Assert :: () => Exp -> ErrorMsg Exp -> (SrcLoc, [SrcLoc]) -> Code a -- | Function call. The results are written to the provided VName -- variables. pattern Call :: () => [VName] -> Name -> [Arg] -> Code a -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. pattern Copy :: () => VName -> Count Bytes (TExp Int64) -> Space -> VName -> Count Bytes (TExp Int64) -> Space -> Count Bytes (TExp Int64) -> Code a -- | Memory space must match the corresponding DeclareMem. pattern Allocate :: () => VName -> Count Bytes (TExp Int64) -> Space -> Code a -- | No-op. Crucial for the Monoid instance. pattern Skip :: () => Code a -- | A for-loop iterating the given number of times. The loop parameter -- starts counting from zero and will have the same (integer) type as the -- bound. The bound is evaluated just once, before the loop is entered. pattern For :: () => VName -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. pattern While :: () => TExp Bool -> Code a -> Code a -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. pattern Free :: () => VName -> Space -> Code a -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. pattern Comment :: () => String -> Code a -> Code a -- | Write mem i t space vol v writes the value v to -- mem offset by i elements of type t. The -- Space argument is the memory space of mem (technically -- redundant, but convenient). Note that reading is done with an -- Exp (Index). pattern Write :: () => VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -> Code a -- | Conditional execution. pattern If :: () => TExp Bool -> Code a -> Code a -> Code a -- | Perform an extensible operation. pattern Op :: () => a -> Code a -- | The contents of a statically declared constant array. Such arrays are -- always unidimensional, and reshaped if necessary in the code that uses -- them. data ArrayContents -- | Precisely these values. ArrayValues :: [PrimValue] -> ArrayContents -- | This many zeroes. ArrayZeros :: Int -> ArrayContents -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. We record the uniqueness because it is important to the -- external interface as well. data ExternalValue -- | The string is a human-readable description with no other semantics. -- not matter. OpaqueValue :: Uniqueness -> String -> [ValueDesc] -> ExternalValue TransparentValue :: Uniqueness -> ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block memory space, element type, signedness of -- element type (if applicable), and shape. ArrayValue :: VName -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc -- | Since the core language does not care for signedness, but the source -- language does, entry point input/output information has metadata for -- integer types (and arrays containing these) that indicate whether they -- are really unsigned integers. data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | A collection of imperative constants. data Constants a Constants :: [Param] -> Code a -> Constants a -- | The constants that are made available to the functions. [constsDecl] :: Constants a -> [Param] -- | Setting the value of the constants. Note that this must not contain -- declarations of the names defined in constsDecl. [constsInit] :: Constants a -> Code a -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a -- | A collection of imperative functions and constants. data Definitions a Definitions :: Constants a -> Functions a -> Definitions a [defConsts] :: Definitions a -> Constants a [defFuns] :: Definitions a -> Functions a -- | An ImpCode function parameter. data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param -- | The size of an array. type DimSize = SubExp -- | The size of a memory block. type MemSize = SubExp -- | The name of a parameter. paramName :: Param -> VName -- | Find those memory blocks that are used only lexically. That is, are -- not used as the source or target of a SetMem, or are the result -- of the function, nor passed as arguments to other functions. This is -- interesting because such memory blocks do not need reference counting, -- but can be managed in a purely stack-like fashion. -- -- We do not look inside any Ops. We assume that no Op is -- going to SetMem a memory block declared outside it. lexicalMemoryUsage :: Function a -> Map VName Space -- | The set of functions that are called by this code. Assumes there are -- no function calls in Ops. calledFuncs :: Code a -> Set Name -- | This expression counts elements. elements :: a -> Count Elements a -- | This expression counts bytes. bytes :: a -> Count Bytes a -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements (TExp Int64) -> PrimType -> Count Bytes (TExp Int64) -- | Turn a VName into a ScalarVar. var :: VName -> PrimType -> Exp -- | Turn a VName into a Int32 ScalarVar. vi32 :: VName -> TExp Int32 -- | Turn a VName into a Int64 ScalarVar. vi64 :: VName -> TExp Int64 -- | Concise wrapper for using Index. index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -- | The names declared with DeclareMem, DeclareScalar, and -- DeclareArray in the given code. declaredIn :: Code a -> Names instance GHC.Show.Show Futhark.CodeGen.ImpCode.OpenCL.KernelArg instance GHC.Show.Show Futhark.CodeGen.ImpCode.OpenCL.MayFail instance GHC.Show.Show Futhark.CodeGen.ImpCode.OpenCL.KernelSafety instance GHC.Classes.Ord Futhark.CodeGen.ImpCode.OpenCL.KernelSafety instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.OpenCL.KernelSafety instance GHC.Show.Show Futhark.CodeGen.ImpCode.OpenCL.OpenCL instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.OpenCL.KernelTarget instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.OpenCL.OpenCL -- | Multicore imperative code. module Futhark.CodeGen.ImpCode.Multicore -- | An imperative program. type Program = Functions Multicore -- | An imperative function. type Function = Function Multicore -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Maybe Name -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a -- | A piece of imperative code, with multicore operations inside. type Code = Code Multicore -- | A multicore operation. data Multicore Segop :: String -> [Param] -> ParallelTask -> Maybe ParallelTask -> [Param] -> SchedulerInfo -> Multicore ParLoop :: String -> VName -> Code -> Code -> Code -> [Param] -> VName -> Multicore Atomic :: AtomicOp -> Multicore -- | Whether the Scheduler should schedule the tasks as Dynamic or it is -- restainted to Static data Scheduling Dynamic :: Scheduling Static :: Scheduling data SchedulerInfo SchedulerInfo :: VName -> Exp -> Scheduling -> SchedulerInfo [nsubtasks] :: SchedulerInfo -> VName [iterations] :: SchedulerInfo -> Exp [scheduling] :: SchedulerInfo -> Scheduling -- | Atomic operations return the value stored before the update. This old -- value is stored in the first VName. The second VName is -- the memory block to update. The Exp is the new value. data AtomicOp AtomicAdd :: IntType -> VName -> VName -> Count Elements (TExp Int32) -> Exp -> AtomicOp AtomicSub :: IntType -> VName -> VName -> Count Elements (TExp Int32) -> Exp -> AtomicOp AtomicAnd :: IntType -> VName -> VName -> Count Elements (TExp Int32) -> Exp -> AtomicOp AtomicOr :: IntType -> VName -> VName -> Count Elements (TExp Int32) -> Exp -> AtomicOp AtomicXor :: IntType -> VName -> VName -> Count Elements (TExp Int32) -> Exp -> AtomicOp AtomicXchg :: PrimType -> VName -> VName -> Count Elements (TExp Int32) -> Exp -> AtomicOp AtomicCmpXchg :: PrimType -> VName -> VName -> Count Elements (TExp Int32) -> VName -> Exp -> AtomicOp data ParallelTask ParallelTask :: Code -> VName -> ParallelTask [task_code] :: ParallelTask -> Code [flatTid] :: ParallelTask -> VName -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 data Half -- | The SrcLoc of a Located value. srclocOf :: Located a => a -> SrcLoc -- | Location type, consisting of a beginning position and an end position. data Loc -- | Source location type. Source location are all equal, which allows AST -- nodes to be compared modulo location information. data SrcLoc -- | Located values have a location. class Located a locOf :: Located a => a -> Loc locOfList :: Located a => [a] -> Loc -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they always return a -- boolean value. The somewhat ugly constructor names are straight out of -- LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> Overflow -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> Overflow -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> Overflow -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> Safety -> BinOp -- | Unsigned integer division. Rounds towards positive infinity. UDivUp :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards positive infinity. SDivUp :: IntType -> Safety -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Floating-point modulus. FMod :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> Safety -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM and integer division in C. SQuot :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM and integer modulo in C. SRem :: IntType -> Safety -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. -- -- For operations like integer division, a safe division will not explode -- the computer in case of division by zero, but instead return some -- unspecified value. This always involves a run-time check, so generally -- the unsafe variant is what the compiler will insert, but guarded by an -- explicit assertion elsewhere. Safe operations are useful when the -- optimiser wants to move e.g. a division to a location where the -- divisor may be zero, but where the result will only be used when it is -- non-zero (so it doesn't matter what result is provided with a zero -- divisor, as long as the program keeps running). data Safety Unsafe :: Safety Safe :: Safety -- | What to do in case of arithmetic overflow. Futhark's semantics are -- that overflow does wraparound, but for generated code (like address -- arithmetic), it can be beneficial for overflow to be undefined -- behaviour, as it allows better optimisation of things such as GPU -- kernels. -- -- Note that all values of this type are considered equal for Eq -- and Ord. data Overflow OverflowWrap :: Overflow OverflowUndef :: Overflow -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Floating-point sign function. FSignum :: FloatType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type Unit. UnitValue :: PrimValue -- | A floating-point value. data FloatValue Float16Value :: !Half -> FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType -- | An informationless type - still takes up space! Unit :: PrimType -- | A floating point type. data FloatType Float16 :: FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue -- | The type of an integer value. intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue -- | The type of a floating-point value. floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] -- | Apply an UnOp to an operand. Returns Nothing if the -- application is mistyped. doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue -- | Apply a BinOp to an operand. Returns Nothing if the -- application is mistyped, or outside the domain (e.g. division by -- zero). doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue -- | Apply a ConvOp to an operand. Returns Nothing if the -- application is mistyped. doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Turn the conversion the other way around. Note that most conversions -- are lossy, so there is no guarantee the value will round-trip. flipConvOp :: ConvOp -> ConvOp -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue -- | Apply a CmpOp to an operand. Returns Nothing if the -- application is mistyped. doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to Int64. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | Is the given integer value kind of zero? zeroIshInt :: IntValue -> Bool -- | Is the given integer value kind of one? oneIshInt :: IntValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | The size of a value of a given integer type in eight-bit bytes. intByteSize :: Num a => IntType -> a -- | The size of a value of a given floating-point type in eight-bit bytes. floatByteSize :: Num a => FloatType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool -- | The human-readable name for a ConvOp. This is used to expose -- the ConvOp in the intrinsics module of a Futhark -- program. convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. This follows the GNU coding -- standards for error messages: -- https://www.gnu.org/prep/standards/html_node/Errors.html -- -- This function assumes that both start and end position is in the same -- file (it is not clear what the alternative would even mean). locStr :: Located a => a -> String -- | Like locStr, but locStrRel prev now prints the -- location now with the file name left out if the same as -- prev. This is useful when printing messages that are all in -- the context of some initially printed location (e.g. the first mention -- contains the file name; the rest just line and column name). locStrRel :: (Located a, Located b) => a -> b -> String -- | Given a list of strings representing entries in the stack trace and -- the index of the frame to highlight, produce a final -- newline-terminated string for showing to the user. This string should -- also be preceded by a newline. The most recent stack frame must come -- first in the list. prettyStacktrace :: Int -> [String] -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | Enclose a string in the prefered quotes used in error messages. These -- are picked to not collide with characters permitted in identifiers. quote :: String -> String -- | As quote, but works on prettyprinted representation. pquote :: Doc -> Doc -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time value. ErrorVal :: PrimType -> a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceId depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A special kind of memory that is a statically sized array of some -- primitive type. Used for private memory on GPUs. ScalarSpace :: [SubExp] -> PrimType -> Space -- | How many non-constant parts does the error message have, and what is -- their type? errorMsgArgTypes :: ErrorMsg a -> [PrimType] -- | Either return precomputed free names stored in the attribute, or the -- freshly computed names. Relies on lazy evaluation to avoid the work. class FreeIn dec => FreeDec dec precomputed :: FreeDec dec => dec -> FV -> FV -- | A class indicating that we can obtain free variable information from -- values of this type. class FreeIn a freeIn' :: FreeIn a => a -> FV -- | A computation to build a free variable set. data FV -- | A set of names. Note that the Ord instance is a dummy that -- treats everything as EQ if ==, and otherwise LT. data Names -- | Retrieve the data structure underlying the names representation. namesIntMap :: Names -> IntMap VName -- | Does the set of names contain this name? nameIn :: VName -> Names -> Bool -- | Construct a name set from a list. Slow. namesFromList :: [VName] -> Names -- | Turn a name set into a list of names. Slow. namesToList :: Names -> [VName] -- | Construct a name set from a single name. oneName :: VName -> Names -- | The intersection of two name sets. namesIntersection :: Names -> Names -> Names -- | Do the two name sets intersect? namesIntersect :: Names -> Names -> Bool -- | Subtract the latter name set from the former. namesSubtract :: Names -> Names -> Names -- | Map over the names in a set. mapNames :: (VName -> VName) -> Names -> Names -- | Consider a variable to be bound in the given FV computation. fvBind :: Names -> FV -> FV -- | Take note of a variable reference. fvName :: VName -> FV -- | Take note of a set of variable references. fvNames :: Names -> FV -- | Return the set of variable names that are free in the given statements -- and result. Filters away the names that are bound by the statements. freeInStmsAndRes :: (FreeIn (Op rep), FreeIn (LetDec rep), FreeIn (LParamInfo rep), FreeIn (FParamInfo rep), FreeDec (BodyDec rep), FreeIn (RetType rep), FreeIn (BranchType rep), FreeDec (ExpDec rep)) => Stms rep -> Result -> FV -- | The free variables of some syntactic construct. freeIn :: FreeIn a => a -> Names -- | The names bound by the bindings immediately in a Body. boundInBody :: Body rep -> Names -- | The names bound by a binding. boundByStm :: Stm rep -> Names -- | The names bound by the bindings. boundByStms :: Stms rep -> Names -- | The names of the lambda parameters plus the index parameter. boundByLambda :: Lambda rep -> [VName] -- | The class of floating-point types that can be used for constructing -- TPrimExps. class NumExp t => FloatExp t -- | Construct a typed expression from a rational. fromRational' :: FloatExp t => Rational -> TPrimExp t v -- | The class of integer types that can be used for constructing -- TPrimExps. class NumExp t => IntExp t -- | The class of numeric types that can be used for constructing -- TPrimExps. class NumExp t -- | Construct a typed expression from an integer. fromInteger' :: NumExp t => Integer -> TPrimExp t v -- | Construct a numeric expression from a boolean expression. This can be -- used to encode arithmetic control flow. fromBoolExp :: NumExp t => TPrimExp Bool v -> TPrimExp t v -- | A PrimExp tagged with a phantom type used to provide type-safe -- construction. Does not guarantee that the underlying expression is -- actually type correct. newtype TPrimExp t v TPrimExp :: PrimExp v -> TPrimExp t v [untyped] :: TPrimExp t v -> PrimExp v -- | A primitive expression parametrised over the representation of free -- variables. Note that the Functor, Traversable, and -- Num instances perform automatic (but simple) constant folding. -- -- Note also that the Num instance assumes OverflowUndef -- semantics! data PrimExp v LeafExp :: v -> PrimType -> PrimExp v ValueExp :: PrimValue -> PrimExp v BinOpExp :: BinOp -> PrimExp v -> PrimExp v -> PrimExp v CmpOpExp :: CmpOp -> PrimExp v -> PrimExp v -> PrimExp v UnOpExp :: UnOp -> PrimExp v -> PrimExp v ConvOpExp :: ConvOp -> PrimExp v -> PrimExp v FunExp :: String -> [PrimExp v] -> PrimType -> PrimExp v -- | This expression is of type Int8. isInt8 :: PrimExp v -> TPrimExp Int8 v -- | This expression is of type Int16. isInt16 :: PrimExp v -> TPrimExp Int16 v -- | This expression is of type Int32. isInt32 :: PrimExp v -> TPrimExp Int32 v -- | This expression is of type Int64. isInt64 :: PrimExp v -> TPrimExp Int64 v -- | This is a boolean expression. isBool :: PrimExp v -> TPrimExp Bool v -- | This expression is of type Half. isF16 :: PrimExp v -> TPrimExp Half v -- | This expression is of type Float. isF32 :: PrimExp v -> TPrimExp Float v -- | This expression is of type Double. isF64 :: PrimExp v -> TPrimExp Double v -- | True if the PrimExp has at least this many nodes. This can be -- much more efficient than comparing with length for large -- PrimExps, as this function is lazy. primExpSizeAtLeast :: Int -> PrimExp v -> Bool -- | Perform quick and dirty constant folding on the top level of a -- PrimExp. This is necessary because we want to consider e.g. equality -- modulo constant folding. constFoldPrimExp :: PrimExp v -> PrimExp v -- | Lifted logical conjunction. (.&&.) :: TPrimExp Bool v -> TPrimExp Bool v -> TPrimExp Bool v infixr 3 .&&. -- | Lifted logical conjunction. (.||.) :: TPrimExp Bool v -> TPrimExp Bool v -> TPrimExp Bool v infixr 2 .||. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .<. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<=.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .<=. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.==.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .==. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .>. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>=.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .>=. -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.&.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.|.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.^.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.>>.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.<<.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Untyped smart constructor for sign extension that does a bit of -- constant folding. sExt :: IntType -> PrimExp v -> PrimExp v -- | Untyped smart constructor for zero extension that does a bit of -- constant folding. zExt :: IntType -> PrimExp v -> PrimExp v -- | Evaluate a PrimExp in the given monad. Invokes fail on -- type errors. evalPrimExp :: (Pretty v, MonadFail m) => (v -> m PrimValue) -> PrimExp v -> m PrimValue -- | The type of values returned by a PrimExp. This function -- returning does not imply that the PrimExp is type-correct. primExpType :: PrimExp v -> PrimType -- | If the given PrimExp is a constant of the wrong integer type, -- coerce it to the given integer type. This is a workaround for an issue -- in the Num instance. coerceIntPrimExp :: IntType -> PrimExp v -> PrimExp v -- | Boolean-valued PrimExps. true :: TPrimExp Bool v -- | Boolean-valued PrimExps. false :: TPrimExp Bool v -- | Boolean negation smart constructor. bNot :: TPrimExp Bool v -> TPrimExp Bool v -- | SMax on 32-bit integers. sMax32 :: TPrimExp Int32 v -> TPrimExp Int32 v -> TPrimExp Int32 v -- | SMin on 32-bit integers. sMin32 :: TPrimExp Int32 v -> TPrimExp Int32 v -> TPrimExp Int32 v -- | SMax on 64-bit integers. sMax64 :: TPrimExp Int64 v -> TPrimExp Int64 v -> TPrimExp Int64 v -- | SMin on 64-bit integers. sMin64 :: TPrimExp Int64 v -> TPrimExp Int64 v -> TPrimExp Int64 v -- | Sign-extend to 32 bit integer. sExt32 :: IntExp t => TPrimExp t v -> TPrimExp Int32 v -- | Sign-extend to 64 bit integer. sExt64 :: IntExp t => TPrimExp t v -> TPrimExp Int64 v -- | Zero-extend to 32 bit integer. zExt32 :: IntExp t => TPrimExp t v -> TPrimExp Int32 v -- | Zero-extend to 64 bit integer. zExt64 :: IntExp t => TPrimExp t v -> TPrimExp Int64 v -- | 64-bit float minimum. fMin64 :: TPrimExp Double v -> TPrimExp Double v -> TPrimExp Double v -- | 64-bit float maximum. fMax64 :: TPrimExp Double v -> TPrimExp Double v -> TPrimExp Double v -- | Produce a mapping from the leaves of the PrimExp to their -- designated types. leafExpTypes :: Ord a => PrimExp a -> Set (a, PrimType) -- | A wrapper supporting a phantom type for indicating what we are -- counting. newtype Count u e Count :: e -> Count u e [unCount] :: Count u e -> e -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg -- | Like Exp, but with a required/known type. type TExp t = TPrimExp t ExpLeaf -- | A side-effect free expression whose execution will produce a single -- primitive value. type Exp = PrimExp ExpLeaf -- | The leaves of an Exp. data ExpLeaf -- | A scalar variable. The type is stored in the LeafExp -- constructor itself. ScalarVar :: VName -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> ExpLeaf -- | The volatility of a memory access or variable. Feel free to ignore -- this for backends where it makes no sense (anything but C and similar -- low-level things) data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | Log the given message, *without* a trailing linebreak (unless part of -- the mssage). pattern TracePrint :: () => ErrorMsg Exp -> Code a -- | Print the given value to the screen, somehow annotated with the given -- string as a description. If no type/value pair, just print the string. -- This has no semantic meaning, but is used entirely for debugging. Code -- generators are free to ignore this statement. pattern DebugPrint :: () => String -> Maybe Exp -> Code a -- | Must be in same space. pattern SetMem :: () => VName -> VName -> Space -> Code a -- | Set a scalar variable. pattern SetScalar :: () => VName -> Exp -> Code a -- | Create an array containing the given values. The lifetime of the array -- will be the entire application. This is mostly used for constant -- arrays, but also for some bookkeeping data, like the synchronisation -- counts used to implement reduction. pattern DeclareArray :: () => VName -> Space -> PrimType -> ArrayContents -> Code a -- | Declare a scalar variable with an initially undefined value. pattern DeclareScalar :: () => VName -> Volatility -> PrimType -> Code a -- | Declare a memory block variable that will point to memory in the given -- memory space. Note that this is distinct from allocation. The memory -- block must be the target of either an Allocate or a -- SetMem before it can be used for reading or writing. pattern DeclareMem :: () => VName -> Space -> Code a -- | Statement composition. Crucial for the Semigroup instance. pattern (:>>:) :: () => Code a -> Code a -> Code a -- | Assert that something must be true. Should it turn out not to be true, -- then report a failure along with the given error message. pattern Assert :: () => Exp -> ErrorMsg Exp -> (SrcLoc, [SrcLoc]) -> Code a -- | Function call. The results are written to the provided VName -- variables. pattern Call :: () => [VName] -> Name -> [Arg] -> Code a -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. pattern Copy :: () => VName -> Count Bytes (TExp Int64) -> Space -> VName -> Count Bytes (TExp Int64) -> Space -> Count Bytes (TExp Int64) -> Code a -- | Memory space must match the corresponding DeclareMem. pattern Allocate :: () => VName -> Count Bytes (TExp Int64) -> Space -> Code a -- | No-op. Crucial for the Monoid instance. pattern Skip :: () => Code a -- | A for-loop iterating the given number of times. The loop parameter -- starts counting from zero and will have the same (integer) type as the -- bound. The bound is evaluated just once, before the loop is entered. pattern For :: () => VName -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. pattern While :: () => TExp Bool -> Code a -> Code a -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. pattern Free :: () => VName -> Space -> Code a -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. pattern Comment :: () => String -> Code a -> Code a -- | Write mem i t space vol v writes the value v to -- mem offset by i elements of type t. The -- Space argument is the memory space of mem (technically -- redundant, but convenient). Note that reading is done with an -- Exp (Index). pattern Write :: () => VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -> Code a -- | Conditional execution. pattern If :: () => TExp Bool -> Code a -> Code a -> Code a -- | Perform an extensible operation. pattern Op :: () => a -> Code a -- | The contents of a statically declared constant array. Such arrays are -- always unidimensional, and reshaped if necessary in the code that uses -- them. data ArrayContents -- | Precisely these values. ArrayValues :: [PrimValue] -> ArrayContents -- | This many zeroes. ArrayZeros :: Int -> ArrayContents -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. We record the uniqueness because it is important to the -- external interface as well. data ExternalValue -- | The string is a human-readable description with no other semantics. -- not matter. OpaqueValue :: Uniqueness -> String -> [ValueDesc] -> ExternalValue TransparentValue :: Uniqueness -> ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block memory space, element type, signedness of -- element type (if applicable), and shape. ArrayValue :: VName -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc -- | Since the core language does not care for signedness, but the source -- language does, entry point input/output information has metadata for -- integer types (and arrays containing these) that indicate whether they -- are really unsigned integers. data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | A collection of imperative constants. data Constants a Constants :: [Param] -> Code a -> Constants a -- | The constants that are made available to the functions. [constsDecl] :: Constants a -> [Param] -- | Setting the value of the constants. Note that this must not contain -- declarations of the names defined in constsDecl. [constsInit] :: Constants a -> Code a -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a -- | A collection of imperative functions and constants. data Definitions a Definitions :: Constants a -> Functions a -> Definitions a [defConsts] :: Definitions a -> Constants a [defFuns] :: Definitions a -> Functions a -- | An ImpCode function parameter. data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param -- | The size of an array. type DimSize = SubExp -- | The size of a memory block. type MemSize = SubExp -- | The name of a parameter. paramName :: Param -> VName -- | Find those memory blocks that are used only lexically. That is, are -- not used as the source or target of a SetMem, or are the result -- of the function, nor passed as arguments to other functions. This is -- interesting because such memory blocks do not need reference counting, -- but can be managed in a purely stack-like fashion. -- -- We do not look inside any Ops. We assume that no Op is -- going to SetMem a memory block declared outside it. lexicalMemoryUsage :: Function a -> Map VName Space -- | The set of functions that are called by this code. Assumes there are -- no function calls in Ops. calledFuncs :: Code a -> Set Name -- | This expression counts elements. elements :: a -> Count Elements a -- | This expression counts bytes. bytes :: a -> Count Bytes a -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements (TExp Int64) -> PrimType -> Count Bytes (TExp Int64) -- | Turn a VName into a ScalarVar. var :: VName -> PrimType -> Exp -- | Turn a VName into a Int32 ScalarVar. vi32 :: VName -> TExp Int32 -- | Turn a VName into a Int64 ScalarVar. vi64 :: VName -> TExp Int64 -- | Concise wrapper for using Index. index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -- | The names declared with DeclareMem, DeclareScalar, and -- DeclareArray in the given code. declaredIn :: Code a -> Names instance GHC.Show.Show Futhark.CodeGen.ImpCode.Multicore.AtomicOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Multicore.ParallelTask instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Multicore.Multicore instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Multicore.ParallelTask instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Multicore.Multicore instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Multicore.SchedulerInfo instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Multicore.SchedulerInfo instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Multicore.Scheduling instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Multicore.AtomicOp -- | Variation of Futhark.CodeGen.ImpCode that contains the notion -- of a kernel invocation. module Futhark.CodeGen.ImpCode.GPU -- | A program that calls kernels. type Program = Definitions HostOp -- | A function that calls kernels. type Function = Function HostOp -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a Function :: Maybe Name -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a -- | Host-level code that can call kernels. type Code = Code HostOp -- | Code inside a kernel. type KernelCode = Code KernelOp -- | A run-time constant related to kernels. newtype KernelConst SizeConst :: Name -> KernelConst -- | An expression whose variables are kernel constants. type KernelConstExp = PrimExp KernelConst -- | An operation that runs on the host (CPU). data HostOp CallKernel :: Kernel -> HostOp GetSize :: VName -> Name -> SizeClass -> HostOp CmpSizeLe :: VName -> Name -> SizeClass -> Exp -> HostOp GetSizeMax :: VName -> SizeClass -> HostOp -- | An operation that occurs within a kernel body. data KernelOp GetGroupId :: VName -> Int -> KernelOp GetLocalId :: VName -> Int -> KernelOp GetLocalSize :: VName -> Int -> KernelOp GetGlobalSize :: VName -> Int -> KernelOp GetGlobalId :: VName -> Int -> KernelOp GetLockstepWidth :: VName -> KernelOp Atomic :: Space -> AtomicOp -> KernelOp Barrier :: Fence -> KernelOp MemFence :: Fence -> KernelOp LocalAlloc :: VName -> Count Bytes (TExp Int64) -> KernelOp -- | Perform a barrier and also check whether any threads have failed an -- assertion. Make sure all threads would reach all ErrorSyncs if -- any of them do. A failing assertion will jump to the next following -- ErrorSync, so make sure it's not inside control flow or -- similar. ErrorSync :: Fence -> KernelOp -- | When we do a barrier or fence, is it at the local or global level? data Fence FenceLocal :: Fence FenceGlobal :: Fence -- | Atomic operations return the value stored before the update. This old -- value is stored in the first VName. The second VName is -- the memory block to update. The Exp is the new value. data AtomicOp AtomicAdd :: IntType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicFAdd :: FloatType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicSMax :: IntType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicSMin :: IntType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicUMax :: IntType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicUMin :: IntType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicAnd :: IntType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicOr :: IntType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicXor :: IntType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp AtomicCmpXchg :: PrimType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> Exp -> AtomicOp AtomicXchg :: PrimType -> VName -> VName -> Count Elements (TExp Int64) -> Exp -> AtomicOp -- | A generic kernel containing arbitrary kernel code. data Kernel Kernel :: Code KernelOp -> [KernelUse] -> [Exp] -> [Exp] -> Name -> Bool -> Kernel [kernelBody] :: Kernel -> Code KernelOp -- | The host variables referenced by the kernel. [kernelUses] :: Kernel -> [KernelUse] [kernelNumGroups] :: Kernel -> [Exp] [kernelGroupSize] :: Kernel -> [Exp] -- | A short descriptive and _unique_ name - should be alphanumeric and -- without spaces. [kernelName] :: Kernel -> Name -- | If true, this kernel does not need to check whether we are in a -- failing state, as it can cope. Intuitively, it means that the kernel -- does not depend on any non-scalar parameters to make control flow -- decisions. Replication, transpose, and copy kernels are examples of -- this. [kernelFailureTolerant] :: Kernel -> Bool -- | Information about a host-level variable that is used inside this -- kernel. When generating the actual kernel code, this is used to deduce -- which parameters are needed. data KernelUse ScalarUse :: VName -> PrimType -> KernelUse MemoryUse :: VName -> KernelUse ConstUse :: VName -> KernelConstExp -> KernelUse -- | 8-bit signed integer type data Int8 -- | 16-bit signed integer type data Int16 -- | 32-bit signed integer type data Int32 -- | 64-bit signed integer type data Int64 -- | 8-bit unsigned integer type data Word8 -- | 16-bit unsigned integer type data Word16 -- | 32-bit unsigned integer type data Word32 -- | 64-bit unsigned integer type data Word64 data Half -- | The SrcLoc of a Located value. srclocOf :: Located a => a -> SrcLoc -- | Location type, consisting of a beginning position and an end position. data Loc -- | Source location type. Source location are all equal, which allows AST -- nodes to be compared modulo location information. data SrcLoc -- | Located values have a location. class Located a locOf :: Located a => a -> Loc locOfList :: Located a => [a] -> Loc -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Conversion operators try to generalise the from t0 x to t1 -- instructions from LLVM. data ConvOp -- | Zero-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. ZExt :: IntType -> IntType -> ConvOp -- | Sign-extend the former integer type to the latter. If the new type is -- smaller, the result is a truncation. SExt :: IntType -> IntType -> ConvOp -- | Convert value of the former floating-point type to the latter. If the -- new type is smaller, the result is a truncation. FPConv :: FloatType -> FloatType -> ConvOp -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). FPToUI :: FloatType -> IntType -> ConvOp -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). FPToSI :: FloatType -> IntType -> ConvOp -- | Convert an unsigned integer to a floating-point value. UIToFP :: IntType -> FloatType -> ConvOp -- | Convert a signed integer to a floating-point value. SIToFP :: IntType -> FloatType -> ConvOp -- | Convert an integer to a boolean value. Zero becomes false; anything -- else is true. IToB :: IntType -> ConvOp -- | Convert a boolean to an integer. True is converted to 1 and False to -- 0. BToI :: IntType -> ConvOp -- | Comparison operators are like BinOps, but they always return a -- boolean value. The somewhat ugly constructor names are straight out of -- LLVM. data CmpOp -- | All types equality. CmpEq :: PrimType -> CmpOp -- | Unsigned less than. CmpUlt :: IntType -> CmpOp -- | Unsigned less than or equal. CmpUle :: IntType -> CmpOp -- | Signed less than. CmpSlt :: IntType -> CmpOp -- | Signed less than or equal. CmpSle :: IntType -> CmpOp -- | Floating-point less than. FCmpLt :: FloatType -> CmpOp -- | Floating-point less than or equal. FCmpLe :: FloatType -> CmpOp -- | Boolean less than. CmpLlt :: CmpOp -- | Boolean less than or equal. CmpLle :: CmpOp -- | Binary operators. These correspond closely to the binary operators in -- LLVM. Most are parametrised by their expected input and output types. data BinOp -- | Integer addition. Add :: IntType -> Overflow -> BinOp -- | Floating-point addition. FAdd :: FloatType -> BinOp -- | Integer subtraction. Sub :: IntType -> Overflow -> BinOp -- | Floating-point subtraction. FSub :: FloatType -> BinOp -- | Integer multiplication. Mul :: IntType -> Overflow -> BinOp -- | Floating-point multiplication. FMul :: FloatType -> BinOp -- | Unsigned integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. UDiv :: IntType -> Safety -> BinOp -- | Unsigned integer division. Rounds towards positive infinity. UDivUp :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. SDiv :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards positive infinity. SDivUp :: IntType -> Safety -> BinOp -- | Floating-point division. FDiv :: FloatType -> BinOp -- | Floating-point modulus. FMod :: FloatType -> BinOp -- | Unsigned integer modulus; the countepart to UDiv. UMod :: IntType -> Safety -> BinOp -- | Signed integer modulus; the countepart to SDiv. SMod :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- sdiv instruction in LLVM and integer division in C. SQuot :: IntType -> Safety -> BinOp -- | Signed integer division. Rounds towards zero. This corresponds to the -- srem instruction in LLVM and integer modulo in C. SRem :: IntType -> Safety -> BinOp -- | Returns the smallest of two signed integers. SMin :: IntType -> BinOp -- | Returns the smallest of two unsigned integers. UMin :: IntType -> BinOp -- | Returns the smallest of two floating-point numbers. FMin :: FloatType -> BinOp -- | Returns the greatest of two signed integers. SMax :: IntType -> BinOp -- | Returns the greatest of two unsigned integers. UMax :: IntType -> BinOp -- | Returns the greatest of two floating-point numbers. FMax :: FloatType -> BinOp -- | Left-shift. Shl :: IntType -> BinOp -- | Logical right-shift, zero-extended. LShr :: IntType -> BinOp -- | Arithmetic right-shift, sign-extended. AShr :: IntType -> BinOp -- | Bitwise and. And :: IntType -> BinOp -- | Bitwise or. Or :: IntType -> BinOp -- | Bitwise exclusive-or. Xor :: IntType -> BinOp -- | Integer exponentiation. Pow :: IntType -> BinOp -- | Floating-point exponentiation. FPow :: FloatType -> BinOp -- | Boolean and - not short-circuiting. LogAnd :: BinOp -- | Boolean or - not short-circuiting. LogOr :: BinOp -- | Whether something is safe or unsafe (mostly function calls, and in the -- context of whether operations are dynamically checked). When we inline -- an Unsafe function, we remove all safety checks in its body. -- The Ord instance picks Unsafe as being less than -- Safe. -- -- For operations like integer division, a safe division will not explode -- the computer in case of division by zero, but instead return some -- unspecified value. This always involves a run-time check, so generally -- the unsafe variant is what the compiler will insert, but guarded by an -- explicit assertion elsewhere. Safe operations are useful when the -- optimiser wants to move e.g. a division to a location where the -- divisor may be zero, but where the result will only be used when it is -- non-zero (so it doesn't matter what result is provided with a zero -- divisor, as long as the program keeps running). data Safety Unsafe :: Safety Safe :: Safety -- | What to do in case of arithmetic overflow. Futhark's semantics are -- that overflow does wraparound, but for generated code (like address -- arithmetic), it can be beneficial for overflow to be undefined -- behaviour, as it allows better optimisation of things such as GPU -- kernels. -- -- Note that all values of this type are considered equal for Eq -- and Ord. data Overflow OverflowWrap :: Overflow OverflowUndef :: Overflow -- | Various unary operators. It is a bit ad-hoc what is a unary operator -- and what is a built-in function. Perhaps these should all go away -- eventually. data UnOp -- | E.g., ! True == False. Not :: UnOp -- | E.g., ~(~1) = 1. Complement :: IntType -> UnOp -- | abs(-2) = 2. Abs :: IntType -> UnOp -- | fabs(-2.0) = 2.0. FAbs :: FloatType -> UnOp -- | Signed sign function: ssignum(-2) = -1. SSignum :: IntType -> UnOp -- | Unsigned sign function: usignum(2) = 1. USignum :: IntType -> UnOp -- | Floating-point sign function. FSignum :: FloatType -> UnOp -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type Unit. UnitValue :: PrimValue -- | A floating-point value. data FloatValue Float16Value :: !Half -> FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | Low-level primitive types. data PrimType IntType :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType -- | An informationless type - still takes up space! Unit :: PrimType -- | A floating point type. data FloatType Float16 :: FloatType Float32 :: FloatType Float64 :: FloatType -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A list of all integer types. allIntTypes :: [IntType] -- | A list of all floating-point types. allFloatTypes :: [FloatType] -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | Create an IntValue from a type and an Integer. intValue :: Integral int => IntType -> int -> IntValue -- | The type of an integer value. intValueType :: IntValue -> IntType -- | Convert an IntValue to any Integral type. valueIntegral :: Integral int => IntValue -> int -- | Create a FloatValue from a type and a Rational. floatValue :: Real num => FloatType -> num -> FloatValue -- | The type of a floating-point value. floatValueType :: FloatValue -> FloatType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | A "blank" value of the given primitive type - this is zero, or -- whatever is close to it. Don't depend on this value, but use it for -- e.g. creating arrays to be populated by do-loops. blankPrimValue :: PrimType -> PrimValue -- | A list of all unary operators for all types. allUnOps :: [UnOp] -- | A list of all binary operators for all types. allBinOps :: [BinOp] -- | A list of all comparison operators for all types. allCmpOps :: [CmpOp] -- | A list of all conversion operators for all types. allConvOps :: [ConvOp] -- | Apply an UnOp to an operand. Returns Nothing if the -- application is mistyped. doUnOp :: UnOp -> PrimValue -> Maybe PrimValue -- | E.g., ~(~1) = 1. doComplement :: IntValue -> IntValue -- | abs(-2) = 2. doAbs :: IntValue -> IntValue -- | abs(-2.0) = 2.0. doFAbs :: FloatValue -> FloatValue -- | ssignum(-2) = -1. doSSignum :: IntValue -> IntValue -- | usignum(-2) = -1. doUSignum :: IntValue -> IntValue -- | Apply a BinOp to an operand. Returns Nothing if the -- application is mistyped, or outside the domain (e.g. division by -- zero). doBinOp :: BinOp -> PrimValue -> PrimValue -> Maybe PrimValue -- | Integer addition. doAdd :: IntValue -> IntValue -> IntValue -- | Integer multiplication. doMul :: IntValue -> IntValue -> IntValue -- | Signed integer division. Rounds towards negativity infinity. Note: -- this is different from LLVM. doSDiv :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer modulus; the countepart to SDiv. doSMod :: IntValue -> IntValue -> Maybe IntValue -- | Signed integer exponentatation. doPow :: IntValue -> IntValue -> Maybe IntValue -- | Apply a ConvOp to an operand. Returns Nothing if the -- application is mistyped. doConvOp :: ConvOp -> PrimValue -> Maybe PrimValue -- | Turn the conversion the other way around. Note that most conversions -- are lossy, so there is no guarantee the value will round-trip. flipConvOp :: ConvOp -> ConvOp -- | Zero-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doZExt :: IntValue -> IntType -> IntValue -- | Sign-extend the given integer value to the size of the given type. If -- the type is smaller than the given value, the result is a truncation. doSExt :: IntValue -> IntType -> IntValue -- | Convert the former floating-point type to the latter. doFPConv :: FloatValue -> FloatType -> FloatValue -- | Convert a floating-point value to the nearest unsigned integer -- (rounding towards zero). doFPToUI :: FloatValue -> IntType -> IntValue -- | Convert a floating-point value to the nearest signed integer (rounding -- towards zero). doFPToSI :: FloatValue -> IntType -> IntValue -- | Convert an unsigned integer to a floating-point value. doUIToFP :: IntValue -> FloatType -> FloatValue -- | Convert a signed integer to a floating-point value. doSIToFP :: IntValue -> FloatType -> FloatValue -- | Apply a CmpOp to an operand. Returns Nothing if the -- application is mistyped. doCmpOp :: CmpOp -> PrimValue -> PrimValue -> Maybe Bool -- | Compare any two primtive values for exact equality. doCmpEq :: PrimValue -> PrimValue -> Bool -- | Unsigned less than. doCmpUlt :: IntValue -> IntValue -> Bool -- | Unsigned less than or equal. doCmpUle :: IntValue -> IntValue -> Bool -- | Signed less than. doCmpSlt :: IntValue -> IntValue -> Bool -- | Signed less than or equal. doCmpSle :: IntValue -> IntValue -> Bool -- | Floating-point less than. doFCmpLt :: FloatValue -> FloatValue -> Bool -- | Floating-point less than or equal. doFCmpLe :: FloatValue -> FloatValue -> Bool -- | Translate an IntValue to Word64. This is guaranteed to -- fit. intToWord64 :: IntValue -> Word64 -- | Translate an IntValue to Int64. This is guaranteed to -- fit. intToInt64 :: IntValue -> Int64 -- | The result type of a binary operator. binOpType :: BinOp -> PrimType -- | The operand types of a comparison operator. cmpOpType :: CmpOp -> PrimType -- | The operand and result type of a unary operator. unOpType :: UnOp -> PrimType -- | The input and output types of a conversion operator. convOpType :: ConvOp -> (PrimType, PrimType) -- | A mapping from names of primitive functions to their parameter types, -- their result type, and a function for evaluating them. primFuns :: Map String ([PrimType], PrimType, [PrimValue] -> Maybe PrimValue) -- | Is the given value kind of zero? zeroIsh :: PrimValue -> Bool -- | Is the given value kind of one? oneIsh :: PrimValue -> Bool -- | Is the given value kind of negative? negativeIsh :: PrimValue -> Bool -- | Is the given integer value kind of zero? zeroIshInt :: IntValue -> Bool -- | Is the given integer value kind of one? oneIshInt :: IntValue -> Bool -- | The size of a value of a given primitive type in bites. primBitSize :: PrimType -> Int -- | The size of a value of a given primitive type in eight-bit bytes. primByteSize :: Num a => PrimType -> a -- | The size of a value of a given integer type in eight-bit bytes. intByteSize :: Num a => IntType -> a -- | The size of a value of a given floating-point type in eight-bit bytes. floatByteSize :: Num a => FloatType -> a -- | True if the given binary operator is commutative. commutativeBinOp :: BinOp -> Bool -- | The human-readable name for a ConvOp. This is used to expose -- the ConvOp in the intrinsics module of a Futhark -- program. convOpFun :: ConvOp -> String -- | True if signed. Only makes a difference for integer types. prettySigned :: Bool -> PrimType -> String -- | A name tagged with some integer. Only the integer is used in -- comparisons, no matter the type of vn. data VName VName :: !Name -> !Int -> VName -- | The abstract (not really) type representing names in the Futhark -- compiler. Strings, being lists of characters, are very slow, -- while Texts are based on byte-arrays. data Name -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | The name of the default program entry point (main). defaultEntryPoint :: Name -- | Convert a name to the corresponding list of characters. nameToString :: Name -> String -- | Convert a list of characters to the corresponding name. nameFromString :: String -> Name -- | Convert a name to the corresponding Text. nameToText :: Name -> Text -- | Convert a Text to the corresponding name. nameFromText :: Text -> Name -- | A human-readable location string, of the form -- filename:lineno:columnno. This follows the GNU coding -- standards for error messages: -- https://www.gnu.org/prep/standards/html_node/Errors.html -- -- This function assumes that both start and end position is in the same -- file (it is not clear what the alternative would even mean). locStr :: Located a => a -> String -- | Like locStr, but locStrRel prev now prints the -- location now with the file name left out if the same as -- prev. This is useful when printing messages that are all in -- the context of some initially printed location (e.g. the first mention -- contains the file name; the rest just line and column name). locStrRel :: (Located a, Located b) => a -> b -> String -- | Given a list of strings representing entries in the stack trace and -- the index of the frame to highlight, produce a final -- newline-terminated string for showing to the user. This string should -- also be preceded by a newline. The most recent stack frame must come -- first in the list. prettyStacktrace :: Int -> [String] -> String -- | Return the tag contained in the VName. baseTag :: VName -> Int -- | Return the name contained in the VName. baseName :: VName -> Name -- | Return the base Name converted to a string. baseString :: VName -> String -- | Enclose a string in the prefered quotes used in error messages. These -- are picked to not collide with characters permitted in identifiers. quote :: String -> String -- | As quote, but works on prettyprinted representation. pquote :: Doc -> Doc -- | A part of an error message. data ErrorMsgPart a -- | A literal string. ErrorString :: String -> ErrorMsgPart a -- | A run-time value. ErrorVal :: PrimType -> a -> ErrorMsgPart a -- | An error message is a list of error parts, which are concatenated to -- form the final message. newtype ErrorMsg a ErrorMsg :: [ErrorMsgPart a] -> ErrorMsg a -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is guaranteed -- to complete in constant time. data SubExp Constant :: PrimValue -> SubExp Var :: VName -> SubExp -- | A string representing a specific non-default memory space. type SpaceId = String -- | The memory space of a block. If DefaultSpace, this is the -- "default" space, whatever that is. The exact meaning of the -- SpaceId depends on the backend used. In GPU kernels, for -- example, this is used to distinguish between constant, global and -- shared memory spaces. In GPU-enabled host code, it is used to -- distinguish between host memory (DefaultSpace) and GPU space. data Space DefaultSpace :: Space Space :: SpaceId -> Space -- | A special kind of memory that is a statically sized array of some -- primitive type. Used for private memory on GPUs. ScalarSpace :: [SubExp] -> PrimType -> Space -- | How many non-constant parts does the error message have, and what is -- their type? errorMsgArgTypes :: ErrorMsg a -> [PrimType] -- | Either return precomputed free names stored in the attribute, or the -- freshly computed names. Relies on lazy evaluation to avoid the work. class FreeIn dec => FreeDec dec precomputed :: FreeDec dec => dec -> FV -> FV -- | A class indicating that we can obtain free variable information from -- values of this type. class FreeIn a freeIn' :: FreeIn a => a -> FV -- | A computation to build a free variable set. data FV -- | A set of names. Note that the Ord instance is a dummy that -- treats everything as EQ if ==, and otherwise LT. data Names -- | Retrieve the data structure underlying the names representation. namesIntMap :: Names -> IntMap VName -- | Does the set of names contain this name? nameIn :: VName -> Names -> Bool -- | Construct a name set from a list. Slow. namesFromList :: [VName] -> Names -- | Turn a name set into a list of names. Slow. namesToList :: Names -> [VName] -- | Construct a name set from a single name. oneName :: VName -> Names -- | The intersection of two name sets. namesIntersection :: Names -> Names -> Names -- | Do the two name sets intersect? namesIntersect :: Names -> Names -> Bool -- | Subtract the latter name set from the former. namesSubtract :: Names -> Names -> Names -- | Map over the names in a set. mapNames :: (VName -> VName) -> Names -> Names -- | Consider a variable to be bound in the given FV computation. fvBind :: Names -> FV -> FV -- | Take note of a variable reference. fvName :: VName -> FV -- | Take note of a set of variable references. fvNames :: Names -> FV -- | Return the set of variable names that are free in the given statements -- and result. Filters away the names that are bound by the statements. freeInStmsAndRes :: (FreeIn (Op rep), FreeIn (LetDec rep), FreeIn (LParamInfo rep), FreeIn (FParamInfo rep), FreeDec (BodyDec rep), FreeIn (RetType rep), FreeIn (BranchType rep), FreeDec (ExpDec rep)) => Stms rep -> Result -> FV -- | The free variables of some syntactic construct. freeIn :: FreeIn a => a -> Names -- | The names bound by the bindings immediately in a Body. boundInBody :: Body rep -> Names -- | The names bound by a binding. boundByStm :: Stm rep -> Names -- | The names bound by the bindings. boundByStms :: Stms rep -> Names -- | The names of the lambda parameters plus the index parameter. boundByLambda :: Lambda rep -> [VName] -- | The class of floating-point types that can be used for constructing -- TPrimExps. class NumExp t => FloatExp t -- | Construct a typed expression from a rational. fromRational' :: FloatExp t => Rational -> TPrimExp t v -- | The class of integer types that can be used for constructing -- TPrimExps. class NumExp t => IntExp t -- | The class of numeric types that can be used for constructing -- TPrimExps. class NumExp t -- | Construct a typed expression from an integer. fromInteger' :: NumExp t => Integer -> TPrimExp t v -- | Construct a numeric expression from a boolean expression. This can be -- used to encode arithmetic control flow. fromBoolExp :: NumExp t => TPrimExp Bool v -> TPrimExp t v -- | A PrimExp tagged with a phantom type used to provide type-safe -- construction. Does not guarantee that the underlying expression is -- actually type correct. newtype TPrimExp t v TPrimExp :: PrimExp v -> TPrimExp t v [untyped] :: TPrimExp t v -> PrimExp v -- | A primitive expression parametrised over the representation of free -- variables. Note that the Functor, Traversable, and -- Num instances perform automatic (but simple) constant folding. -- -- Note also that the Num instance assumes OverflowUndef -- semantics! data PrimExp v LeafExp :: v -> PrimType -> PrimExp v ValueExp :: PrimValue -> PrimExp v BinOpExp :: BinOp -> PrimExp v -> PrimExp v -> PrimExp v CmpOpExp :: CmpOp -> PrimExp v -> PrimExp v -> PrimExp v UnOpExp :: UnOp -> PrimExp v -> PrimExp v ConvOpExp :: ConvOp -> PrimExp v -> PrimExp v FunExp :: String -> [PrimExp v] -> PrimType -> PrimExp v -- | This expression is of type Int8. isInt8 :: PrimExp v -> TPrimExp Int8 v -- | This expression is of type Int16. isInt16 :: PrimExp v -> TPrimExp Int16 v -- | This expression is of type Int32. isInt32 :: PrimExp v -> TPrimExp Int32 v -- | This expression is of type Int64. isInt64 :: PrimExp v -> TPrimExp Int64 v -- | This is a boolean expression. isBool :: PrimExp v -> TPrimExp Bool v -- | This expression is of type Half. isF16 :: PrimExp v -> TPrimExp Half v -- | This expression is of type Float. isF32 :: PrimExp v -> TPrimExp Float v -- | This expression is of type Double. isF64 :: PrimExp v -> TPrimExp Double v -- | True if the PrimExp has at least this many nodes. This can be -- much more efficient than comparing with length for large -- PrimExps, as this function is lazy. primExpSizeAtLeast :: Int -> PrimExp v -> Bool -- | Perform quick and dirty constant folding on the top level of a -- PrimExp. This is necessary because we want to consider e.g. equality -- modulo constant folding. constFoldPrimExp :: PrimExp v -> PrimExp v -- | Lifted logical conjunction. (.&&.) :: TPrimExp Bool v -> TPrimExp Bool v -> TPrimExp Bool v infixr 3 .&&. -- | Lifted logical conjunction. (.||.) :: TPrimExp Bool v -> TPrimExp Bool v -> TPrimExp Bool v infixr 2 .||. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .<. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<=.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .<=. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.==.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .==. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .>. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>=.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp Bool v infix 4 .>=. -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.&.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.|.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.^.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.>>.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Lifted bitwise operators. The right-shift is logical, *not* -- arithmetic. (.<<.) :: TPrimExp t v -> TPrimExp t v -> TPrimExp t v -- | Untyped smart constructor for sign extension that does a bit of -- constant folding. sExt :: IntType -> PrimExp v -> PrimExp v -- | Untyped smart constructor for zero extension that does a bit of -- constant folding. zExt :: IntType -> PrimExp v -> PrimExp v -- | Evaluate a PrimExp in the given monad. Invokes fail on -- type errors. evalPrimExp :: (Pretty v, MonadFail m) => (v -> m PrimValue) -> PrimExp v -> m PrimValue -- | The type of values returned by a PrimExp. This function -- returning does not imply that the PrimExp is type-correct. primExpType :: PrimExp v -> PrimType -- | If the given PrimExp is a constant of the wrong integer type, -- coerce it to the given integer type. This is a workaround for an issue -- in the Num instance. coerceIntPrimExp :: IntType -> PrimExp v -> PrimExp v -- | Boolean-valued PrimExps. true :: TPrimExp Bool v -- | Boolean-valued PrimExps. false :: TPrimExp Bool v -- | Boolean negation smart constructor. bNot :: TPrimExp Bool v -> TPrimExp Bool v -- | SMax on 32-bit integers. sMax32 :: TPrimExp Int32 v -> TPrimExp Int32 v -> TPrimExp Int32 v -- | SMin on 32-bit integers. sMin32 :: TPrimExp Int32 v -> TPrimExp Int32 v -> TPrimExp Int32 v -- | SMax on 64-bit integers. sMax64 :: TPrimExp Int64 v -> TPrimExp Int64 v -> TPrimExp Int64 v -- | SMin on 64-bit integers. sMin64 :: TPrimExp Int64 v -> TPrimExp Int64 v -> TPrimExp Int64 v -- | Sign-extend to 32 bit integer. sExt32 :: IntExp t => TPrimExp t v -> TPrimExp Int32 v -- | Sign-extend to 64 bit integer. sExt64 :: IntExp t => TPrimExp t v -> TPrimExp Int64 v -- | Zero-extend to 32 bit integer. zExt32 :: IntExp t => TPrimExp t v -> TPrimExp Int32 v -- | Zero-extend to 64 bit integer. zExt64 :: IntExp t => TPrimExp t v -> TPrimExp Int64 v -- | 64-bit float minimum. fMin64 :: TPrimExp Double v -> TPrimExp Double v -> TPrimExp Double v -- | 64-bit float maximum. fMax64 :: TPrimExp Double v -> TPrimExp Double v -> TPrimExp Double v -- | Produce a mapping from the leaves of the PrimExp to their -- designated types. leafExpTypes :: Ord a => PrimExp a -> Set (a, PrimType) -- | A wrapper supporting a phantom type for indicating what we are -- counting. newtype Count u e Count :: e -> Count u e [unCount] :: Count u e -> e -- | Phantom type for a count of bytes. data Bytes -- | Phantom type for a count of elements. data Elements -- | A function call argument. data Arg ExpArg :: Exp -> Arg MemArg :: VName -> Arg -- | Like Exp, but with a required/known type. type TExp t = TPrimExp t ExpLeaf -- | A side-effect free expression whose execution will produce a single -- primitive value. type Exp = PrimExp ExpLeaf -- | The leaves of an Exp. data ExpLeaf -- | A scalar variable. The type is stored in the LeafExp -- constructor itself. ScalarVar :: VName -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> ExpLeaf -- | The volatility of a memory access or variable. Feel free to ignore -- this for backends where it makes no sense (anything but C and similar -- low-level things) data Volatility Volatile :: Volatility Nonvolatile :: Volatility -- | Log the given message, *without* a trailing linebreak (unless part of -- the mssage). pattern TracePrint :: () => ErrorMsg Exp -> Code a -- | Print the given value to the screen, somehow annotated with the given -- string as a description. If no type/value pair, just print the string. -- This has no semantic meaning, but is used entirely for debugging. Code -- generators are free to ignore this statement. pattern DebugPrint :: () => String -> Maybe Exp -> Code a -- | Must be in same space. pattern SetMem :: () => VName -> VName -> Space -> Code a -- | Set a scalar variable. pattern SetScalar :: () => VName -> Exp -> Code a -- | Create an array containing the given values. The lifetime of the array -- will be the entire application. This is mostly used for constant -- arrays, but also for some bookkeeping data, like the synchronisation -- counts used to implement reduction. pattern DeclareArray :: () => VName -> Space -> PrimType -> ArrayContents -> Code a -- | Declare a scalar variable with an initially undefined value. pattern DeclareScalar :: () => VName -> Volatility -> PrimType -> Code a -- | Declare a memory block variable that will point to memory in the given -- memory space. Note that this is distinct from allocation. The memory -- block must be the target of either an Allocate or a -- SetMem before it can be used for reading or writing. pattern DeclareMem :: () => VName -> Space -> Code a -- | Statement composition. Crucial for the Semigroup instance. pattern (:>>:) :: () => Code a -> Code a -> Code a -- | Assert that something must be true. Should it turn out not to be true, -- then report a failure along with the given error message. pattern Assert :: () => Exp -> ErrorMsg Exp -> (SrcLoc, [SrcLoc]) -> Code a -- | Function call. The results are written to the provided VName -- variables. pattern Call :: () => [VName] -> Name -> [Arg] -> Code a -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. pattern Copy :: () => VName -> Count Bytes (TExp Int64) -> Space -> VName -> Count Bytes (TExp Int64) -> Space -> Count Bytes (TExp Int64) -> Code a -- | Memory space must match the corresponding DeclareMem. pattern Allocate :: () => VName -> Count Bytes (TExp Int64) -> Space -> Code a -- | No-op. Crucial for the Monoid instance. pattern Skip :: () => Code a -- | A for-loop iterating the given number of times. The loop parameter -- starts counting from zero and will have the same (integer) type as the -- bound. The bound is evaluated just once, before the loop is entered. pattern For :: () => VName -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. pattern While :: () => TExp Bool -> Code a -> Code a -- | Indicate that some memory block will never again be referenced via the -- indicated variable. However, it may still be accessed through aliases. -- It is only safe to actually deallocate the memory block if this is the -- last reference. There is no guarantee that all memory blocks will be -- freed with this statement. Backends are free to ignore it entirely. pattern Free :: () => VName -> Space -> Code a -- | Has the same semantics as the contained code, but the comment should -- show up in generated code for ease of inspection. pattern Comment :: () => String -> Code a -> Code a -- | Write mem i t space vol v writes the value v to -- mem offset by i elements of type t. The -- Space argument is the memory space of mem (technically -- redundant, but convenient). Note that reading is done with an -- Exp (Index). pattern Write :: () => VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -> Code a -- | Conditional execution. pattern If :: () => TExp Bool -> Code a -> Code a -> Code a -- | Perform an extensible operation. pattern Op :: () => a -> Code a -- | The contents of a statically declared constant array. Such arrays are -- always unidimensional, and reshaped if necessary in the code that uses -- them. data ArrayContents -- | Precisely these values. ArrayValues :: [PrimValue] -> ArrayContents -- | This many zeroes. ArrayZeros :: Int -> ArrayContents -- | A imperative function, containing the body as well as its low-level -- inputs and outputs, as well as its high-level arguments and results. -- The latter are only used if the function is an entry point. data FunctionT a -- | ^ An externally visible value. This can be an opaque value (covering -- several physical internal values), or a single value that can be used -- externally. We record the uniqueness because it is important to the -- external interface as well. data ExternalValue -- | The string is a human-readable description with no other semantics. -- not matter. OpaqueValue :: Uniqueness -> String -> [ValueDesc] -> ExternalValue TransparentValue :: Uniqueness -> ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block memory space, element type, signedness of -- element type (if applicable), and shape. ArrayValue :: VName -> Space -> PrimType -> Signedness -> [DimSize] -> ValueDesc -- | A scalar value with signedness if applicable. ScalarValue :: PrimType -> Signedness -> VName -> ValueDesc -- | Since the core language does not care for signedness, but the source -- language does, entry point input/output information has metadata for -- integer types (and arrays containing these) that indicate whether they -- are really unsigned integers. data Signedness TypeUnsigned :: Signedness TypeDirect :: Signedness -- | A collection of imperative constants. data Constants a Constants :: [Param] -> Code a -> Constants a -- | The constants that are made available to the functions. [constsDecl] :: Constants a -> [Param] -- | Setting the value of the constants. Note that this must not contain -- declarations of the names defined in constsDecl. [constsInit] :: Constants a -> Code a -- | A collection of imperative functions. newtype Functions a Functions :: [(Name, Function a)] -> Functions a -- | A collection of imperative functions and constants. data Definitions a Definitions :: Constants a -> Functions a -> Definitions a [defConsts] :: Definitions a -> Constants a [defFuns] :: Definitions a -> Functions a -- | An ImpCode function parameter. data Param MemParam :: VName -> Space -> Param ScalarParam :: VName -> PrimType -> Param -- | The size of an array. type DimSize = SubExp -- | The size of a memory block. type MemSize = SubExp -- | The name of a parameter. paramName :: Param -> VName -- | Find those memory blocks that are used only lexically. That is, are -- not used as the source or target of a SetMem, or are the result -- of the function, nor passed as arguments to other functions. This is -- interesting because such memory blocks do not need reference counting, -- but can be managed in a purely stack-like fashion. -- -- We do not look inside any Ops. We assume that no Op is -- going to SetMem a memory block declared outside it. lexicalMemoryUsage :: Function a -> Map VName Space -- | The set of functions that are called by this code. Assumes there are -- no function calls in Ops. calledFuncs :: Code a -> Set Name -- | This expression counts elements. elements :: a -> Count Elements a -- | This expression counts bytes. bytes :: a -> Count Bytes a -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements (TExp Int64) -> PrimType -> Count Bytes (TExp Int64) -- | Turn a VName into a ScalarVar. var :: VName -> PrimType -> Exp -- | Turn a VName into a Int32 ScalarVar. vi32 :: VName -> TExp Int32 -- | Turn a VName into a Int64 ScalarVar. vi64 :: VName -> TExp Int64 -- | Concise wrapper for using Index. index :: VName -> Count Elements (TExp Int64) -> PrimType -> Space -> Volatility -> Exp -- | The names declared with DeclareMem, DeclareScalar, and -- DeclareArray in the given code. declaredIn :: Code a -> Names instance GHC.Show.Show Futhark.CodeGen.ImpCode.GPU.KernelConst instance GHC.Classes.Ord Futhark.CodeGen.ImpCode.GPU.KernelConst instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.GPU.KernelConst instance GHC.Show.Show Futhark.CodeGen.ImpCode.GPU.KernelUse instance GHC.Classes.Ord Futhark.CodeGen.ImpCode.GPU.KernelUse instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.GPU.KernelUse instance GHC.Show.Show Futhark.CodeGen.ImpCode.GPU.Fence instance GHC.Show.Show Futhark.CodeGen.ImpCode.GPU.AtomicOp instance GHC.Show.Show Futhark.CodeGen.ImpCode.GPU.KernelOp instance GHC.Show.Show Futhark.CodeGen.ImpCode.GPU.Kernel instance GHC.Show.Show Futhark.CodeGen.ImpCode.GPU.HostOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.GPU.HostOp instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.GPU.HostOp instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.GPU.Kernel instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.GPU.Kernel instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.GPU.KernelOp instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.GPU.KernelOp instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.GPU.AtomicOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.GPU.KernelUse instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.GPU.KernelConst -- | Carefully optimised implementations of GPU transpositions. Written in -- ImpCode so we can compile it to both CUDA and OpenCL. module Futhark.CodeGen.ImpGen.GPU.Transpose -- | Which form of transposition to generate code for. data TransposeType TransposeNormal :: TransposeType TransposeLowWidth :: TransposeType TransposeLowHeight :: TransposeType -- | For small arrays that do not benefit from coalescing. TransposeSmall :: TransposeType -- | The types of the arguments accepted by a transposition function. type TransposeArgs = (VName, TExp Int32, VName, TExp Int32, TExp Int32, TExp Int32, TExp Int32, TExp Int32, TExp Int32, VName) -- | Generate a transpose kernel. There is special support to handle input -- arrays with low width, low height, or both. -- -- Normally when transposing a [2][n] array we would use a -- FUT_BLOCK_DIM x FUT_BLOCK_DIM group to process a -- [2][FUT_BLOCK_DIM] slice of the input array. This would mean -- that many of the threads in a group would be inactive. We try to -- remedy this by using a special kernel that will process a larger part -- of the input, by using more complex indexing. In our example, we could -- use all threads in a group if we are processing -- (2/FUT_BLOCK_DIM) as large a slice of each rows per group. -- The variable mulx contains this factor for the kernel to -- handle input arrays with low height. -- -- See issue #308 on GitHub for more details. -- -- These kernels are optimized to ensure all global reads and writes are -- coalesced, and to avoid bank conflicts in shared memory. Each thread -- group transposes a 2D tile of block_dim*2 by block_dim*2 elements. The -- size of a thread group is block_dim/2 by block_dim*2, meaning that -- each thread will process 4 elements in a 2D tile. The shared memory -- array containing the 2D tile consists of block_dim*2 by block_dim*2+1 -- elements. Padding each row with an additional element prevents bank -- conflicts from occuring when the tile is accessed column-wise. mapTransposeKernel :: String -> Integer -> TransposeArgs -> PrimType -> TransposeType -> Kernel instance GHC.Show.Show Futhark.CodeGen.ImpGen.GPU.Transpose.TransposeType instance GHC.Classes.Ord Futhark.CodeGen.ImpGen.GPU.Transpose.TransposeType instance GHC.Classes.Eq Futhark.CodeGen.ImpGen.GPU.Transpose.TransposeType -- | Simple C runtime representation. -- -- Most types use the same memory and scalar variable representation. For -- those that do not (as of this writing, only Float16), we use -- primStorageType for the array element representation, and -- primTypeToCType for their scalar representation. Use -- toStorage and fromStorage to convert back and forth. module Futhark.CodeGen.Backends.SimpleRep -- | tupleField i is the name of field number i in a -- tuple. tupleField :: Int -> String -- | funName f is the name of the C function corresponding to the -- Futhark function f. funName :: Name -> String -- | The type of memory blocks in the default memory space. defaultMemBlockType :: Type -- | The C type corresponding to a signed integer type. intTypeToCType :: IntType -> Type -- | The C type corresponding to a primitive type. Integers are assumed to -- be unsigned. primTypeToCType :: PrimType -> Type -- | The C storage type for arrays of this primitive type. primStorageType :: PrimType -> Type -- | The C API corresponding to a primitive type. Integers are assumed to -- have the specified sign. primAPIType :: Signedness -> PrimType -> Type -- | The name of exposed array type structs. arrayName :: PrimType -> Signedness -> Int -> String -- | The name of exposed opaque types. opaqueName :: String -> [ValueDesc] -> String -- | The type used to expose a Futhark value in the C API. A pointer in the -- case of arrays and opaques. externalValueType :: ExternalValue -> Type -- | Convert from scalar to storage representation for the given type. toStorage :: PrimType -> Exp -> Exp -- | Convert from storage to scalar representation for the given type. fromStorage :: PrimType -> Exp -> Exp -- | Return an expression multiplying together the given expressions. If an -- empty list is given, the expression 1 is returned. cproduct :: [Exp] -> Exp -- | Return an expression summing the given expressions. If an empty list -- is given, the expression 0 is returned. csum :: [Exp] -> Exp -- | Implementations of scalar operations. cScalarDefs :: Text storageSize :: PrimType -> Int -> Exp -> Exp storeValueHeader :: Signedness -> PrimType -> Int -> Exp -> Exp -> [Stm] loadValueHeader :: Signedness -> PrimType -> Int -> Exp -> Exp -> [Stm] instance Language.C.Quote.Base.ToIdent Language.Futhark.Core.Name instance Language.C.Quote.Base.ToIdent Language.Futhark.Core.VName instance Language.C.Quote.Base.ToExp Language.Futhark.Core.VName instance Language.C.Quote.Base.ToExp Futhark.IR.Primitive.IntValue instance Language.C.Quote.Base.ToExp Futhark.IR.Primitive.FloatValue instance Language.C.Quote.Base.ToExp Futhark.IR.Primitive.PrimValue instance Language.C.Quote.Base.ToExp Futhark.IR.Syntax.Core.SubExp -- | Code generation for server executables. module Futhark.CodeGen.Backends.GenericC.Server -- | Generate Futhark server executable code. serverDefs :: [Option] -> Functions a -> Text -- | Code generation for standalone executables. module Futhark.CodeGen.Backends.GenericC.CLI -- | Generate Futhark standalone executable code. cliDefs :: [Option] -> Functions a -> Text -- | C code generator framework. module Futhark.CodeGen.Backends.GenericC -- | Compile imperative program to a C program. Always uses the function -- named "main" as entry point, so make sure it is defined. compileProg :: MonadFreshNames m => Text -> Operations op () -> CompilerM op () () -> Text -> [Space] -> [Option] -> Definitions op -> m CParts -- | The result of compilation to C is multiple parts, which can be put -- together in various ways. The obvious way is to concatenate all of -- them, which yields a CLI program. Another is to compile the library -- part by itself, and use the header file to call into it. data CParts CParts :: Text -> Text -> Text -> Text -> Text -> CParts [cHeader] :: CParts -> Text -- | Utility definitions that must be visible to both CLI and library -- parts. [cUtils] :: CParts -> Text [cCLI] :: CParts -> Text [cServer] :: CParts -> Text [cLib] :: CParts -> Text -- | Produce header and implementation files. asLibrary :: CParts -> (Text, Text) -- | As executable with command-line interface. asExecutable :: CParts -> Text -- | As server executable. asServer :: CParts -> Text data Operations op s Operations :: WriteScalar op s -> ReadScalar op s -> Allocate op s -> Deallocate op s -> Copy op s -> StaticArray op s -> MemoryType op s -> OpCompiler op s -> ErrorCompiler op s -> CallCompiler op s -> Bool -> ([BlockItem], [BlockItem]) -> Operations op s [opsWriteScalar] :: Operations op s -> WriteScalar op s [opsReadScalar] :: Operations op s -> ReadScalar op s [opsAllocate] :: Operations op s -> Allocate op s [opsDeallocate] :: Operations op s -> Deallocate op s [opsCopy] :: Operations op s -> Copy op s [opsStaticArray] :: Operations op s -> StaticArray op s [opsMemoryType] :: Operations op s -> MemoryType op s [opsCompiler] :: Operations op s -> OpCompiler op s [opsError] :: Operations op s -> ErrorCompiler op s [opsCall] :: Operations op s -> CallCompiler op s -- | If true, use reference counting. Otherwise, bare pointers. [opsFatMemory] :: Operations op s -> Bool -- | Code to bracket critical sections. [opsCritical] :: Operations op s -> ([BlockItem], [BlockItem]) -- | A set of operations that fail for every operation involving -- non-default memory spaces. Uses plain pointers and malloc for -- memory management. defaultOperations :: Operations op s -- | A substitute expression compiler, tried before the main compilation -- function. type OpCompiler op s = op -> CompilerM op s () type ErrorCompiler op s = ErrorMsg Exp -> String -> CompilerM op s () -- | Call a function. type CallCompiler op s = [VName] -> Name -> [Exp] -> CompilerM op s () -- | The address space qualifiers for a pointer of the given type with the -- given annotation. type PointerQuals op s = String -> CompilerM op s [TypeQual] -- | The type of a memory block in the given memory space. type MemoryType op s = SpaceId -> CompilerM op s Type -- | Write a scalar to the given memory block with the given element index -- and in the given memory space. type WriteScalar op s = Exp -> Exp -> Type -> SpaceId -> Volatility -> Exp -> CompilerM op s () writeScalarPointerWithQuals :: PointerQuals op s -> WriteScalar op s -- | Read a scalar from the given memory block with the given element index -- and in the given memory space. type ReadScalar op s = Exp -> Exp -> Type -> SpaceId -> Volatility -> CompilerM op s Exp readScalarPointerWithQuals :: PointerQuals op s -> ReadScalar op s -- | Allocate a memory block of the given size and with the given tag in -- the given memory space, saving a reference in the given variable name. type Allocate op s = Exp -> Exp -> Exp -> SpaceId -> CompilerM op s () -- | De-allocate the given memory block with the given tag, which is in the -- given memory space. type Deallocate op s = Exp -> Exp -> SpaceId -> CompilerM op s () -- | Copy from one memory block to another. type Copy op s = Exp -> Exp -> Space -> Exp -> Exp -> Space -> Exp -> CompilerM op s () -- | Create a static array of values - initialised at load time. type StaticArray op s = VName -> SpaceId -> PrimType -> ArrayContents -> CompilerM op s () data CompilerM op s a data CompilerState s getUserState :: CompilerM op s s modifyUserState :: (s -> s) -> CompilerM op s () contextContents :: CompilerM op s ([FieldGroup], [Stm]) contextFinalInits :: CompilerM op s [Stm] runCompilerM :: Operations op s -> VNameSource -> s -> CompilerM op s a -> (a, CompilerState s) -- | Used when we, inside an existing CompilerM action, want to -- generate code for a new function. Use this so that the compiler -- understands that previously declared memory doesn't need to be freed -- inside this action. inNewFunction :: Bool -> CompilerM op s a -> CompilerM op s a cachingMemory :: Map VName Space -> ([BlockItem] -> [Stm] -> CompilerM op s a) -> CompilerM op s a blockScope :: CompilerM op s () -> CompilerM op s [BlockItem] compileFun :: [BlockItem] -> [Param] -> (Name, Function op) -> CompilerM op s (Definition, Func) compileCode :: Code op -> CompilerM op s () compileExp :: Exp -> CompilerM op s Exp -- | Tell me how to compile a v, and I'll Compile any PrimExp -- v for you. compilePrimExp :: Monad m => (v -> m Exp) -> PrimExp v -> m Exp compileExpToName :: String -> PrimType -> Exp -> CompilerM op s VName rawMem :: VName -> CompilerM op s Exp item :: BlockItem -> CompilerM op s () items :: [BlockItem] -> CompilerM op s () stm :: Stm -> CompilerM op s () stms :: [Stm] -> CompilerM op s () decl :: InitGroup -> CompilerM op s () atInit :: Stm -> CompilerM op s () headerDecl :: HeaderSection -> Definition -> CompilerM op s () -- | Construct a publicly visible definition using the specified name as -- the template. The first returned definition is put in the header file, -- and the second is the implementation. Returns the public name. publicDef :: String -> HeaderSection -> (String -> (Definition, Definition)) -> CompilerM op s String -- | As publicDef, but ignores the public name. publicDef_ :: String -> HeaderSection -> (String -> (Definition, Definition)) -> CompilerM op s () profileReport :: BlockItem -> CompilerM op s () onClear :: BlockItem -> CompilerM op s () -- | In which part of the header file we put the declaration. This is to -- ensure that the header file remains structured and readable. data HeaderSection ArrayDecl :: String -> HeaderSection OpaqueDecl :: String -> HeaderSection EntryDecl :: HeaderSection MiscDecl :: HeaderSection InitDecl :: HeaderSection libDecl :: Definition -> CompilerM op s () earlyDecl :: Definition -> CompilerM op s () -- | Public names must have a consitent prefix. publicName :: String -> CompilerM op s String -- | The generated code must define a struct with this name. contextType :: CompilerM op s Type contextField :: Id -> Type -> Maybe Exp -> CompilerM op s () memToCType :: VName -> Space -> CompilerM op s Type cacheMem :: ToExp a => a -> CompilerM op s (Maybe VName) fatMemory :: Space -> CompilerM op s Bool rawMemCType :: Space -> CompilerM op s Type -- | Return an expression multiplying together the given expressions. If an -- empty list is given, the expression 1 is returned. cproduct :: [Exp] -> Exp fatMemType :: Space -> Type -- | The C type corresponding to a primitive type. Integers are assumed to -- be unsigned. primTypeToCType :: PrimType -> Type -- | The C type corresponding to a signed integer type. intTypeToCType :: IntType -> Type copyMemoryDefaultSpace :: Exp -> Exp -> Exp -> Exp -> Exp -> CompilerM op s () instance GHC.Show.Show Futhark.CodeGen.Backends.GenericC.Publicness instance GHC.Classes.Ord Futhark.CodeGen.Backends.GenericC.Publicness instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericC.Publicness instance GHC.Classes.Ord Futhark.CodeGen.Backends.GenericC.HeaderSection instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericC.HeaderSection instance Control.Monad.Reader.Class.MonadReader (Futhark.CodeGen.Backends.GenericC.CompilerEnv op s) (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance Control.Monad.State.Class.MonadState (Futhark.CodeGen.Backends.GenericC.CompilerState s) (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance GHC.Base.Monad (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance GHC.Base.Applicative (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance GHC.Base.Functor (Futhark.CodeGen.Backends.GenericC.CompilerM op s) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.CodeGen.Backends.GenericC.CompilerM op s) -- | This module defines a translation from imperative code with kernels to -- imperative code with OpenCL calls. module Futhark.CodeGen.ImpGen.GPU.ToOpenCL kernelsToOpenCL :: Program -> Program kernelsToCUDA :: Program -> Program instance GHC.Classes.Eq Futhark.CodeGen.ImpGen.GPU.ToOpenCL.OpsMode module Futhark.CodeGen.Backends.SequentialC.Boilerplate generateBoilerplate :: CompilerM op s () module Futhark.CodeGen.Backends.GenericWASM -- | The result of compilation to C is multiple parts, which can be put -- together in various ways. The obvious way is to concatenate all of -- them, which yields a CLI program. Another is to compile the library -- part by itself, and use the header file to call into it. data CParts CParts :: Text -> Text -> Text -> Text -> Text -> CParts [cHeader] :: CParts -> Text -- | Utility definitions that must be visible to both CLI and library -- parts. [cUtils] :: CParts -> Text [cCLI] :: CParts -> Text [cServer] :: CParts -> Text [cLib] :: CParts -> Text -- | Produce header and implementation files. asLibrary :: CParts -> (Text, Text) -- | As executable with command-line interface. asExecutable :: CParts -> Text -- | As server executable. asServer :: CParts -> Text data JSEntryPoint JSEntryPoint :: String -> [EntryPointType] -> [EntryPointType] -> JSEntryPoint [name] :: JSEntryPoint -> String [parameters] :: JSEntryPoint -> [EntryPointType] [ret] :: JSEntryPoint -> [EntryPointType] emccExportNames :: [JSEntryPoint] -> [String] javascriptWrapper :: [JSEntryPoint] -> Text extToString :: ExternalValue -> String runServer :: Text libraryExports :: Text module Futhark.CodeGen.Backends.COpenCL.Boilerplate -- | Called after most code has been generated to generate the bulk of the -- boilerplate. generateBoilerplate :: Text -> Text -> [Name] -> Map KernelName KernelSafety -> [PrimType] -> Map Name SizeClass -> [FailureMsg] -> CompilerM OpenCL () () profilingEvent :: Name -> Exp copyDevToDev :: Name copyDevToHost :: Name copyHostToDev :: Name copyScalarToDev :: Name copyScalarFromDev :: Name commonOptions :: [Option] failureSwitch :: [FailureMsg] -> Stm costCentreReport :: [Name] -> [BlockItem] kernelRuntime :: KernelName -> Name kernelRuns :: KernelName -> Name sizeLoggingCode :: VName -> Name -> Exp -> CompilerM op () () -- | Various boilerplate definitions for the CUDA backend. module Futhark.CodeGen.Backends.CCUDA.Boilerplate -- | Called after most code has been generated to generate the bulk of the -- boilerplate. generateBoilerplate :: Text -> Text -> [Name] -> Map KernelName KernelSafety -> Map Name SizeClass -> [FailureMsg] -> CompilerM OpenCL () () -- | Block items to put before and after a thing to be profiled. profilingEnclosure :: Name -> ([BlockItem], [BlockItem]) failureSwitch :: [FailureMsg] -> Stm copyDevToDev :: Name copyDevToHost :: Name copyHostToDev :: Name copyScalarToDev :: Name copyScalarFromDev :: Name kernelRuntime :: KernelName -> Name kernelRuns :: KernelName -> Name costCentreReport :: [Name] -> [BlockItem] module Futhark.CodeGen.Backends.GenericPython.AST data PyExp Integer :: Integer -> PyExp Bool :: Bool -> PyExp Float :: Double -> PyExp String :: String -> PyExp RawStringLiteral :: Text -> PyExp Var :: String -> PyExp BinOp :: String -> PyExp -> PyExp -> PyExp UnOp :: String -> PyExp -> PyExp Cond :: PyExp -> PyExp -> PyExp -> PyExp Index :: PyExp -> PyIdx -> PyExp Call :: PyExp -> [PyArg] -> PyExp Cast :: PyExp -> String -> PyExp Tuple :: [PyExp] -> PyExp List :: [PyExp] -> PyExp Field :: PyExp -> String -> PyExp Dict :: [(PyExp, PyExp)] -> PyExp Lambda :: String -> PyExp -> PyExp None :: PyExp data PyIdx IdxRange :: PyExp -> PyExp -> PyIdx IdxExp :: PyExp -> PyIdx data PyArg ArgKeyword :: String -> PyExp -> PyArg Arg :: PyExp -> PyArg data PyStmt If :: PyExp -> [PyStmt] -> [PyStmt] -> PyStmt Try :: [PyStmt] -> [PyExcept] -> PyStmt While :: PyExp -> [PyStmt] -> PyStmt For :: String -> PyExp -> [PyStmt] -> PyStmt With :: PyExp -> [PyStmt] -> PyStmt Assign :: PyExp -> PyExp -> PyStmt AssignOp :: String -> PyExp -> PyExp -> PyStmt Comment :: String -> [PyStmt] -> PyStmt Assert :: PyExp -> PyExp -> PyStmt Raise :: PyExp -> PyStmt Exp :: PyExp -> PyStmt Return :: PyExp -> PyStmt Pass :: PyStmt Import :: String -> Maybe String -> PyStmt FunDef :: PyFunDef -> PyStmt ClassDef :: PyClassDef -> PyStmt Escape :: Text -> PyStmt newtype PyProg PyProg :: [PyStmt] -> PyProg data PyExcept Catch :: PyExp -> [PyStmt] -> PyExcept data PyFunDef Def :: String -> [String] -> [PyStmt] -> PyFunDef data PyClassDef Class :: String -> [PyStmt] -> PyClassDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.UnOp instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.UnOp instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyIdx instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyIdx instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyExp instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyExp instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyArg instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyArg instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyExcept instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyExcept instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyFunDef instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyFunDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyStmt instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyStmt instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyClassDef instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyClassDef instance GHC.Show.Show Futhark.CodeGen.Backends.GenericPython.AST.PyProg instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericPython.AST.PyProg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyProg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyStmt instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyFunDef instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyClassDef instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyExcept instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyIdx instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyArg instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.Backends.GenericPython.AST.PyExp -- | This module defines a generator for getopt based command line -- argument parsing. Each option is associated with arbitrary Python code -- that will perform side effects, usually by setting some global -- variables. module Futhark.CodeGen.Backends.GenericPython.Options -- | Specification if a single command line option. The option must have a -- long name, and may also have a short name. -- -- When the statement is being executed, the argument (if any) will be -- stored in the variable optarg. data Option Option :: String -> Maybe Char -> OptionArgument -> [PyStmt] -> Option [optionLongName] :: Option -> String [optionShortName] :: Option -> Maybe Char [optionArgument] :: Option -> OptionArgument [optionAction] :: Option -> [PyStmt] -- | Whether an option accepts an argument. data OptionArgument NoArgument :: OptionArgument RequiredArgument :: String -> OptionArgument OptionalArgument :: OptionArgument -- | Generate option parsing code that accepts the given command line -- options. Will read from sys.argv. -- -- If option parsing fails for any reason, the entire process will -- terminate with error code 1. generateOptionParser :: [Option] -> [PyStmt] -- | The Futhark Prelude Library embedded embedded as strings read during -- compilation of the Futhark compiler. The advantage is that the prelude -- can be accessed without reading it from disk, thus saving users from -- include path headaches. module Language.Futhark.Prelude -- | Prelude embedded as Text values, one for every file. prelude :: [(FilePath, Text)] -- | The Futhark source language AST definition. Many types, such as -- ExpBase, are parametrised by type and name representation. -- E.g. in a value of type ExpBase f vn, annotations are wrapped -- in the functor f, and all names are of type vn. See -- the https://futhark.readthedocs.org@ for a language -- reference, or this module may be a little hard to understand. module Language.Futhark.Syntax -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | The uniqueness attribute of a type. This essentially indicates whether -- or not in-place modifications are acceptable. With respect to -- ordering, Unique is greater than Nonunique. data Uniqueness -- | May have references outside current function. Nonunique :: Uniqueness -- | No references outside current function. Unique :: Uniqueness -- | An integer type, ordered by size. Note that signedness is not a -- property of the type, but a property of the operations performed on -- values of these types. data IntType Int8 :: IntType Int16 :: IntType Int32 :: IntType Int64 :: IntType -- | A floating point type. data FloatType Float16 :: FloatType Float32 :: FloatType Float64 :: FloatType -- | Low-level primitive types. data PrimType Signed :: IntType -> PrimType Unsigned :: IntType -> PrimType FloatType :: FloatType -> PrimType Bool :: PrimType -- | A type class for things that can be array dimensions. class Eq dim => ArrayDim dim -- | unifyDims x y combines x and y to contain -- their maximum common information, and fails if they conflict. unifyDims :: ArrayDim dim => dim -> dim -> Maybe dim -- | Declaration of a dimension size. data DimDecl vn -- | The size of the dimension is this name, which must be in scope. In a -- return type, this will give rise to an assertion. NamedDim :: QualName vn -> DimDecl vn -- | The size is a constant. ConstDim :: Int -> DimDecl vn -- | No known size - but still possibly given a unique name, so we can -- recognise e.g. type square [n] = [n][n]i32 and make -- square [] do the right thing. If Nothing, then this -- is a name distinct from any other. AnyDim :: Maybe vn -> DimDecl vn -- | The size of an array type is a list of its dimension sizes. If -- Nothing, that dimension is of a (statically) unknown size. newtype ShapeDecl dim ShapeDecl :: [dim] -> ShapeDecl dim [shapeDims] :: ShapeDecl dim -> [dim] -- | The number of dimensions contained in a shape. shapeRank :: ShapeDecl dim -> Int -- | stripDims n shape strips the outer n dimensions from -- shape, returning Nothing if this would result in zero -- or fewer dimensions. stripDims :: Int -> ShapeDecl dim -> Maybe (ShapeDecl dim) -- | A type name consists of qualifiers (for error messages) and a -- VName (for equality checking). data TypeName TypeName :: [VName] -> VName -> TypeName [typeQuals] :: TypeName -> [VName] [typeLeaf] :: TypeName -> VName -- | Convert a QualName to a TypeName. typeNameFromQualName :: QualName VName -> TypeName -- | Convert a TypeName to a QualName. qualNameFromTypeName :: TypeName -> QualName VName -- | An expanded Futhark type is either an array, or something that can be -- an element of an array. When comparing types for equality, function -- parameter names are ignored. This representation permits some -- malformed types (arrays of functions), but importantly rules out -- arrays-of-arrays. data TypeBase dim as Scalar :: ScalarTypeBase dim as -> TypeBase dim as Array :: as -> Uniqueness -> ScalarTypeBase dim () -> ShapeDecl dim -> TypeBase dim as -- | An argument passed to a type constructor. data TypeArg dim TypeArgDim :: dim -> SrcLoc -> TypeArg dim TypeArgType :: TypeBase dim () -> SrcLoc -> TypeArg dim -- | A dimension declaration expression for use in a TypeExp. data DimExp vn -- | The size of the dimension is this name, which must be in scope. DimExpNamed :: QualName vn -> SrcLoc -> DimExp vn -- | The size is a constant. DimExpConst :: Int -> SrcLoc -> DimExp vn -- | No dimension declaration. DimExpAny :: DimExp vn -- | An unstructured type with type variables and possibly shape -- declarations - this is what the user types in the source program. -- These are used to construct TypeBases in the type checker. data TypeExp vn TEVar :: QualName vn -> SrcLoc -> TypeExp vn TETuple :: [TypeExp vn] -> SrcLoc -> TypeExp vn TERecord :: [(Name, TypeExp vn)] -> SrcLoc -> TypeExp vn TEArray :: TypeExp vn -> DimExp vn -> SrcLoc -> TypeExp vn TEUnique :: TypeExp vn -> SrcLoc -> TypeExp vn TEApply :: TypeExp vn -> TypeArgExp vn -> SrcLoc -> TypeExp vn TEArrow :: Maybe vn -> TypeExp vn -> TypeExp vn -> SrcLoc -> TypeExp vn TESum :: [(Name, [TypeExp vn])] -> SrcLoc -> TypeExp vn -- | A type argument expression passed to a type constructor. data TypeArgExp vn TypeArgExpDim :: DimExp vn -> SrcLoc -> TypeArgExp vn TypeArgExpType :: TypeExp vn -> TypeArgExp vn -- | The name (if any) of a function parameter. The Eq and -- Ord instances always compare values of this type equal. data PName Named :: VName -> PName Unnamed :: PName -- | Types that can be elements of arrays. This representation does allow -- arrays of records of functions, which is nonsensical, but it -- convolutes the code too much if we try to statically rule it out. data ScalarTypeBase dim as Prim :: PrimType -> ScalarTypeBase dim as TypeVar :: as -> Uniqueness -> TypeName -> [TypeArg dim] -> ScalarTypeBase dim as Record :: Map Name (TypeBase dim as) -> ScalarTypeBase dim as Sum :: Map Name [TypeBase dim as] -> ScalarTypeBase dim as -- | The aliasing corresponds to the lexical closure of the function. Arrow :: as -> PName -> TypeBase dim as -> TypeBase dim as -> ScalarTypeBase dim as -- | A type with aliasing information and shape annotations, used for -- describing the type patterns and expressions. type PatType = TypeBase (DimDecl VName) Aliasing -- | A "structural" type with shape annotations and no aliasing -- information, used for declarations. type StructType = TypeBase (DimDecl VName) () -- | A value type contains full, manifest size information. type ValueType = TypeBase Int64 () -- | Information about which parts of a value/type are consumed. data Diet -- | Consumes these fields in the record. RecordDiet :: Map Name Diet -> Diet -- | A function that consumes its argument(s) like this. The final -- Diet should always be Observe, as there is no way for a -- function to consume its return value. FuncDiet :: Diet -> Diet -> Diet -- | Consumes this value. Consume :: Diet -- | Only observes value in this position, does not consume. Observe :: Diet -- | A declaration of the type of something. data TypeDeclBase f vn TypeDecl :: TypeExp vn -> f StructType -> TypeDeclBase f vn -- | The type declared by the user. [declaredType] :: TypeDeclBase f vn -> TypeExp vn -- | The type deduced by the type checker. [expandedType] :: TypeDeclBase f vn -> f StructType -- | An integer value. data IntValue Int8Value :: !Int8 -> IntValue Int16Value :: !Int16 -> IntValue Int32Value :: !Int32 -> IntValue Int64Value :: !Int64 -> IntValue -- | A floating-point value. data FloatValue Float16Value :: !Half -> FloatValue Float32Value :: !Float -> FloatValue Float64Value :: !Double -> FloatValue -- | Non-array values. data PrimValue SignedValue :: !IntValue -> PrimValue UnsignedValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | A class for converting ordinary Haskell values to primitive Futhark -- values. class IsPrimValue v primValue :: IsPrimValue v => v -> PrimValue -- | Simple Futhark values. Values are fully evaluated and their type is -- always unambiguous. data Value PrimValue :: !PrimValue -> Value -- | It is assumed that the array is 0-indexed. The type is the full type. ArrayValue :: !Array Int Value -> ValueType -> Value -- | The payload of an attribute. data AttrInfo AttrAtom :: Name -> AttrInfo AttrComp :: Name -> [AttrInfo] -> AttrInfo -- | Default binary operators. data BinOp -- | A pseudo-operator standing in for any normal identifier used as an -- operator (they all have the same fixity). Binary Ops for Numbers Backtick :: BinOp Plus :: BinOp Minus :: BinOp Pow :: BinOp Times :: BinOp Divide :: BinOp Mod :: BinOp Quot :: BinOp Rem :: BinOp ShiftR :: BinOp ShiftL :: BinOp Band :: BinOp Xor :: BinOp Bor :: BinOp LogAnd :: BinOp LogOr :: BinOp Equal :: BinOp NotEqual :: BinOp Less :: BinOp Leq :: BinOp Greater :: BinOp Geq :: BinOp -- |
-- |> --PipeRight :: BinOp -- | <| Misc PipeLeft :: BinOp -- | An identifier consists of its name and the type of the value bound to -- the identifier. data IdentBase f vn Ident :: vn -> f PatType -> SrcLoc -> IdentBase f vn [identName] :: IdentBase f vn -> vn [identType] :: IdentBase f vn -> f PatType [identSrcLoc] :: IdentBase f vn -> SrcLoc -- | Whether a bound for an end-point of a DimSlice or a range -- literal is inclusive or exclusive. data Inclusiveness a DownToExclusive :: a -> Inclusiveness a -- | May be "down to" if step is negative. ToInclusive :: a -> Inclusiveness a UpToExclusive :: a -> Inclusiveness a -- | An indexing of a single dimension. data DimIndexBase f vn DimFix :: ExpBase f vn -> DimIndexBase f vn DimSlice :: Maybe (ExpBase f vn) -> Maybe (ExpBase f vn) -> Maybe (ExpBase f vn) -> DimIndexBase f vn -- | A slicing of an array (potentially multiple dimensions). type SliceBase f vn = [DimIndexBase f vn] -- | A binding of a size in a pattern (essentially a size parameter in a -- let expression). data SizeBinder vn SizeBinder :: !vn -> !SrcLoc -> SizeBinder vn [sizeName] :: SizeBinder vn -> !vn [sizeLoc] :: SizeBinder vn -> !SrcLoc -- | An "application expression" is a semantic (not syntactic) grouping of -- expressions that have "funcall-like" semantics, mostly meaning that -- they can return existential sizes. In our type theory, these are all -- thought to be bound to names (*Administrative Normal Form*), but as -- this is not practical in a real language, we instead use an annotation -- (AppRes) that stores the information we need, so we can pretend -- that an application expression was really bound to a name. data AppExpBase f vn -- | The Maybe VName is a possible existential size that is -- instantiated by this argument. May have duplicates across the program, -- but they will all produce the same value (the expressions will be -- identical). Apply :: ExpBase f vn -> ExpBase f vn -> f (Diet, Maybe VName) -> SrcLoc -> AppExpBase f vn -- | Size coercion: e :> t. Coerce :: ExpBase f vn -> TypeDeclBase f vn -> SrcLoc -> AppExpBase f vn Range :: ExpBase f vn -> Maybe (ExpBase f vn) -> Inclusiveness (ExpBase f vn) -> SrcLoc -> AppExpBase f vn LetPat :: [SizeBinder vn] -> PatBase f vn -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> AppExpBase f vn LetFun :: vn -> ([TypeParamBase vn], [PatBase f vn], Maybe (TypeExp vn), f StructType, ExpBase f vn) -> ExpBase f vn -> SrcLoc -> AppExpBase f vn If :: ExpBase f vn -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> AppExpBase f vn DoLoop :: [VName] -> PatBase f vn -> ExpBase f vn -> LoopFormBase f vn -> ExpBase f vn -> SrcLoc -> AppExpBase f vn BinOp :: (QualName vn, SrcLoc) -> f PatType -> (ExpBase f vn, f (StructType, Maybe VName)) -> (ExpBase f vn, f (StructType, Maybe VName)) -> SrcLoc -> AppExpBase f vn LetWith :: IdentBase f vn -> IdentBase f vn -> SliceBase f vn -> ExpBase f vn -> ExpBase f vn -> SrcLoc -> AppExpBase f vn Index :: ExpBase f vn -> SliceBase f vn -> SrcLoc -> AppExpBase f vn -- | A match expression. Match :: ExpBase f vn -> NonEmpty (CaseBase f vn) -> SrcLoc -> AppExpBase f vn -- | An annotation inserted by the type checker on constructs that are -- "function calls" (either literally or conceptually). This annotation -- encodes the result type, as well as any existential sizes that are -- generated here. data AppRes AppRes :: PatType -> [VName] -> AppRes [appResType] :: AppRes -> PatType [appResExt] :: AppRes -> [VName] -- | The Futhark expression language. -- -- This allows us to encode whether or not the expression has been -- type-checked in the Haskell type of the expression. Specifically, the -- parser will produce expressions of type Exp NoInfo -- Name, and the type checker will convert these to Exp -- Info VName, in which type information is always -- present and all names are unique. data ExpBase f vn Literal :: PrimValue -> SrcLoc -> ExpBase f vn -- | A polymorphic integral literal. IntLit :: Integer -> f PatType -> SrcLoc -> ExpBase f vn -- | A polymorphic decimal literal. FloatLit :: Double -> f PatType -> SrcLoc -> ExpBase f vn -- | A string literal is just a fancy syntax for an array of bytes. StringLit :: [Word8] -> SrcLoc -> ExpBase f vn Var :: QualName vn -> f PatType -> SrcLoc -> ExpBase f vn -- | A parenthesized expression. Parens :: ExpBase f vn -> SrcLoc -> ExpBase f vn QualParens :: (QualName vn, SrcLoc) -> ExpBase f vn -> SrcLoc -> ExpBase f vn -- | Tuple literals, e.g., {1+3, {x, y+z}}. TupLit :: [ExpBase f vn] -> SrcLoc -> ExpBase f vn -- | Record literals, e.g. {x=2,y=3,z}. RecordLit :: [FieldBase f vn] -> SrcLoc -> ExpBase f vn -- | Array literals, e.g., [ [1+x, 3], [2, 1+4] ]. Second arg is -- the row type of the rows of the array. ArrayLit :: [ExpBase f vn] -> f PatType -> SrcLoc -> ExpBase f vn -- | An attribute applied to the following expression. Attr :: AttrInfo -> ExpBase f vn -> SrcLoc -> ExpBase f vn Project :: Name -> ExpBase f vn -> f PatType -> SrcLoc -> ExpBase f vn -- | Numeric negation (ugly special case; Haskell did it first). Negate :: ExpBase f vn -> SrcLoc -> ExpBase f vn -- | Logical and bitwise negation. Not :: ExpBase f vn -> SrcLoc -> ExpBase f vn -- | Fail if the first expression does not return true, and return the -- value of the second expression if it does. Assert :: ExpBase f vn -> ExpBase f vn -> f String -> SrcLoc -> ExpBase f vn -- | An n-ary value constructor. Constr :: Name -> [ExpBase f vn] -> f PatType -> SrcLoc -> ExpBase f vn Update :: ExpBase f vn -> SliceBase f vn -> ExpBase f vn -> SrcLoc -> ExpBase f vn RecordUpdate :: ExpBase f vn -> [Name] -> ExpBase f vn -> f PatType -> SrcLoc -> ExpBase f vn Lambda :: [PatBase f vn] -> ExpBase f vn -> Maybe (TypeExp vn) -> f (Aliasing, StructType) -> SrcLoc -> ExpBase f vn -- | +; first two types are operands, third is result. OpSection :: QualName vn -> f PatType -> SrcLoc -> ExpBase f vn -- | 2+; first type is operand, second is result. OpSectionLeft :: QualName vn -> f PatType -> ExpBase f vn -> (f (PName, StructType, Maybe VName), f (PName, StructType)) -> (f PatType, f [VName]) -> SrcLoc -> ExpBase f vn -- | +2; first type is operand, second is result. OpSectionRight :: QualName vn -> f PatType -> ExpBase f vn -> (f (PName, StructType), f (PName, StructType, Maybe VName)) -> f PatType -> SrcLoc -> ExpBase f vn -- | Field projection as a section: (.x.y.z). ProjectSection :: [Name] -> f PatType -> SrcLoc -> ExpBase f vn -- | Array indexing as a section: (.[i,j]). IndexSection :: SliceBase f vn -> f PatType -> SrcLoc -> ExpBase f vn -- | Type ascription: e : t. Ascript :: ExpBase f vn -> TypeDeclBase f vn -> SrcLoc -> ExpBase f vn AppExp :: AppExpBase f vn -> f AppRes -> ExpBase f vn -- | An entry in a record literal. data FieldBase f vn RecordFieldExplicit :: Name -> ExpBase f vn -> SrcLoc -> FieldBase f vn RecordFieldImplicit :: vn -> f PatType -> SrcLoc -> FieldBase f vn -- | A case in a match expression. data CaseBase f vn CasePat :: PatBase f vn -> ExpBase f vn -> SrcLoc -> CaseBase f vn -- | Whether the loop is a for-loop or a while-loop. data LoopFormBase f vn For :: IdentBase f vn -> ExpBase f vn -> LoopFormBase f vn ForIn :: PatBase f vn -> ExpBase f vn -> LoopFormBase f vn While :: ExpBase f vn -> LoopFormBase f vn -- | A literal in a pattern. data PatLit PatLitInt :: Integer -> PatLit PatLitFloat :: Double -> PatLit PatLitPrim :: PrimValue -> PatLit -- | A pattern as used most places where variables are bound (function -- parameters, let expressions, etc). data PatBase f vn TuplePat :: [PatBase f vn] -> SrcLoc -> PatBase f vn RecordPat :: [(Name, PatBase f vn)] -> SrcLoc -> PatBase f vn PatParens :: PatBase f vn -> SrcLoc -> PatBase f vn Id :: vn -> f PatType -> SrcLoc -> PatBase f vn Wildcard :: f PatType -> SrcLoc -> PatBase f vn PatAscription :: PatBase f vn -> TypeDeclBase f vn -> SrcLoc -> PatBase f vn PatLit :: PatLit -> f PatType -> SrcLoc -> PatBase f vn PatConstr :: Name -> f PatType -> [PatBase f vn] -> SrcLoc -> PatBase f vn -- | A spec is a component of a module type. data SpecBase f vn ValSpec :: vn -> [TypeParamBase vn] -> TypeDeclBase f vn -> Maybe DocComment -> SrcLoc -> SpecBase f vn [specName] :: SpecBase f vn -> vn [specTypeParams] :: SpecBase f vn -> [TypeParamBase vn] [specType] :: SpecBase f vn -> TypeDeclBase f vn [specDoc] :: SpecBase f vn -> Maybe DocComment [specLocation] :: SpecBase f vn -> SrcLoc TypeAbbrSpec :: TypeBindBase f vn -> SpecBase f vn -- | Abstract type. TypeSpec :: Liftedness -> vn -> [TypeParamBase vn] -> Maybe DocComment -> SrcLoc -> SpecBase f vn ModSpec :: vn -> SigExpBase f vn -> Maybe DocComment -> SrcLoc -> SpecBase f vn IncludeSpec :: SigExpBase f vn -> SrcLoc -> SpecBase f vn -- | A module type expression. data SigExpBase f vn SigVar :: QualName vn -> f (Map VName VName) -> SrcLoc -> SigExpBase f vn SigParens :: SigExpBase f vn -> SrcLoc -> SigExpBase f vn SigSpecs :: [SpecBase f vn] -> SrcLoc -> SigExpBase f vn SigWith :: SigExpBase f vn -> TypeRefBase f vn -> SrcLoc -> SigExpBase f vn SigArrow :: Maybe vn -> SigExpBase f vn -> SigExpBase f vn -> SrcLoc -> SigExpBase f vn -- | A type refinement. data TypeRefBase f vn TypeRef :: QualName vn -> [TypeParamBase vn] -> TypeDeclBase f vn -> SrcLoc -> TypeRefBase f vn -- | Module type binding. data SigBindBase f vn SigBind :: vn -> SigExpBase f vn -> Maybe DocComment -> SrcLoc -> SigBindBase f vn [sigName] :: SigBindBase f vn -> vn [sigExp] :: SigBindBase f vn -> SigExpBase f vn [sigDoc] :: SigBindBase f vn -> Maybe DocComment [sigLoc] :: SigBindBase f vn -> SrcLoc -- | Module expression. data ModExpBase f vn ModVar :: QualName vn -> SrcLoc -> ModExpBase f vn ModParens :: ModExpBase f vn -> SrcLoc -> ModExpBase f vn -- | The contents of another file as a module. ModImport :: FilePath -> f FilePath -> SrcLoc -> ModExpBase f vn ModDecs :: [DecBase f vn] -> SrcLoc -> ModExpBase f vn -- | Functor application. The first mapping is from parameter names to -- argument names, while the second maps names in the constructed module -- to the names inside the functor. ModApply :: ModExpBase f vn -> ModExpBase f vn -> f (Map VName VName) -> f (Map VName VName) -> SrcLoc -> ModExpBase f vn ModAscript :: ModExpBase f vn -> SigExpBase f vn -> f (Map VName VName) -> SrcLoc -> ModExpBase f vn ModLambda :: ModParamBase f vn -> Maybe (SigExpBase f vn, f (Map VName VName)) -> ModExpBase f vn -> SrcLoc -> ModExpBase f vn -- | A module binding. data ModBindBase f vn ModBind :: vn -> [ModParamBase f vn] -> Maybe (SigExpBase f vn, f (Map VName VName)) -> ModExpBase f vn -> Maybe DocComment -> SrcLoc -> ModBindBase f vn [modName] :: ModBindBase f vn -> vn [modParams] :: ModBindBase f vn -> [ModParamBase f vn] [modSignature] :: ModBindBase f vn -> Maybe (SigExpBase f vn, f (Map VName VName)) [modExp] :: ModBindBase f vn -> ModExpBase f vn [modDoc] :: ModBindBase f vn -> Maybe DocComment [modLocation] :: ModBindBase f vn -> SrcLoc -- | A module parameter. data ModParamBase f vn ModParam :: vn -> SigExpBase f vn -> f [VName] -> SrcLoc -> ModParamBase f vn [modParamName] :: ModParamBase f vn -> vn [modParamType] :: ModParamBase f vn -> SigExpBase f vn [modParamAbs] :: ModParamBase f vn -> f [VName] [modParamLocation] :: ModParamBase f vn -> SrcLoc -- | Documentation strings, including source location. data DocComment DocComment :: String -> SrcLoc -> DocComment -- | Function Declarations data ValBindBase f vn ValBind :: Maybe (f EntryPoint) -> vn -> Maybe (TypeExp vn) -> f (StructType, [VName]) -> [TypeParamBase vn] -> [PatBase f vn] -> ExpBase f vn -> Maybe DocComment -> [AttrInfo] -> SrcLoc -> ValBindBase f vn -- | Just if this function is an entry point. If so, it also contains the -- externally visible interface. Note that this may not strictly be -- well-typed after some desugaring operations, as it may refer to -- abstract types that are no longer in scope. [valBindEntryPoint] :: ValBindBase f vn -> Maybe (f EntryPoint) [valBindName] :: ValBindBase f vn -> vn [valBindRetDecl] :: ValBindBase f vn -> Maybe (TypeExp vn) [valBindRetType] :: ValBindBase f vn -> f (StructType, [VName]) [valBindTypeParams] :: ValBindBase f vn -> [TypeParamBase vn] [valBindParams] :: ValBindBase f vn -> [PatBase f vn] [valBindBody] :: ValBindBase f vn -> ExpBase f vn [valBindDoc] :: ValBindBase f vn -> Maybe DocComment [valBindAttrs] :: ValBindBase f vn -> [AttrInfo] [valBindLocation] :: ValBindBase f vn -> SrcLoc -- | Information about the external interface exposed by an entry point. -- The important thing is that that we remember the original -- source-language types, without desugaring them at all. The annoying -- thing is that we do not require type annotations on entry points, so -- the types can be either ascribed or inferred. data EntryPoint EntryPoint :: [EntryType] -> EntryType -> EntryPoint [entryParams] :: EntryPoint -> [EntryType] [entryReturn] :: EntryPoint -> EntryType -- | Part of the type of an entry point. Has an actual type, and maybe also -- an ascribed type expression. data EntryType EntryType :: StructType -> Maybe (TypeExp VName) -> EntryType [entryType] :: EntryType -> StructType [entryAscribed] :: EntryType -> Maybe (TypeExp VName) -- | The liftedness of a type parameter. By the Ord instance, -- Unlifted < SizeLifted < Lifted. data Liftedness -- | May only be instantiated with a zero-order type of (possibly -- symbolically) known size. Unlifted :: Liftedness -- | May only be instantiated with a zero-order type, but the size can be -- varying. SizeLifted :: Liftedness -- | May be instantiated with a functional type. Lifted :: Liftedness -- | Type Declarations data TypeBindBase f vn TypeBind :: vn -> Liftedness -> [TypeParamBase vn] -> TypeDeclBase f vn -> Maybe DocComment -> SrcLoc -> TypeBindBase f vn [typeAlias] :: TypeBindBase f vn -> vn [typeLiftedness] :: TypeBindBase f vn -> Liftedness [typeParams] :: TypeBindBase f vn -> [TypeParamBase vn] [typeExp] :: TypeBindBase f vn -> TypeDeclBase f vn [typeDoc] :: TypeBindBase f vn -> Maybe DocComment [typeBindLocation] :: TypeBindBase f vn -> SrcLoc -- | A type parameter. data TypeParamBase vn -- | A type parameter that must be a size. TypeParamDim :: vn -> SrcLoc -> TypeParamBase vn -- | A type parameter that must be a type. TypeParamType :: Liftedness -> vn -> SrcLoc -> TypeParamBase vn -- | The name of a type parameter. typeParamName :: TypeParamBase vn -> vn -- | The program described by a single Futhark file. May depend on other -- files. data ProgBase f vn Prog :: Maybe DocComment -> [DecBase f vn] -> ProgBase f vn [progDoc] :: ProgBase f vn -> Maybe DocComment [progDecs] :: ProgBase f vn -> [DecBase f vn] -- | A top-level binding. data DecBase f vn ValDec :: ValBindBase f vn -> DecBase f vn TypeDec :: TypeBindBase f vn -> DecBase f vn SigDec :: SigBindBase f vn -> DecBase f vn ModDec :: ModBindBase f vn -> DecBase f vn OpenDec :: ModExpBase f vn -> SrcLoc -> DecBase f vn LocalDec :: DecBase f vn -> SrcLoc -> DecBase f vn ImportDec :: FilePath -> f FilePath -> SrcLoc -> DecBase f vn -- | Convenience class for deriving Show instances for the AST. class (Show vn, Show (f VName), Show (f (Diet, Maybe VName)), Show (f String), Show (f [VName]), Show (f ([VName], [VName])), Show (f PatType), Show (f (PatType, [VName])), Show (f (StructType, [VName])), Show (f EntryPoint), Show (f StructType), Show (f (StructType, Maybe VName)), Show (f (PName, StructType)), Show (f (PName, StructType, Maybe VName)), Show (f (Aliasing, StructType)), Show (f (Map VName VName)), Show (f AppRes)) => Showable f vn -- | No information functor. Usually used for placeholder type- or aliasing -- information. data NoInfo a NoInfo :: NoInfo a -- | Some information. The dual to NoInfo newtype Info a Info :: a -> Info a [unInfo] :: Info a -> a -- | A variable that is aliased. Can be still in-scope, or have gone out of -- scope and be free. In the latter case, it behaves more like an -- equivalence class. See uniqueness-error18.fut for an example of why -- this is necessary. data Alias AliasBound :: VName -> Alias [aliasVar] :: Alias -> VName AliasFree :: VName -> Alias [aliasVar] :: Alias -> VName -- | Aliasing for a type, which is a set of the variables that are aliased. type Aliasing = Set Alias -- | A name qualified with a breadcrumb of module accesses. data QualName vn QualName :: ![vn] -> !vn -> QualName vn [qualQuals] :: QualName vn -> ![vn] [qualLeaf] :: QualName vn -> !vn instance GHC.Show.Show (Language.Futhark.Syntax.NoInfo a) instance GHC.Classes.Ord (Language.Futhark.Syntax.NoInfo a) instance GHC.Classes.Eq (Language.Futhark.Syntax.NoInfo a) instance GHC.Show.Show a => GHC.Show.Show (Language.Futhark.Syntax.Info a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Language.Futhark.Syntax.Info a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Language.Futhark.Syntax.Info a) instance GHC.Show.Show Language.Futhark.Syntax.PrimType instance GHC.Classes.Ord Language.Futhark.Syntax.PrimType instance GHC.Classes.Eq Language.Futhark.Syntax.PrimType instance GHC.Show.Show Language.Futhark.Syntax.PrimValue instance GHC.Classes.Ord Language.Futhark.Syntax.PrimValue instance GHC.Classes.Eq Language.Futhark.Syntax.PrimValue instance GHC.Show.Show Language.Futhark.Syntax.AttrInfo instance GHC.Classes.Ord Language.Futhark.Syntax.AttrInfo instance GHC.Classes.Eq Language.Futhark.Syntax.AttrInfo instance GHC.Show.Show dim => GHC.Show.Show (Language.Futhark.Syntax.ShapeDecl dim) instance GHC.Classes.Ord dim => GHC.Classes.Ord (Language.Futhark.Syntax.ShapeDecl dim) instance GHC.Classes.Eq dim => GHC.Classes.Eq (Language.Futhark.Syntax.ShapeDecl dim) instance GHC.Show.Show Language.Futhark.Syntax.TypeName instance GHC.Show.Show Language.Futhark.Syntax.PName instance (GHC.Show.Show as, GHC.Show.Show dim) => GHC.Show.Show (Language.Futhark.Syntax.ScalarTypeBase dim as) instance (GHC.Classes.Ord as, GHC.Classes.Ord dim) => GHC.Classes.Ord (Language.Futhark.Syntax.ScalarTypeBase dim as) instance (GHC.Classes.Eq as, GHC.Classes.Eq dim) => GHC.Classes.Eq (Language.Futhark.Syntax.ScalarTypeBase dim as) instance (GHC.Show.Show as, GHC.Show.Show dim) => GHC.Show.Show (Language.Futhark.Syntax.TypeBase dim as) instance (GHC.Classes.Ord as, GHC.Classes.Ord dim) => GHC.Classes.Ord (Language.Futhark.Syntax.TypeBase dim as) instance (GHC.Classes.Eq as, GHC.Classes.Eq dim) => GHC.Classes.Eq (Language.Futhark.Syntax.TypeBase dim as) instance GHC.Show.Show dim => GHC.Show.Show (Language.Futhark.Syntax.TypeArg dim) instance GHC.Classes.Ord dim => GHC.Classes.Ord (Language.Futhark.Syntax.TypeArg dim) instance GHC.Classes.Eq dim => GHC.Classes.Eq (Language.Futhark.Syntax.TypeArg dim) instance GHC.Show.Show Language.Futhark.Syntax.Alias instance GHC.Classes.Ord Language.Futhark.Syntax.Alias instance GHC.Classes.Eq Language.Futhark.Syntax.Alias instance GHC.Show.Show Language.Futhark.Syntax.Diet instance GHC.Classes.Eq Language.Futhark.Syntax.Diet instance GHC.Show.Show Language.Futhark.Syntax.Value instance GHC.Classes.Eq Language.Futhark.Syntax.Value instance GHC.Enum.Bounded Language.Futhark.Syntax.BinOp instance GHC.Enum.Enum Language.Futhark.Syntax.BinOp instance GHC.Show.Show Language.Futhark.Syntax.BinOp instance GHC.Classes.Ord Language.Futhark.Syntax.BinOp instance GHC.Classes.Eq Language.Futhark.Syntax.BinOp instance GHC.Show.Show a => GHC.Show.Show (Language.Futhark.Syntax.Inclusiveness a) instance GHC.Classes.Ord a => GHC.Classes.Ord (Language.Futhark.Syntax.Inclusiveness a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Language.Futhark.Syntax.Inclusiveness a) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.QualName vn) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.DimExp vn) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.TypeArgExp vn) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.TypeExp vn) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.DimDecl vn) instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.SizeBinder vn) instance GHC.Classes.Ord vn => GHC.Classes.Ord (Language.Futhark.Syntax.SizeBinder vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.SizeBinder vn) instance GHC.Show.Show Language.Futhark.Syntax.AppRes instance GHC.Classes.Ord Language.Futhark.Syntax.AppRes instance GHC.Classes.Eq Language.Futhark.Syntax.AppRes instance GHC.Show.Show Language.Futhark.Syntax.PatLit instance GHC.Classes.Ord Language.Futhark.Syntax.PatLit instance GHC.Classes.Eq Language.Futhark.Syntax.PatLit instance GHC.Show.Show Language.Futhark.Syntax.DocComment instance GHC.Show.Show Language.Futhark.Syntax.EntryType instance GHC.Show.Show Language.Futhark.Syntax.EntryPoint instance GHC.Show.Show Language.Futhark.Syntax.Liftedness instance GHC.Classes.Ord Language.Futhark.Syntax.Liftedness instance GHC.Classes.Eq Language.Futhark.Syntax.Liftedness instance GHC.Show.Show vn => GHC.Show.Show (Language.Futhark.Syntax.TypeParamBase vn) instance GHC.Classes.Ord vn => GHC.Classes.Ord (Language.Futhark.Syntax.TypeParamBase vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.TypeParamBase vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.DimDecl Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.DimDecl Language.Futhark.Core.VName) instance GHC.Classes.Eq (Language.Futhark.Syntax.DimExp Language.Futhark.Core.Name) instance GHC.Classes.Eq (Language.Futhark.Syntax.DimExp Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.DimExp Language.Futhark.Core.Name) instance GHC.Classes.Ord (Language.Futhark.Syntax.DimExp Language.Futhark.Core.VName) instance GHC.Classes.Eq (Language.Futhark.Syntax.TypeExp Language.Futhark.Core.Name) instance GHC.Classes.Eq (Language.Futhark.Syntax.TypeExp Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.TypeExp Language.Futhark.Core.Name) instance GHC.Classes.Ord (Language.Futhark.Syntax.TypeExp Language.Futhark.Core.VName) instance GHC.Classes.Eq (Language.Futhark.Syntax.TypeArgExp Language.Futhark.Core.Name) instance GHC.Classes.Eq (Language.Futhark.Syntax.TypeArgExp Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.TypeArgExp Language.Futhark.Core.Name) instance GHC.Classes.Ord (Language.Futhark.Syntax.TypeArgExp Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.TypeDeclBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.TypeDeclBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.TypeDeclBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.IdentBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.DimIndexBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.DimIndexBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.DimIndexBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.AppExpBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.AppExpBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.AppExpBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ExpBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.ExpBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.ExpBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.FieldBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.FieldBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.FieldBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.CaseBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.CaseBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.CaseBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.LoopFormBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.LoopFormBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.LoopFormBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.PatBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.PatBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.PatBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ValBindBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.TypeBindBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.SpecBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.SigExpBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.TypeRefBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.SigBindBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ModExpBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ModBindBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ModParamBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.DecBase f vn) instance Language.Futhark.Syntax.Showable f vn => GHC.Show.Show (Language.Futhark.Syntax.ProgBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ModExpBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ModBindBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.DecBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ModParamBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.SigBindBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.SpecBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.SigExpBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.TypeRefBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ValBindBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.AppExpBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.ExpBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.FieldBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.CaseBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.TypeBindBase f vn) instance GHC.Base.Functor Language.Futhark.Syntax.TypeParamBase instance Data.Foldable.Foldable Language.Futhark.Syntax.TypeParamBase instance Data.Traversable.Traversable Language.Futhark.Syntax.TypeParamBase instance Data.Loc.Located (Language.Futhark.Syntax.TypeParamBase vn) instance GHC.Show.Show vn => Language.Futhark.Syntax.Showable Language.Futhark.Syntax.NoInfo vn instance GHC.Show.Show vn => Language.Futhark.Syntax.Showable Language.Futhark.Syntax.Info vn instance Data.Loc.Located Language.Futhark.Syntax.DocComment instance Data.Loc.Located (Language.Futhark.Syntax.PatBase f vn) instance Data.Loc.Located (Language.Futhark.Syntax.SizeBinder vn) instance GHC.Classes.Eq vn => GHC.Classes.Eq (Language.Futhark.Syntax.IdentBase ty vn) instance GHC.Classes.Ord vn => GHC.Classes.Ord (Language.Futhark.Syntax.IdentBase ty vn) instance Data.Loc.Located (Language.Futhark.Syntax.IdentBase ty vn) instance Data.Loc.Located (Language.Futhark.Syntax.TypeDeclBase f vn) instance GHC.Base.Functor Language.Futhark.Syntax.DimDecl instance Data.Foldable.Foldable Language.Futhark.Syntax.DimDecl instance Data.Traversable.Traversable Language.Futhark.Syntax.DimDecl instance Language.Futhark.Syntax.ArrayDim (Language.Futhark.Syntax.DimDecl Language.Futhark.Core.VName) instance Data.Loc.Located (Language.Futhark.Syntax.TypeExp vn) instance Data.Loc.Located (Language.Futhark.Syntax.TypeArgExp vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.QualName Language.Futhark.Core.Name) instance GHC.Classes.Eq (Language.Futhark.Syntax.QualName Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.QualName Language.Futhark.Core.Name) instance GHC.Classes.Ord (Language.Futhark.Syntax.QualName Language.Futhark.Core.VName) instance GHC.Base.Functor Language.Futhark.Syntax.QualName instance Data.Foldable.Foldable Language.Futhark.Syntax.QualName instance Data.Traversable.Traversable Language.Futhark.Syntax.QualName instance Data.Loc.Located a => Data.Loc.Located (Language.Futhark.Syntax.Inclusiveness a) instance GHC.Base.Functor Language.Futhark.Syntax.Inclusiveness instance Data.Foldable.Foldable Language.Futhark.Syntax.Inclusiveness instance Data.Traversable.Traversable Language.Futhark.Syntax.Inclusiveness instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.BinOp instance Data.Bitraversable.Bitraversable Language.Futhark.Syntax.ScalarTypeBase instance Data.Bifunctor.Bifunctor Language.Futhark.Syntax.ScalarTypeBase instance Data.Bifoldable.Bifoldable Language.Futhark.Syntax.ScalarTypeBase instance Data.Bitraversable.Bitraversable Language.Futhark.Syntax.TypeBase instance Data.Bifunctor.Bifunctor Language.Futhark.Syntax.TypeBase instance Data.Bifoldable.Bifoldable Language.Futhark.Syntax.TypeBase instance Data.Traversable.Traversable Language.Futhark.Syntax.TypeArg instance GHC.Base.Functor Language.Futhark.Syntax.TypeArg instance Data.Foldable.Foldable Language.Futhark.Syntax.TypeArg instance GHC.Classes.Eq Language.Futhark.Syntax.PName instance GHC.Classes.Ord Language.Futhark.Syntax.PName instance GHC.Classes.Eq Language.Futhark.Syntax.TypeName instance GHC.Classes.Ord Language.Futhark.Syntax.TypeName instance Data.Foldable.Foldable Language.Futhark.Syntax.ShapeDecl instance Data.Traversable.Traversable Language.Futhark.Syntax.ShapeDecl instance GHC.Base.Functor Language.Futhark.Syntax.ShapeDecl instance GHC.Base.Semigroup (Language.Futhark.Syntax.ShapeDecl dim) instance GHC.Base.Monoid (Language.Futhark.Syntax.ShapeDecl dim) instance Language.Futhark.Syntax.ArrayDim () instance Language.Futhark.Syntax.IsPrimValue GHC.Types.Int instance Language.Futhark.Syntax.IsPrimValue GHC.Int.Int8 instance Language.Futhark.Syntax.IsPrimValue GHC.Int.Int16 instance Language.Futhark.Syntax.IsPrimValue GHC.Int.Int32 instance Language.Futhark.Syntax.IsPrimValue GHC.Int.Int64 instance Language.Futhark.Syntax.IsPrimValue GHC.Word.Word8 instance Language.Futhark.Syntax.IsPrimValue GHC.Word.Word16 instance Language.Futhark.Syntax.IsPrimValue GHC.Word.Word32 instance Language.Futhark.Syntax.IsPrimValue GHC.Word.Word64 instance Language.Futhark.Syntax.IsPrimValue GHC.Types.Float instance Language.Futhark.Syntax.IsPrimValue GHC.Types.Double instance Language.Futhark.Syntax.IsPrimValue GHC.Types.Bool instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.PrimType instance GHC.Base.Functor Language.Futhark.Syntax.Info instance Data.Foldable.Foldable Language.Futhark.Syntax.Info instance Data.Traversable.Traversable Language.Futhark.Syntax.Info instance GHC.Base.Functor Language.Futhark.Syntax.NoInfo instance Data.Foldable.Foldable Language.Futhark.Syntax.NoInfo instance Data.Traversable.Traversable Language.Futhark.Syntax.NoInfo -- | This module provides various simple ways to query and manipulate -- fundamental Futhark terms, such as types and values. The intent is to -- keep Futhark.Language.Syntax simple, and put whatever -- embellishments we need here. module Language.Futhark.Prop -- | The nature of something predefined. For functions, these can either be -- monomorphic or overloaded. An overloaded builtin is a list valid types -- it can be instantiated with, to the parameter and result type, with -- Nothing representing the overloaded parameter type. data Intrinsic IntrinsicMonoFun :: [PrimType] -> PrimType -> Intrinsic IntrinsicOverloadedFun :: [PrimType] -> [Maybe PrimType] -> Maybe PrimType -> Intrinsic IntrinsicPolyFun :: [TypeParamBase VName] -> [StructType] -> StructType -> Intrinsic IntrinsicType :: Liftedness -> [TypeParamBase VName] -> StructType -> Intrinsic IntrinsicEquality :: Intrinsic -- | A map of all built-ins. intrinsics :: Map VName Intrinsic -- | The largest tag used by an intrinsic - this can be used to determine -- whether a VName refers to an intrinsic or a user-defined name. maxIntrinsicTag :: Int -- | Names of primitive types to types. This is only valid if no shadowing -- is going on, but useful for tools. namesToPrimTypes :: Map Name PrimType -- | Create a name with no qualifiers from a name. qualName :: v -> QualName v -- | Add another qualifier (at the head) to a qualified name. qualify :: v -> QualName v -> QualName v -- | Create a type name name with no qualifiers from a VName. typeName :: VName -> TypeName -- | The type of the value. valueType :: Value -> ValueType -- | The type of a basic value. primValueType :: PrimValue -> PrimType -- | Given an operator name, return the operator that determines its -- syntactical properties. leadingOperator :: Name -> BinOp -- | The modules imported by a Futhark program. progImports :: ProgBase f vn -> [(String, SrcLoc)] -- | The modules imported by a single declaration. decImports :: DecBase f vn -> [(String, SrcLoc)] -- | The set of module types used in any exported (non-local) declaration. progModuleTypes :: Ord vn => ProgBase f vn -> Set vn -- | Extract a leading ((name, namespace, file), remainder) from a -- documentation comment string. These are formatted as -- `name`@namespace[@file]. Let us hope that this pattern does not occur -- anywhere else. identifierReference :: String -> Maybe ((String, String, Maybe FilePath), String) -- | Given a list of strings representing entries in the stack trace and -- the index of the frame to highlight, produce a final -- newline-terminated string for showing to the user. This string should -- also be preceded by a newline. The most recent stack frame must come -- first in the list. prettyStacktrace :: Int -> [String] -> String -- | The type of an Futhark term. The aliasing will refer to itself, if the -- term is a non-tuple-typed variable. typeOf :: ExpBase Info VName -> PatType -- | The type scheme of a value binding, comprising the type parameters and -- the actual type. valBindTypeScheme :: ValBindBase Info VName -> ([TypeParamBase VName], StructType) -- | The type of a function with the given parameters and return type. funType :: [PatBase Info VName] -> StructType -> StructType -- | The set of identifiers bound in a pattern. patIdents :: (Functor f, Ord vn) => PatBase f vn -> Set (IdentBase f vn) -- | The set of names bound in a pattern. patNames :: (Functor f, Ord vn) => PatBase f vn -> Set vn -- | A mapping from names bound in a map to their identifier. patternMap :: Functor f => PatBase f VName -> Map VName (IdentBase f VName) -- | The type of values bound by the pattern. patternType :: PatBase Info VName -> PatType -- | The type matched by the pattern, including shape declarations if -- present. patternStructType :: PatBase Info VName -> StructType -- | When viewed as a function parameter, does this pattern correspond to a -- named parameter of some type? patternParam :: PatBase Info VName -> (PName, StructType) -- | patternOrderZero pat is True if all of the types in -- the given pattern have order 0. patternOrderZero :: PatBase Info vn -> Bool -- | Extract all the shape names that occur in a given pattern. patternDimNames :: PatBase Info VName -> Set VName -- | Return the uniqueness of a type. uniqueness :: TypeBase shape as -> Uniqueness -- | unique t is True if the type of the argument is -- unique. unique :: TypeBase shape as -> Bool -- | Return the set of all variables mentioned in the aliasing of a type. aliases :: Monoid as => TypeBase shape as -> as -- | diet t returns a description of how a function parameter of -- type t might consume its argument. diet :: TypeBase shape as -> Diet -- | Return the dimensionality of a type. For non-arrays, this is zero. For -- a one-dimensional array it is one, for a two-dimensional it is two, -- and so forth. arrayRank :: TypeBase dim as -> Int -- | Return the shape of a type - for non-arrays, this is mempty. arrayShape :: TypeBase dim as -> ShapeDecl dim -- | Return any shape declarations in the type, with duplicates removed. nestedDims :: TypeBase (DimDecl VName) as -> [DimDecl VName] -- | orderZero t is True if the argument type has order 0, -- i.e., it is not a function type, does not contain a function type as a -- subcomponent, and may not be instantiated with a function type. orderZero :: TypeBase dim as -> Bool -- | Extract the parameter types and return type from a type. If the type -- is not an arrow type, the list of parameter types is empty. unfoldFunType :: TypeBase dim as -> ([TypeBase dim as], TypeBase dim as) -- | foldFunType ts ret creates a function type (Arrow) -- that takes ts as parameters and returns ret. foldFunType :: Monoid as => [TypeBase dim as] -> TypeBase dim as -> TypeBase dim as -- | The type names mentioned in a type. typeVars :: Monoid as => TypeBase dim as -> Set VName -- | Extract all the shape names that occur in a given type. typeDimNames :: TypeBase (DimDecl VName) als -> Set VName -- | peelArray n t returns the type resulting from peeling the -- first n array dimensions from t. Returns -- Nothing if t has less than n dimensions. peelArray :: Int -> TypeBase dim as -> Maybe (TypeBase dim as) -- | stripArray n t removes the n outermost layers of the -- array. Essentially, it is the type of indexing an array of type -- t with n indexes. stripArray :: Int -> TypeBase dim as -> TypeBase dim as -- | arrayOf t s u constructs an array type. The convenience -- compared to using the Array constructor directly is that -- t can itself be an array. If t is an -- n-dimensional array, and s is a list of length -- n, the resulting type is of an n+m dimensions. The -- uniqueness of the new array will be u, no matter the -- uniqueness of t. arrayOf :: Monoid as => TypeBase dim as -> ShapeDecl dim -> Uniqueness -> TypeBase dim as -- | Convert any type to one that has rank information, no alias -- information, and no embedded names. toStructural :: TypeBase dim as -> TypeBase () () -- | Remove aliasing information from a type. toStruct :: TypeBase dim as -> TypeBase dim () -- | Replace no aliasing with an empty alias set. fromStruct :: TypeBase dim as -> TypeBase dim Aliasing -- | t `setAliases` als returns t, but with als -- substituted for any already present aliasing. setAliases :: TypeBase dim asf -> ast -> TypeBase dim ast -- | t `addAliases` f returns t, but with any already -- present aliasing replaced by f applied to that aliasing. addAliases :: TypeBase dim asf -> (asf -> ast) -> TypeBase dim ast -- | Set the uniqueness attribute of a type. If the type is a record or sum -- type, the uniqueness of its components will be modified. setUniqueness :: TypeBase dim as -> Uniqueness -> TypeBase dim as -- | Change the shape of a type to be just the rank. noSizes :: TypeBase (DimDecl vn) as -> TypeBase () as -- | Change all size annotations to be AnyDim. anySizes :: TypeBase (DimDecl vn) as -> TypeBase (DimDecl vn) as -- | Perform a traversal (possibly including replacement) on sizes that are -- parameters in a function type, but also including the type immediately -- passed to the function. Also passes along a set of the parameter names -- inside the type that have come in scope at the occurrence of the -- dimension. traverseDims :: forall f fdim tdim als. Applicative f => (Set VName -> DimPos -> fdim -> f tdim) -> TypeBase fdim als -> f (TypeBase tdim als) -- | Where does this dimension occur? data DimPos -- | Immediately in the argument to traverseDims. PosImmediate :: DimPos -- | In a function parameter type. PosParam :: DimPos -- | In a function return type. PosReturn :: DimPos -- | Figure out which of the sizes in a binding type must be passed -- explicitly, because their first use is as something else than just an -- array dimension. mustBeExplicit :: StructType -> Set VName -- | Figure out which of the sizes in a parameter type must be passed -- explicitly, because their first use is as something else than just an -- array dimension. mustBeExplicit is like this function, but -- first decomposes into parameter types. mustBeExplicitInType :: StructType -> Set VName -- | Create a record type corresponding to a tuple with the given element -- types. tupleRecord :: [TypeBase dim as] -> TypeBase dim as -- | Does this type corespond to a tuple? If so, return the elements of -- that tuple. isTupleRecord :: TypeBase dim as -> Maybe [TypeBase dim as] -- | Does this record map correspond to a tuple? areTupleFields :: Map Name a -> Maybe [a] -- | Construct a record map corresponding to a tuple. tupleFields :: [a] -> Map Name a -- | Increasing field names for a tuple (starts at 0). tupleFieldNames :: [Name] -- | Sort fields by their name; taking care to sort numeric fields by their -- numeric value. This ensures that tuples and tuple-like records match. sortFields :: Map Name a -> [(Name, a)] -- | Sort the constructors of a sum type in some well-defined (but not -- otherwise significant) manner. sortConstrs :: Map Name a -> [(Name, a)] -- | Is this a TypeParamType? isTypeParam :: TypeParamBase vn -> Bool -- | Is this a TypeParamDim? isSizeParam :: TypeParamBase vn -> Bool -- | Combine the shape information of types as much as possible. The first -- argument is the orignal type and the second is the type of the -- transformed expression. This is necessary since the original type may -- contain additional information (e.g., shape restrictions) from the -- user given annotation. combineTypeShapes :: (Monoid as, ArrayDim dim) => TypeBase dim as -> TypeBase dim as -> TypeBase dim as -- | Match the dimensions of otherwise assumed-equal types. matchDims :: (Monoid as, Monad m) => (d1 -> d2 -> m d1) -> TypeBase d1 as -> TypeBase d2 as -> m (TypeBase d1 as) -- | No information functor. Usually used for placeholder type- or aliasing -- information. data NoInfo a NoInfo :: NoInfo a -- | A type with no aliasing information but shape annotations. type UncheckedType = TypeBase (ShapeDecl Name) () -- | An expression with no type annotations. type UncheckedTypeExp = TypeExp Name -- | An identifier with no type annotations. type UncheckedIdent = IdentBase NoInfo Name -- | A type declaration with no expanded type. type UncheckedTypeDecl = TypeDeclBase NoInfo Name -- | An index with no type annotations. type UncheckedDimIndex = DimIndexBase NoInfo Name -- | A slice with no type annotations. type UncheckedSlice = SliceBase NoInfo Name -- | An expression with no type annotations. type UncheckedExp = ExpBase NoInfo Name -- | A module expression with no type annotations. type UncheckedModExp = ModExpBase NoInfo Name -- | A module type expression with no type annotations. type UncheckedSigExp = SigExpBase NoInfo Name -- | A type parameter with no type annotations. type UncheckedTypeParam = TypeParamBase Name -- | A pattern with no type annotations. type UncheckedPat = PatBase NoInfo Name -- | A function declaration with no type annotations. type UncheckedValBind = ValBindBase NoInfo Name -- | A declaration with no type annotations. type UncheckedDec = DecBase NoInfo Name -- | A spec with no type annotations. type UncheckedSpec = SpecBase NoInfo Name -- | A Futhark program with no type annotations. type UncheckedProg = ProgBase NoInfo Name -- | A case (of a match expression) with no type annotations. type UncheckedCase = CaseBase NoInfo Name instance GHC.Show.Show Language.Futhark.Prop.DimPos instance GHC.Classes.Ord Language.Futhark.Prop.DimPos instance GHC.Classes.Eq Language.Futhark.Prop.DimPos -- | Futhark prettyprinter. This module defines Pretty instances for -- the AST defined in Language.Futhark.Syntax. module Language.Futhark.Pretty -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String -- | Prettyprint a list enclosed in curly braces. prettyTuple :: Pretty a => [a] -> String -- | Given an operator name, return the operator that determines its -- syntactical properties. leadingOperator :: Name -> BinOp -- | A class for types that are variable names in the Futhark source -- language. This is used instead of a mere Pretty instance -- because in the compiler frontend we want to print VNames differently -- depending on whether the FUTHARK_COMPILER_DEBUGGING environment -- variable is set, yet in the backend we want to always print VNames -- with the tag. To avoid erroneously using the Pretty instance -- for VNames, we in fact only define it inside the modules for the core -- language (as an orphan instance). class IsName v pprName :: IsName v => v -> Doc -- | Prettyprint a name to a string. prettyName :: IsName v => v -> String -- | Class for type constructors that represent annotations. Used in the -- prettyprinter to either print the original AST, or the computed -- decoration. class Annot f -- | Extract value, if any. unAnnot :: Annot f => f a -> Maybe a instance Language.Futhark.Pretty.Annot Language.Futhark.Syntax.NoInfo instance Language.Futhark.Pretty.Annot Language.Futhark.Syntax.Info instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeDeclBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.DimIndexBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.AppExpBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ExpBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.FieldBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.CaseBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.LoopFormBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.PatBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ProgBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.DecBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ModExpBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeBindBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ValBindBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.SpecBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.SigExpBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.SigBindBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ModParamBase f vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn, Language.Futhark.Pretty.Annot f) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ModBindBase f vn) instance Language.Futhark.Pretty.IsName Language.Futhark.Core.VName instance Language.Futhark.Pretty.IsName Language.Futhark.Core.Name instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.DimDecl vn) instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.DimExp vn) instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl (Language.Futhark.Syntax.DimDecl vn)) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl dim) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ScalarTypeBase dim as) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeExp vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeArgExp vn) instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.QualName vn) instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.IdentBase f vn) instance Language.Futhark.Pretty.IsName vn => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.SizeBinder vn) instance (GHC.Classes.Eq vn, Language.Futhark.Pretty.IsName vn) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeParamBase vn) instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.Value instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.PrimValue instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl ()) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl GHC.Int.Int64) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl GHC.Types.Bool) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl dim) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeBase dim as) instance Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.ShapeDecl dim) => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Syntax.TypeArg dim) instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.AttrInfo instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.PatLit instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Syntax.Liftedness -- | Interface to the Futhark parser. module Language.Futhark.Parser -- | Parse an entire Futhark program from the given Text, using the -- FilePath as the source name for error messages. parseFuthark :: FilePath -> Text -> Either ParseError UncheckedProg -- | Parse an Futhark expression from the given String, using the -- FilePath as the source name for error messages. parseExp :: FilePath -> Text -> Either ParseError UncheckedExp -- | Parse a Futhark module expression from the given String, using -- the FilePath as the source name for error messages. parseModExp :: FilePath -> Text -> Either ParseError (ModExpBase NoInfo Name) -- | Parse an Futhark type from the given String, using the -- FilePath as the source name for error messages. parseType :: FilePath -> Text -> Either ParseError UncheckedTypeExp -- | Parse any Futhark value from the given String, using the -- FilePath as the source name for error messages. parseValue :: FilePath -> Text -> Either ParseError Value -- | Parse several Futhark values (separated by anything) from the given -- String, using the FilePath as the source name for error -- messages. parseValues :: FilePath -> Text -> Either ParseError [Value] -- | Parse either an expression or a declaration incrementally; favouring -- declarations in case of ambiguity. parseDecOrExpIncrM :: Monad m => m Text -> FilePath -> Text -> m (Either ParseError (Either UncheckedDec UncheckedExp)) -- | A parse error. Use show to get a human-readable description. data ParseError ParseError :: String -> ParseError -- | Given a starting position, produce tokens from the given text (or a -- lexer error). Returns the final position. scanTokensText :: Pos -> Text -> Either String ([L Token], Pos) -- | A value tagged with a source location. data L a L :: SrcLoc -> a -> L a -- | A lexical token. It does not itself contain position information, so -- in practice the parser will consume tokens tagged with a source -- position. data Token ID :: Name -> Token INDEXING :: Name -> Token QUALINDEXING :: [Name] -> Name -> Token QUALPAREN :: [Name] -> Name -> Token SYMBOL :: BinOp -> [Name] -> Name -> Token CONSTRUCTOR :: Name -> Token PROJ_INTFIELD :: Name -> Token INTLIT :: Integer -> Token STRINGLIT :: Text -> Token I8LIT :: Int8 -> Token I16LIT :: Int16 -> Token I32LIT :: Int32 -> Token I64LIT :: Int64 -> Token U8LIT :: Word8 -> Token U16LIT :: Word16 -> Token U32LIT :: Word32 -> Token U64LIT :: Word64 -> Token FLOATLIT :: Double -> Token F16LIT :: Half -> Token F32LIT :: Float -> Token F64LIT :: Double -> Token CHARLIT :: Char -> Token COLON :: Token COLON_GT :: Token BACKSLASH :: Token APOSTROPHE :: Token APOSTROPHE_THEN_HAT :: Token APOSTROPHE_THEN_TILDE :: Token BACKTICK :: Token HASH_LBRACKET :: Token DOT :: Token TWO_DOTS :: Token TWO_DOTS_LT :: Token TWO_DOTS_GT :: Token THREE_DOTS :: Token LPAR :: Token RPAR :: Token RPAR_THEN_LBRACKET :: Token LBRACKET :: Token RBRACKET :: Token LCURLY :: Token RCURLY :: Token COMMA :: Token UNDERSCORE :: Token RIGHT_ARROW :: Token EQU :: Token ASTERISK :: Token NEGATE :: Token BANG :: Token LTH :: Token HAT :: Token TILDE :: Token PIPE :: Token IF :: Token THEN :: Token ELSE :: Token LET :: Token LOOP :: Token IN :: Token FOR :: Token DO :: Token WITH :: Token ASSERT :: Token TRUE :: Token FALSE :: Token WHILE :: Token INCLUDE :: Token IMPORT :: Token ENTRY :: Token TYPE :: Token MODULE :: Token VAL :: Token OPEN :: Token LOCAL :: Token MATCH :: Token CASE :: Token DOC :: String -> Token EOF :: Token -- | Re-export the external Futhark modules for convenience. module Language.Futhark -- | An identifier with type- and aliasing information. type Ident = IdentBase Info VName -- | An index with type information. type DimIndex = DimIndexBase Info VName -- | A slice with type information. type Slice = SliceBase Info VName -- | An application expression with type information. type AppExp = AppExpBase Info VName -- | An expression with type information. type Exp = ExpBase Info VName -- | A pattern with type information. type Pat = PatBase Info VName -- | A type-checked module expression. type ModExp = ModExpBase Info VName -- | A type-checked module parameter. type ModParam = ModParamBase Info VName -- | A type-checked module type expression. type SigExp = SigExpBase Info VName -- | A type-checked module binding. type ModBind = ModBindBase Info VName -- | A type-checked module type binding. type SigBind = SigBindBase Info VName -- | An constant declaration with type information. type ValBind = ValBindBase Info VName -- | A type-checked declaration. type Dec = DecBase Info VName -- | A type-checked specification. type Spec = SpecBase Info VName -- | An Futhark program with type information. type Prog = ProgBase Info VName -- | A type binding with type information. type TypeBind = TypeBindBase Info VName -- | A type declaration with type information type TypeDecl = TypeDeclBase Info VName -- | A known type arg with shape annotations. type StructTypeArg = TypeArg (DimDecl VName) -- | A known scalar type with no shape annotations. type ScalarType = ScalarTypeBase () -- | A type-checked type parameter. type TypeParam = TypeParamBase VName -- | A type-checked case (of a match expression). type Case = CaseBase Info VName -- | Definitions of various semantic objects (*not* the Futhark semantics -- themselves). module Language.Futhark.Semantic -- | Canonical reference to a Futhark code file. Does not include the -- .fut extension. This is most often a path relative to the -- current working directory of the compiler. data ImportName -- | Create an import name immediately from a file path specified by the -- user. mkInitialImport :: FilePath -> ImportName -- | We resolve '..' paths here and assume that no shenanigans are going on -- with symbolic links. If there is, too bad. Don't do that. mkImportFrom :: ImportName -> String -> SrcLoc -> ImportName -- | Create a .fut file corresponding to an ImportName. includeToFilePath :: ImportName -> FilePath -- | Produce a human-readable canonicalized string from an -- ImportName. includeToString :: ImportName -> String -- | The result of type checking some file. Can be passed to further -- invocations of the type checker. data FileModule FileModule :: TySet -> Env -> Prog -> FileModule -- | Abstract types. [fileAbs] :: FileModule -> TySet [fileEnv] :: FileModule -> Env [fileProg] :: FileModule -> Prog -- | A mapping from import names to imports. The ordering is significant. type Imports = [(String, FileModule)] -- | The space inhabited by a name. data Namespace -- | Functions and values. Term :: Namespace Type :: Namespace Signature :: Namespace -- | Modules produces environment with this representation. data Env Env :: Map VName BoundV -> Map VName TypeBinding -> Map VName MTy -> Map VName Mod -> NameMap -> Env [envVtable] :: Env -> Map VName BoundV [envTypeTable] :: Env -> Map VName TypeBinding [envSigTable] :: Env -> Map VName MTy [envModTable] :: Env -> Map VName Mod [envNameMap] :: Env -> NameMap -- | A mapping of abstract types to their liftedness. type TySet = Map (QualName VName) Liftedness -- | A parametric functor consists of a set of abstract types, the -- environment of its parameter, and the resulting module type. data FunSig FunSig :: TySet -> Mod -> MTy -> FunSig [funSigAbs] :: FunSig -> TySet [funSigMod] :: FunSig -> Mod [funSigMty] :: FunSig -> MTy -- | A mapping from names (which always exist in some namespace) to a -- unique (tagged) name. type NameMap = Map (Namespace, Name) (QualName VName) -- | Type parameters, list of parameter types (optinally named), and return -- type. The type parameters are in scope in both parameter types and the -- return type. Non-functional values have only a return type. data BoundV BoundV :: [TypeParam] -> StructType -> BoundV -- | Representation of a module, which is either a plain environment, or a -- parametric module ("functor" in SML). data Mod ModEnv :: Env -> Mod ModFun :: FunSig -> Mod -- | A binding from a name to its definition as a type. data TypeBinding TypeAbbr :: Liftedness -> [TypeParam] -> StructType -> TypeBinding -- | Representation of a module type. data MTy MTy :: TySet -> Mod -> MTy -- | Abstract types in the module type. [mtyAbs] :: MTy -> TySet [mtyMod] :: MTy -> Mod instance GHC.Show.Show Language.Futhark.Semantic.ImportName instance GHC.Classes.Ord Language.Futhark.Semantic.ImportName instance GHC.Classes.Eq Language.Futhark.Semantic.ImportName instance GHC.Enum.Enum Language.Futhark.Semantic.Namespace instance GHC.Show.Show Language.Futhark.Semantic.Namespace instance GHC.Classes.Ord Language.Futhark.Semantic.Namespace instance GHC.Classes.Eq Language.Futhark.Semantic.Namespace instance GHC.Show.Show Language.Futhark.Semantic.TypeBinding instance GHC.Classes.Eq Language.Futhark.Semantic.TypeBinding instance GHC.Show.Show Language.Futhark.Semantic.BoundV instance GHC.Show.Show Language.Futhark.Semantic.FunSig instance GHC.Show.Show Language.Futhark.Semantic.Mod instance GHC.Show.Show Language.Futhark.Semantic.MTy instance GHC.Show.Show Language.Futhark.Semantic.Env instance GHC.Base.Semigroup Language.Futhark.Semantic.Env instance GHC.Base.Monoid Language.Futhark.Semantic.Env instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Semantic.MTy instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Semantic.Mod instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Semantic.Env instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Semantic.Namespace instance Data.Loc.Located Language.Futhark.Semantic.ImportName -- | An interpreter operating on type-checked source Futhark terms. -- Relatively slow. module Language.Futhark.Interpreter -- | The interpreter context. All evaluation takes place with respect to a -- context, and it can be extended with more definitions, which is how -- the REPL works. data Ctx Ctx :: Env -> Map FilePath Env -> Ctx [ctxEnv] :: Ctx -> Env [ctxImports] :: Ctx -> Map FilePath Env -- | The actual type- and value environment. data Env -- | An error occurred during interpretation due to an error in the user -- program. Actual interpreter errors will be signaled with an IO -- exception (error). data InterpreterError -- | The initial environment contains definitions of the various intrinsic -- functions. initialCtx :: Ctx interpretExp :: Ctx -> Exp -> F ExtOp Value interpretDec :: Ctx -> Dec -> F ExtOp Ctx interpretImport :: Ctx -> (FilePath, Prog) -> F ExtOp Ctx -- | Execute the named function on the given arguments; may fail horribly -- if these are ill-typed. interpretFunction :: Ctx -> VName -> [Value] -> Either String (F ExtOp Value) data ExtOp a ExtOpTrace :: String -> String -> a -> ExtOp a ExtOpBreak :: Loc -> BreakReason -> NonEmpty StackFrame -> a -> ExtOp a ExtOpError :: InterpreterError -> ExtOp a -- | What is the reason for this break point? data BreakReason -- | An explicit breakpoint in the program. BreakPoint :: BreakReason -- | A BreakNaN :: BreakReason data StackFrame StackFrame :: Loc -> Ctx -> StackFrame [stackFrameLoc] :: StackFrame -> Loc [stackFrameCtx] :: StackFrame -> Ctx typeCheckerEnv :: Env -> Env -- | A fully evaluated Futhark value. data Value ValuePrim :: !PrimValue -> Value ValueArray :: ValueShape -> !Array Int Value -> Value ValueRecord :: Map Name Value -> Value fromTuple :: Value -> Maybe [Value] -- | Does the value correspond to an empty array? isEmptyArray :: Value -> Bool -- | String representation of an empty array with the provided element -- type. This is pretty ad-hoc - don't expect good results unless the -- element type is a primitive. prettyEmptyArray :: TypeBase () () -> Value -> String instance Data.Traversable.Traversable Language.Futhark.Interpreter.Shape instance Data.Foldable.Foldable Language.Futhark.Interpreter.Shape instance GHC.Base.Functor Language.Futhark.Interpreter.Shape instance GHC.Show.Show d => GHC.Show.Show (Language.Futhark.Interpreter.Shape d) instance GHC.Classes.Eq d => GHC.Classes.Eq (Language.Futhark.Interpreter.Shape d) instance Control.Monad.State.Class.MonadState Language.Futhark.Interpreter.Sizes Language.Futhark.Interpreter.EvalM instance Control.Monad.Reader.Class.MonadReader (Language.Futhark.Interpreter.Stack, Data.Map.Internal.Map GHC.IO.FilePath Language.Futhark.Interpreter.Env) Language.Futhark.Interpreter.EvalM instance Control.Monad.Free.Class.MonadFree Language.Futhark.Interpreter.ExtOp Language.Futhark.Interpreter.EvalM instance GHC.Base.Functor Language.Futhark.Interpreter.EvalM instance GHC.Base.Applicative Language.Futhark.Interpreter.EvalM instance GHC.Base.Monad Language.Futhark.Interpreter.EvalM instance Data.Loc.Located Language.Futhark.Interpreter.StackFrame instance GHC.Base.Functor Language.Futhark.Interpreter.ExtOp instance GHC.Classes.Eq Language.Futhark.Interpreter.Value instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Interpreter.Value instance GHC.Base.Monoid Language.Futhark.Interpreter.Env instance GHC.Base.Semigroup Language.Futhark.Interpreter.Env instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Interpreter.Indexing instance GHC.Show.Show Language.Futhark.Interpreter.InterpreterError instance Text.PrettyPrint.Mainland.Class.Pretty d => Text.PrettyPrint.Mainland.Class.Pretty (Language.Futhark.Interpreter.Shape d) module Futhark.Internalise.TypesValues internaliseReturnType :: TypeBase (DimDecl VName) () -> [TypeBase shape u] -> InternaliseM [TypeBase ExtShape Uniqueness] internaliseLambdaReturnType :: TypeBase (DimDecl VName) () -> [TypeBase shape u] -> InternaliseM [TypeBase Shape NoUniqueness] -- | As internaliseReturnType, but returns components of a top-level -- tuple type piecemeal. internaliseEntryReturnType :: TypeBase (DimDecl VName) () -> InternaliseM [[TypeBase ExtShape Uniqueness]] internaliseType :: TypeBase (DimDecl VName) () -> InternaliseM [TypeBase ExtShape Uniqueness] internaliseParamTypes :: [TypeBase (DimDecl VName) ()] -> InternaliseM [[TypeBase Shape Uniqueness]] internaliseLoopParamType :: TypeBase (DimDecl VName) () -> [TypeBase shape u] -> InternaliseM [TypeBase Shape Uniqueness] -- | Convert an external primitive to an internal primitive. internalisePrimType :: PrimType -> PrimType -- | How many core language values are needed to represent one source -- language value of the given type? internalisedTypeSize :: TypeBase (DimDecl VName) als -> InternaliseM Int internaliseSumType :: Map Name [StructType] -> InternaliseM ([TypeBase ExtShape Uniqueness], Map Name (Int, [Int])) -- | Convert an external primitive value to an internal primitive value. internalisePrimValue :: PrimValue -> PrimValue instance Control.Monad.State.Class.MonadState Futhark.Internalise.TypesValues.TypeState Futhark.Internalise.TypesValues.InternaliseTypeM instance GHC.Base.Monad Futhark.Internalise.TypesValues.InternaliseTypeM instance GHC.Base.Applicative Futhark.Internalise.TypesValues.InternaliseTypeM instance GHC.Base.Functor Futhark.Internalise.TypesValues.InternaliseTypeM module Futhark.Internalise.Lambdas -- | A function for internalising lambdas. type InternaliseLambda = Exp -> [Type] -> InternaliseM ([LParam], Body, [Type]) internaliseMapLambda :: InternaliseLambda -> Exp -> [SubExp] -> InternaliseM Lambda internaliseStreamMapLambda :: InternaliseLambda -> Exp -> [SubExp] -> InternaliseM Lambda internaliseFoldLambda :: InternaliseLambda -> Exp -> [Type] -> [Type] -> InternaliseM Lambda internaliseStreamLambda :: InternaliseLambda -> Exp -> [Type] -> InternaliseM ([LParam], Body) internalisePartitionLambda :: InternaliseLambda -> Int -> Exp -> [SubExp] -> InternaliseM Lambda -- | Facilities for computing free variables in an expression, which we -- need for both lambda-lifting and defunctionalisation. module Futhark.Internalise.FreeVars -- | Compute the set of free variables of an expression. freeVars :: Exp -> NameSet -- | Set subtraction. without :: NameSet -> Set VName -> NameSet -- | A NameSet with a single Nonunique name. ident :: Ident -> NameSet size :: VName -> NameSet sizes :: Set VName -> NameSet -- | A set of names where we also track uniqueness. newtype NameSet NameSet :: Map VName StructType -> NameSet [unNameSet] :: NameSet -> Map VName StructType -- | Extract all the variable names bound in a pattern. patVars :: Pat -> NameSet instance GHC.Show.Show Futhark.Internalise.FreeVars.NameSet instance GHC.Base.Semigroup Futhark.Internalise.FreeVars.NameSet instance GHC.Base.Monoid Futhark.Internalise.FreeVars.NameSet -- | Internalising bindings. module Futhark.Internalise.Bindings bindingFParams :: [TypeParam] -> [Pat] -> ([FParam] -> [[FParam]] -> InternaliseM a) -> InternaliseM a bindingLoopParams :: [TypeParam] -> Pat -> [Type] -> ([FParam] -> [FParam] -> InternaliseM a) -> InternaliseM a bindingLambdaParams :: [Pat] -> [Type] -> ([LParam] -> InternaliseM a) -> InternaliseM a stmPat :: Pat -> [Type] -> ([VName] -> InternaliseM a) -> InternaliseM a -- | Conversion of a monomorphic, first-order, defunctorised source program -- to a core Futhark program. module Futhark.Internalise.Exps -- | Convert a program in source Futhark to a program in the Futhark core -- language. transformProg :: MonadFreshNames m => Bool -> [ValBind] -> m (Prog SOACS) -- | Functions for generic traversals across Futhark syntax trees. The -- motivation for this module came from dissatisfaction with rewriting -- the same trivial tree recursions for every module. A possible -- alternative would be to use normal "Scrap your -- boilerplate"-techniques, but these are rejected for two reasons: -- --
-- futhark test --module Futhark.CLI.Test -- | Run futhark test. main :: String -> [String] -> IO () instance GHC.Show.Show Futhark.CLI.Test.TestResult instance GHC.Classes.Eq Futhark.CLI.Test.TestResult instance GHC.Show.Show Futhark.CLI.Test.ProgConfig instance GHC.Show.Show Futhark.CLI.Test.TestMode instance GHC.Classes.Eq Futhark.CLI.Test.TestMode instance GHC.Show.Show Futhark.CLI.Test.TestCase instance GHC.Classes.Eq Futhark.CLI.Test.TestCase instance GHC.Classes.Ord Futhark.CLI.Test.TestCase -- |
-- futhark run --module Futhark.CLI.Run -- | Run futhark run. main :: String -> [String] -> IO () -- |
-- futhark query --module Futhark.CLI.Query -- | Run futhark query. main :: String -> [String] -> IO () -- |
-- futhark pkg --module Futhark.CLI.Pkg -- | Run futhark pkg. main :: String -> [String] -> IO () instance Control.Monad.Reader.Class.MonadReader Futhark.CLI.Pkg.PkgConfig Futhark.CLI.Pkg.PkgM instance Control.Monad.IO.Class.MonadIO Futhark.CLI.Pkg.PkgM instance GHC.Base.Applicative Futhark.CLI.Pkg.PkgM instance GHC.Base.Functor Futhark.CLI.Pkg.PkgM instance GHC.Base.Monad Futhark.CLI.Pkg.PkgM instance Control.Monad.Fail.MonadFail Futhark.CLI.Pkg.PkgM instance Futhark.Pkg.Info.MonadPkgRegistry Futhark.CLI.Pkg.PkgM instance Futhark.Util.Log.MonadLogger Futhark.CLI.Pkg.PkgM -- | Various small subcommands that are too simple to deserve their own -- file. module Futhark.CLI.Misc -- |
-- futhark imports --mainImports :: String -> [String] -> IO () -- |
-- futhark hash --mainHash :: String -> [String] -> IO () -- |
-- futhark dataget --mainDataget :: String -> [String] -> IO () -- |
-- futhark literate --module Futhark.CLI.Literate -- | Run futhark script. main :: String -> [String] -> IO () instance GHC.Show.Show Futhark.CLI.Literate.VideoParams instance GHC.Show.Show Futhark.CLI.Literate.Directive instance GHC.Show.Show Futhark.CLI.Literate.Block instance Control.Monad.State.Class.MonadState Futhark.CLI.Literate.State Futhark.CLI.Literate.ScriptM instance Control.Monad.IO.Class.MonadIO Futhark.CLI.Literate.ScriptM instance Control.Monad.Fail.MonadFail Futhark.CLI.Literate.ScriptM instance Control.Monad.Error.Class.MonadError Data.Text.Internal.Text Futhark.CLI.Literate.ScriptM instance GHC.Base.Monad Futhark.CLI.Literate.ScriptM instance GHC.Base.Applicative Futhark.CLI.Literate.ScriptM instance GHC.Base.Functor Futhark.CLI.Literate.ScriptM instance GHC.Show.Show Futhark.CLI.Literate.Failure instance GHC.Classes.Ord Futhark.CLI.Literate.Failure instance GHC.Classes.Eq Futhark.CLI.Literate.Failure instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CLI.Literate.Directive -- |
-- futhark dataset --module Futhark.CLI.Dataset -- | Run futhark dataset. main :: String -> [String] -> IO () instance GHC.Show.Show Futhark.CLI.Dataset.OutputFormat instance GHC.Classes.Ord Futhark.CLI.Dataset.OutputFormat instance GHC.Classes.Eq Futhark.CLI.Dataset.OutputFormat instance System.Random.PCG.Class.Variate Numeric.Half.Internal.Half -- |
-- futhark datacmp --module Futhark.CLI.Datacmp -- | Run futhark datacmp main :: String -> [String] -> IO () -- |
-- futhark check --module Futhark.CLI.Check -- | Run futhark check. main :: String -> [String] -> IO () -- |
-- futhark bench --module Futhark.CLI.Bench -- | Run futhark bench. main :: String -> [String] -> IO () instance GHC.Classes.Eq Futhark.CLI.Bench.SkipReason -- |
-- futhark autotune --module Futhark.CLI.Autotune -- | Run futhark autotune main :: String -> [String] -> IO () instance GHC.Show.Show Futhark.CLI.Autotune.DatasetResult -- | The core logic of futhark doc. module Futhark.Doc.Generator -- | renderFiles important_imports imports produces HTML files -- documenting the type-checked program imports, with the files -- in important_imports considered most important. The HTML -- files must be written to the specific locations indicated in the -- return value, or the relative links will be wrong. renderFiles :: [FilePath] -> Imports -> ([(FilePath, Html)], Warnings) -- |
-- futhark doc --module Futhark.CLI.Doc -- | Run futhark doc. main :: String -> [String] -> IO () -- |
-- futhark repl --module Futhark.CLI.REPL -- | Run futhark repl. main :: String -> [String] -> IO () instance Control.Monad.Error.Class.MonadError Futhark.CLI.REPL.StopReason Futhark.CLI.REPL.FutharkiM instance Control.Monad.IO.Class.MonadIO Futhark.CLI.REPL.FutharkiM instance Control.Monad.State.Class.MonadState Futhark.CLI.REPL.FutharkiState Futhark.CLI.REPL.FutharkiM instance GHC.Base.Monad Futhark.CLI.REPL.FutharkiM instance GHC.Base.Applicative Futhark.CLI.REPL.FutharkiM instance GHC.Base.Functor Futhark.CLI.REPL.FutharkiM -- | All (almost) compiler pipelines end with an Action, which does -- something with the result of the pipeline. module Futhark.Actions -- | Print the result to stdout. printAction :: ASTRep rep => Action rep -- | Print the result to stdout, alias annotations. printAliasesAction :: (ASTRep rep, CanBeAliased (Op rep)) => Action rep -- | Print call graph to stdout. callGraphAction :: Action SOACS -- | Convert the program to sequential ImpCode and print it to stdout. impCodeGenAction :: Action SeqMem -- | Convert the program to GPU ImpCode and print it to stdout. kernelImpCodeGenAction :: Action GPUMem -- | Convert the program to CPU multicore ImpCode and print it to stdout. multicoreImpCodeGenAction :: Action MCMem -- | Print metrics about AST node counts to stdout. metricsAction :: OpMetrics (Op rep) => Action rep -- | The futhark c action. compileCAction :: FutharkConfig -> CompilerMode -> FilePath -> Action SeqMem -- | The futhark wasm action. compileCtoWASMAction :: FutharkConfig -> CompilerMode -> FilePath -> Action SeqMem -- | The futhark opencl action. compileOpenCLAction :: FutharkConfig -> CompilerMode -> FilePath -> Action GPUMem -- | The futhark cuda action. compileCUDAAction :: FutharkConfig -> CompilerMode -> FilePath -> Action GPUMem -- | The futhark multicore action. compileMulticoreAction :: FutharkConfig -> CompilerMode -> FilePath -> Action MCMem -- | The futhark wasm-multicore action. compileMulticoreToWASMAction :: FutharkConfig -> CompilerMode -> FilePath -> Action MCMem -- | The futhark python action. compilePythonAction :: FutharkConfig -> CompilerMode -> FilePath -> Action SeqMem -- | The futhark pyopencl action. compilePyOpenCLAction :: FutharkConfig -> CompilerMode -> FilePath -> Action GPUMem -- |
-- futhark wasm --module Futhark.CLI.WASM -- | Run futhark c main :: String -> [String] -> IO () -- |
-- futhark py --module Futhark.CLI.Python -- | Run futhark py main :: String -> [String] -> IO () -- |
-- futhark pyopencl --module Futhark.CLI.PyOpenCL -- | Run futhark pyopencl. main :: String -> [String] -> IO () -- |
-- futhark opencl --module Futhark.CLI.OpenCL -- | Run futhark opencl main :: String -> [String] -> IO () -- |
-- futhark wasm-multicore --module Futhark.CLI.MulticoreWASM -- | Run futhark c main :: String -> [String] -> IO () -- |
-- futhark multicore --module Futhark.CLI.Multicore -- | Run futhark multicore. main :: String -> [String] -> IO () -- | Futhark Compiler Driver module Futhark.CLI.Dev -- | Entry point. Non-interactive, except when reading interpreter input -- from standard input. main :: String -> [String] -> IO () instance Futhark.CLI.Dev.Representation Futhark.CLI.Dev.UntypedAction instance Futhark.CLI.Dev.Representation Futhark.CLI.Dev.UntypedPassState instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CLI.Dev.UntypedPassState -- |
-- futhark cuda --module Futhark.CLI.CUDA -- | Run futhark cuda. main :: String -> [String] -> IO () -- |
-- futhark c --module Futhark.CLI.C -- | Run futhark c main :: String -> [String] -> IO ()