-- 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: -- --
-- > 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 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 -- | 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 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 Cert :: PrimType -- | A list of all primitive types. allPrimTypes :: [PrimType] -- | 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 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 cert. Checked :: 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 -- | 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 -- | 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.Classes.Ord Futhark.IR.Primitive.FloatValue instance GHC.Classes.Eq 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 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 -- | 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 -- | Whether some operator is commutative or not. The Monoid -- instance returns the least commutative of its arguments. data Commutativity Noncommutative :: Commutativity Commutative :: Commutativity -- | 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 -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> 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 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.Show.Show Language.Futhark.Core.Commutativity instance GHC.Classes.Ord Language.Futhark.Core.Commutativity instance GHC.Classes.Eq Language.Futhark.Core.Commutativity 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.Commutativity instance GHC.Base.Monoid Language.Futhark.Core.Commutativity 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.Decorations 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 -- | 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 -- | A Futhark type is either an array or an element type. When comparing -- types for equality with ==, shapes must match. data TypeBase shape u Prim :: PrimType -> 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 integer value. ErrorInt32 :: 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 cert. Checked :: 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 Certificates Certificates :: [VName] -> Certificates [unCertificates] :: Certificates -> [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 DimFixs, 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. type 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 -- | Pattern element decoration. [patElemDec] :: PatElemT dec -> dec 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.Certificates instance GHC.Classes.Ord Futhark.IR.Syntax.Core.Certificates instance GHC.Classes.Eq Futhark.IR.Syntax.Core.Certificates 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 shape, GHC.Classes.Ord u) => GHC.Classes.Ord (Futhark.IR.Syntax.Core.TypeBase shape u) instance (GHC.Classes.Eq shape, GHC.Classes.Eq u) => GHC.Classes.Eq (Futhark.IR.Syntax.Core.TypeBase shape u) instance (GHC.Show.Show shape, GHC.Show.Show u) => 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.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 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 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.Certificates instance GHC.Base.Monoid Futhark.IR.Syntax.Core.Certificates 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 GHC.Base.Semigroup (Futhark.IR.Syntax.Core.ShapeBase d) instance GHC.Base.Monoid (Futhark.IR.Syntax.Core.ShapeBase d) instance GHC.Base.Functor Futhark.IR.Syntax.Core.ShapeBase -- | 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.Types.Int 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 -- | Return the immediate row-type of an array. For [[int]], this -- would be [int]. rowType :: ArrayShape shape => TypeBase shape u -> TypeBase shape u -- | Returns the bottommost type of an array. For [[int]], this -- would be int. If the given type is not an array, it is -- returned. elemType :: TypeBase shape u -> PrimType -- | 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 -- | 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 -- | 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 set of identifiers used for the shape context in the given -- ExtTypes. shapeContext :: [TypeBase ExtShape u] -> Set Int -- | If all dimensions of the given ExtType are statically known, -- return the corresponding list of Type. hasStaticShape :: ExtType -> Maybe Type -- | 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] -- | In the call shapeMapping ts1 ts2, the lists ts1 and -- ts must be of equal length and their corresponding elements -- have the same types modulo exact dimensions (but matching array rank -- is important). The result is a mapping from named dimensions of -- ts1 to a set of the corresponding dimensions in ts2 -- (because they may not fit exactly). -- -- This function is useful when ts1 are the value parameters of -- some function and ts2 are the value arguments, and we need to -- figure out which shape context to pass. shapeMapping :: [TypeBase Shape u0] -> [TypeBase Shape u1] -> Map VName (Set SubExp) -- | Like shapeMapping, but produces 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 value parameter 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 lore type -- parameter, which is then used to invoke the type families defined -- here. module Futhark.IR.Decorations -- | A collection of type families, 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)) => Decorations 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 -- | 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 -- | 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 -- | 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 -- lore-specific operation. Do-loops, branches and function calls are -- special. Everything else is a simple BasicOp. data ExpT lore -- | A simple (non-recursive) operation. BasicOp :: BasicOp -> ExpT lore Apply :: Name -> [(SubExp, Diet)] -> [RetType lore] -> (Safety, SrcLoc, [SrcLoc]) -> ExpT lore If :: SubExp -> BodyT lore -> BodyT lore -> IfDec (BranchType lore) -> ExpT lore -- | loop {a} = {v} (for i < n|while b) do b. The merge -- parameters are divided into context and value part. DoLoop :: [(FParam lore, SubExp)] -> [(FParam lore, SubExp)] -> LoopForm lore -> BodyT lore -> ExpT lore Op :: Op lore -> ExpT lore -- | A type alias for namespace control. type Exp = ExpT -- | For-loop or while-loop? data LoopForm lore ForLoop :: VName -> IntType -> SubExp -> [(LParam lore, VName)] -> LoopForm lore WhileLoop :: VName -> LoopForm lore -- | 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 lore Lambda :: [LParam lore] -> BodyT lore -> [Type] -> LambdaT lore [lambdaParams] :: LambdaT lore -> [LParam lore] [lambdaBody] :: LambdaT lore -> BodyT lore [lambdaReturnType] :: LambdaT lore -> [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 lore = Param (FParamInfo lore) -- | A lambda parameter. type LParam lore = Param (LParamInfo lore) -- | Function Declarations data FunDef lore FunDef :: Maybe EntryPoint -> Attrs -> Name -> [RetType lore] -> [FParam lore] -> BodyT lore -> FunDef lore -- | Contains a value if this function is an entry point. [funDefEntryPoint] :: FunDef lore -> Maybe EntryPoint [funDefAttrs] :: FunDef lore -> Attrs [funDefName] :: FunDef lore -> Name [funDefRetType] :: FunDef lore -> [RetType lore] [funDefParams] :: FunDef lore -> [FParam lore] [funDefBody] :: FunDef lore -> BodyT lore -- | Information about the parameters and return value of an entry point. -- The first element is for parameters, the second for return value. type EntryPoint = ([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 :: EntryPointType -- | A black box type comprising this many core values. The string is a -- human-readable description with no other semantics. TypeOpaque :: String -> Int -> EntryPointType -- | Maps directly. TypeDirect :: EntryPointType -- | An entire Futhark program. data Prog lore Prog :: Stms lore -> [FunDef lore] -> Prog lore -- | Top-level constants that are computed at program startup, and which -- are in scope inside all functions. [progConsts] :: Prog lore -> Stms lore -- | 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 lore -> [FunDef lore] -- | A single statement. oneStm :: Stm lore -> Stms lore -- | Convert a statement list to a statement sequence. stmsFromList :: [Stm lore] -> Stms lore -- | Convert a statement sequence to a statement list. stmsToList :: Stms lore -> [Stm lore] -- | The first statement in the sequence, if any. stmsHead :: Stms lore -> Maybe (Stm lore, Stms lore) 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.PatternT dec) instance GHC.Show.Show dec => GHC.Show.Show (Futhark.IR.Syntax.PatternT dec) instance GHC.Classes.Ord dec => GHC.Classes.Ord (Futhark.IR.Syntax.PatternT 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 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.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.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.Syntax.Prog lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.Syntax.Prog lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.Syntax.Prog lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.Syntax.Stm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.Syntax.Stm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.Syntax.Stm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.Syntax.BodyT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.Syntax.BodyT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.Syntax.BodyT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.Syntax.ExpT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.Syntax.ExpT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.Syntax.ExpT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.Syntax.LoopForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.Syntax.LoopForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.Syntax.LoopForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.Syntax.LambdaT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.Syntax.LambdaT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.Syntax.LambdaT lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.Syntax.FunDef lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.Syntax.FunDef lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.Syntax.FunDef lore) 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.PatternT dec) instance GHC.Base.Monoid (Futhark.IR.Syntax.PatternT dec) instance GHC.Base.Functor Futhark.IR.Syntax.PatternT instance Data.Foldable.Foldable Futhark.IR.Syntax.PatternT instance Data.Traversable.Traversable Futhark.IR.Syntax.PatternT 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 lore -- | 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 Patterns, 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 lore of a PatElem. setPatElemLore :: PatElemT oldattr -> newattr -> PatElemT newattr -- | All pattern elements in the pattern - context first, then values. patternElements :: PatternT dec -> [PatElemT dec] -- | Return a list of the Idents bound by the Pattern. patternIdents :: Typed dec => PatternT dec -> [Ident] -- | Return a list of the context Idents bound by the -- Pattern. patternContextIdents :: Typed dec => PatternT dec -> [Ident] -- | Return a list of the value Idents bound by the Pattern. patternValueIdents :: Typed dec => PatternT dec -> [Ident] -- | Return a list of the Names bound by the Pattern. patternNames :: PatternT dec -> [VName] -- | Return a list of the Names bound by the value part of the -- Pattern. patternValueNames :: PatternT dec -> [VName] -- | Return a list of the Names bound by the context part of the -- Pattern. patternContextNames :: PatternT dec -> [VName] -- | Return a list of the typess bound by the pattern. patternTypes :: Typed dec => PatternT dec -> [Type] -- | Return a list of the typess bound by the value part of the pattern. patternValueTypes :: Typed dec => PatternT dec -> [Type] -- | Return the number of names bound by the pattern. patternSize :: PatternT dec -> Int -- | Create a pattern using Type as the attribute. basicPattern :: [Ident] -> [Ident] -> PatternT 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 -- | Class for values that may have some prettyprinted annotation. class PrettyAnnot a ppAnnot :: PrettyAnnot a => a -> Maybe Doc -- | The class of lores whose annotations can be prettyprinted. class (Decorations lore, Pretty (RetType lore), Pretty (BranchType lore), Pretty (Param (FParamInfo lore)), Pretty (Param (LParamInfo lore)), Pretty (PatElemT (LetDec lore)), PrettyAnnot (PatElem lore), PrettyAnnot (FParam lore), PrettyAnnot (LParam lore), Pretty (Op lore)) => PrettyLore lore ppExpLore :: PrettyLore lore => ExpDec lore -> Exp lore -> Maybe Doc -- | Like prettyTuple, but produces a Doc. ppTuple' :: Pretty a => [a] -> Doc instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Stms lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Body lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Stm lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Exp lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Lambda lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.FunDef lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Prog lore) instance Futhark.IR.Pretty.PrettyAnnot (Futhark.IR.Syntax.Core.PatElemT (Futhark.IR.Syntax.Core.TypeBase shape u)) instance Futhark.IR.Pretty.PrettyAnnot (Futhark.IR.Syntax.Core.Param (Futhark.IR.Syntax.Core.TypeBase shape u)) instance Futhark.IR.Pretty.PrettyAnnot () instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.VName instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Core.NoUniqueness instance Text.PrettyPrint.Mainland.Class.Pretty Language.Futhark.Core.Commutativity 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.Certificates instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.Syntax.Attr instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.PatElemT dec) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.PatternT dec) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.PatElemT b) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.PatElemT (a, b)) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.PatElemT Futhark.IR.Syntax.Core.Type) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Param b) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Param (a, b)) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Param Futhark.IR.Syntax.Core.DeclType) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Param Futhark.IR.Syntax.Core.Type) 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 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, Decorations lore) => HasScope lore m | m -> lore -- | Return the type of the given variable, or fail if it is not in the -- type environment. lookupType :: HasScope lore m => VName -> m Type -- | Return the info of the given variable, or fail if it is not in the -- type environment. lookupInfo :: HasScope lore m => VName -> m (NameInfo lore) -- | Return the type environment contained in the applicative functor. askScope :: HasScope lore m => m (Scope lore) -- | Return the result of applying some function to the type environment. asksScope :: HasScope lore m => (Scope lore -> a) -> m a -- | How some name in scope was bound. data NameInfo lore LetName :: LetDec lore -> NameInfo lore FParamName :: FParamInfo lore -> NameInfo lore LParamName :: LParamInfo lore -> NameInfo lore IndexName :: IntType -> NameInfo lore -- | 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 lore m, Monad m) => LocalScope lore 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 lore m => Scope lore -> m a -> m a -- | A scope is a mapping from variable names to information about that -- name. type Scope lore = Map VName (NameInfo lore) -- | 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 lore a | a -> lore scopeOf :: Scoped lore a => a -> Scope lore -- | Extend the monadic scope with the scopeOf the given value. inScopeOf :: (Scoped lore a, LocalScope lore m) => a -> m b -> m b -- | The scope of some lambda parameters. scopeOfLParams :: LParamInfo lore ~ dec => [Param dec] -> Scope lore -- | The scope of some function or loop parameters. scopeOfFParams :: FParamInfo lore ~ dec => [Param dec] -> Scope lore -- | The scope of a pattern. scopeOfPattern :: LetDec lore ~ dec => PatternT dec -> Scope lore -- | The scope of a pattern element. scopeOfPatElem :: LetDec lore ~ dec => PatElemT dec -> Scope lore -- | A constraint that indicates two lores have the same NameInfo -- representation. type SameScope lore1 lore2 = (LetDec lore1 ~ LetDec lore2, FParamInfo lore1 ~ FParamInfo lore2, LParamInfo lore1 ~ LParamInfo lore2) -- | If two scopes are really the same, then you can convert one to the -- other. castScope :: SameScope fromlore tolore => Scope fromlore -> Scope tolore -- | 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 lore m a -- | Run a computation in the extended type environment. extendedScope :: ExtendedScope lore m a -> Scope lore -> m a instance GHC.Base.Monad m => Control.Monad.Reader.Class.MonadReader (Futhark.IR.Prop.Scope.Scope lore) (Futhark.IR.Prop.Scope.ExtendedScope lore m) instance GHC.Base.Monad m => GHC.Base.Monad (Futhark.IR.Prop.Scope.ExtendedScope lore m) instance GHC.Base.Applicative m => GHC.Base.Applicative (Futhark.IR.Prop.Scope.ExtendedScope lore m) instance GHC.Base.Functor m => GHC.Base.Functor (Futhark.IR.Prop.Scope.ExtendedScope lore m) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.Prop.Scope.NameInfo lore) instance (Futhark.IR.Prop.Scope.HasScope lore m, GHC.Base.Monad m) => Futhark.IR.Prop.Scope.HasScope lore (Futhark.IR.Prop.Scope.ExtendedScope lore m) instance Futhark.IR.Prop.Scope.Scoped lore a => Futhark.IR.Prop.Scope.Scoped lore [a] instance Futhark.IR.Prop.Scope.Scoped lore (Futhark.IR.Syntax.Stms lore) instance Futhark.IR.Prop.Scope.Scoped lore (Futhark.IR.Syntax.Stm lore) instance Futhark.IR.Prop.Scope.Scoped lore (Futhark.IR.Syntax.FunDef lore) instance Futhark.IR.Prop.Scope.Scoped lore (Language.Futhark.Core.VName, Futhark.IR.Prop.Scope.NameInfo lore) instance Futhark.IR.Prop.Scope.Scoped lore (Futhark.IR.Syntax.LoopForm lore) instance Futhark.IR.Prop.Scope.Scoped lore (Futhark.IR.Syntax.Lambda lore) instance (GHC.Base.Monad m, Futhark.IR.Prop.Scope.LocalScope lore m) => Futhark.IR.Prop.Scope.LocalScope lore (Control.Monad.Trans.Except.ExceptT e m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, Futhark.IR.Decorations.Decorations lore) => Futhark.IR.Prop.Scope.LocalScope lore (Control.Monad.Trans.Reader.ReaderT (Futhark.IR.Prop.Scope.Scope lore) m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.IR.Decorations.Decorations lore) => Futhark.IR.Prop.Scope.LocalScope lore (Control.Monad.Trans.RWS.Strict.RWST (Futhark.IR.Prop.Scope.Scope lore) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.IR.Decorations.Decorations lore) => Futhark.IR.Prop.Scope.LocalScope lore (Control.Monad.Trans.RWS.Lazy.RWST (Futhark.IR.Prop.Scope.Scope lore) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, Futhark.IR.Decorations.Decorations lore) => Futhark.IR.Prop.Scope.HasScope lore (Control.Monad.Trans.Reader.ReaderT (Futhark.IR.Prop.Scope.Scope lore) m) instance (GHC.Base.Monad m, Futhark.IR.Prop.Scope.HasScope lore m) => Futhark.IR.Prop.Scope.HasScope lore (Control.Monad.Trans.Except.ExceptT e m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.IR.Decorations.Decorations lore) => Futhark.IR.Prop.Scope.HasScope lore (Control.Monad.Trans.RWS.Strict.RWST (Futhark.IR.Prop.Scope.Scope lore) w s m) instance (GHC.Base.Applicative m, GHC.Base.Monad m, GHC.Base.Monoid w, Futhark.IR.Decorations.Decorations lore) => Futhark.IR.Prop.Scope.HasScope lore (Control.Monad.Trans.RWS.Lazy.RWST (Futhark.IR.Prop.Scope.Scope lore) w s m) instance Futhark.IR.Decorations.Decorations lore => Futhark.IR.Prop.Types.Typed (Futhark.IR.Prop.Scope.NameInfo lore) -- | 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 lore, MonadFreshNames m) => Prog lore -> m (Prog lore) -- | 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 lore, MonadFreshNames m) => Exp lore -> m (Exp lore) -- | 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 lore, MonadFreshNames m) => Stm lore -> m (Stm lore) -- | 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 lore, MonadFreshNames m) => Body lore -> m (Body lore) -- | 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 lore, MonadFreshNames m) => Lambda lore -> m (Lambda lore) -- | Produce an equivalent pattern but with each pattern element given a -- new name. renamePattern :: (Rename dec, MonadFreshNames m) => PatternT dec -> m (PatternT dec) -- | 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 lore => Stms lore -> (Stms lore -> 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 -- | Lores in which all annotations are renameable. type Renameable lore = (Rename (LetDec lore), Rename (ExpDec lore), Rename (BodyDec lore), Rename (FParamInfo lore), Rename (LParamInfo lore), Rename (RetType lore), Rename (BranchType lore), Rename (Op lore)) 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 lore => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.FunDef lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Body lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Stm lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Exp lore) instance Futhark.Transform.Rename.Renameable lore => Futhark.Transform.Rename.Rename (Futhark.IR.Syntax.Lambda lore) 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.PatternT 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.Certificates 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 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 lore -> 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 lore) => Exp lore -> 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 -- | Return the variable dimension sizes. May contain duplicates. shapeVars :: Shape -> [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 lore -> 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 Certificates. defAux :: dec -> StmAux dec -- | The certificates associated with a statement. stmCerts :: Stm lore -> Certificates -- | Add certificates to a statement. certify :: Certificates -> Stm lore -> Stm lore -- | Construct the type of an expression that would match the pattern. expExtTypesFromPattern :: Typed dec => PatternT dec -> [ExtType] -- | Keep only those attributes that are relevant for Assert -- expressions. attrsForAssert :: Attrs -> Attrs -- | 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 -- | Lore-specific attributes; also means the lore supports some basic -- facilities. class (Decorations lore, PrettyLore lore, Renameable lore, Substitutable lore, FreeDec (ExpDec lore), FreeIn (LetDec lore), FreeDec (BodyDec lore), FreeIn (FParamInfo lore), FreeIn (LParamInfo lore), FreeIn (RetType lore), FreeIn (BranchType lore), IsOp (Op lore)) => ASTLore lore -- | Given a pattern, construct the type of a body that would match it. An -- implementation for many lores would be expExtTypesFromPattern. expTypesFromPattern :: (ASTLore lore, HasScope lore m, Monad m) => Pattern lore -> m [BranchType lore] 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 lore => Exp lore -> [Names] -- | The aliases of each pattern element (including the context). patternAliases :: AliasesOf dec => PatternT dec -> [Names] -- | The class of lores that contain aliasing information. class (Decorations lore, AliasedOp (Op lore), AliasesOf (LetDec lore)) => Aliased lore -- | The aliases of the body results. bodyAliases :: Aliased lore => Body lore -> [Names] -- | The variables consumed in the body. consumedInBody :: Aliased lore => Body lore -> 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 lore => Stm lore -> Names -- | The variables consumed in this expression. consumedInExp :: Aliased lore => Exp lore -> Names -- | The variables consumed by this lambda. consumedByLambda :: Aliased lore => Lambda lore -> 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 "lore 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 => 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. Note that -- Futhark.IR.Lore is not exported, as this would cause name -- clashes. You are advised to use a qualified import of the lore module, -- if you need it. 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 :: (ASTLore lore, Aliased lore) => Stm lore -> 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 lore 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. rephrasePattern :: Monad m => (from -> m to) -> PatternT from -> m (PatternT 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 lore 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 [rephraseExpLore] :: Rephraser m from to -> ExpDec from -> m (ExpDec to) [rephraseLetBoundLore] :: Rephraser m from to -> LetDec from -> m (LetDec to) [rephraseFParamLore] :: Rephraser m from to -> FParamInfo from -> m (FParamInfo to) [rephraseLParamLore] :: Rephraser m from to -> LParamInfo from -> m (LParamInfo to) [rephraseBodyLore] :: 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 lore) => Prog lore -> 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 lore) => Stm lore -> MetricsM () -- | Compute metrics for this lambda. lambdaMetrics :: OpMetrics (Op lore) => Lambda lore -> 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 () instance GHC.Base.Semigroup Futhark.Analysis.Metrics.CountMetrics instance GHC.Base.Monoid Futhark.Analysis.Metrics.CountMetrics instance GHC.Show.Show Futhark.Analysis.Metrics.AstMetrics instance GHC.Read.Read Futhark.Analysis.Metrics.AstMetrics -- | 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 :: ASTLore lore => Body lore -> 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 lore. 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 lore to a -- Prog of another lore. data Pass fromlore tolore Pass :: String -> String -> (Prog fromlore -> PassM (Prog tolore)) -> Pass fromlore tolore -- | 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 fromlore tolore -> String -- | A slightly longer description, which will show up in the command-line -- help text. [passDescription] :: Pass fromlore tolore -> String [passFunction] :: Pass fromlore tolore -> Prog fromlore -> PassM (Prog tolore) -- | Take the name of the pass, turn spaces into dashes, and make all -- characters lowercase. passLongOption :: Pass fromlore tolore -> 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 lore -> Stms lore -> PassM (Stms lore)) -> Prog lore -> PassM (Prog lore) -- | 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 fromlore -> PassM (Stms tolore)) -> (Stms tolore -> FunDef fromlore -> PassM (FunDef tolore)) -> Prog fromlore -> PassM (Prog tolore) 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.Binder.Class -- | The class of lores 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 -- MonadBinder instance, it is acceptable for them to create new -- bindings, however. class (ASTLore lore, FParamInfo lore ~ DeclType, LParamInfo lore ~ Type, RetType lore ~ DeclExtType, BranchType lore ~ ExtType, SetType (LetDec lore)) => Bindable lore mkExpPat :: Bindable lore => [Ident] -> [Ident] -> Exp lore -> Pattern lore mkExpDec :: Bindable lore => Pattern lore -> Exp lore -> ExpDec lore mkBody :: Bindable lore => Stms lore -> Result -> Body lore mkLetNames :: (Bindable lore, MonadFreshNames m, HasScope lore m) => [VName] -> Exp lore -> m (Stm lore) -- | Construct a Stm from identifiers for the context- and value -- part of the pattern, as well as the expression. mkLet :: Bindable lore => [Ident] -> [Ident] -> Exp lore -> Stm lore -- | Like mkLet, but also take attributes and certificates from the given -- StmAux. mkLet' :: Bindable lore => [Ident] -> [Ident] -> StmAux a -> Exp lore -> Stm lore -- | A monad that supports the creation of bindings from expressions and -- bodies from bindings, with a specific lore. 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 (ASTLore (Lore m), MonadFreshNames m, Applicative m, Monad m, LocalScope (Lore m) m) => MonadBinder m where { type family Lore m :: Type; } mkExpDecM :: MonadBinder m => Pattern (Lore m) -> Exp (Lore m) -> m (ExpDec (Lore m)) mkBodyM :: MonadBinder m => Stms (Lore m) -> Result -> m (Body (Lore m)) mkLetNamesM :: MonadBinder m => [VName] -> Exp (Lore m) -> m (Stm (Lore m)) -- | Add a statement to the Stms under construction. addStm :: MonadBinder m => Stm (Lore m) -> m () -- | Add multiple statements to the Stms under construction. addStms :: MonadBinder m => Stms (Lore m) -> m () -- | Obtain the statements constructed during a monadic action, instead of -- adding them to the state. collectStms :: MonadBinder m => m a -> m (a, Stms (Lore m)) -- | Add the provided certificates to any statements added during execution -- of the action. certifying :: MonadBinder m => Certificates -> m a -> m a -- | Add several bindings at the outermost level of a Body. insertStms :: Bindable lore => Stms lore -> Body lore -> Body lore -- | Add a single binding at the outermost level of a Body. insertStm :: Bindable lore => Stm lore -> Body lore -> Body lore -- | Add a statement with the given pattern and expression. letBind :: MonadBinder m => Pattern (Lore m) -> Exp (Lore m) -> m () -- | Add a statement with the given pattern element names and expression. letBindNames :: MonadBinder m => [VName] -> Exp (Lore m) -> m () -- | As collectStms, but throw away the ordinary result. collectStms_ :: MonadBinder m => m a -> m (Stms (Lore m)) -- | Add the statements of the body, then return the body result. bodyBind :: MonadBinder m => Body (Lore m) -> m [SubExp] -- | Add the given attributes to any statements added by this action. attributing :: MonadBinder m => Attrs -> m a -> m a -- | Add the certificates and attributes to any statements added by this -- action. auxing :: MonadBinder m => StmAux anylore -> m a -> m a -- | This module defines a convenience monad/typeclass for creating -- normalised programs. The fundamental building block is BinderT -- and its execution functions, but it is usually easier to use -- Binder. -- -- See Futhark.Construct for a high-level description. module Futhark.Binder -- | A monad transformer that tracks statements and provides a -- MonadBinder 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 MonadBinder -- from scratch, then it is likely that you are making a mistake. data BinderT lore m a -- | Run a binder action given an initial scope, returning a value and the -- statements added (addStm) during the action. runBinderT :: MonadFreshNames m => BinderT lore m a -> Scope lore -> m (a, Stms lore) -- | Like runBinderT, but return only the statements. runBinderT_ :: MonadFreshNames m => BinderT lore m () -> Scope lore -> m (Stms lore) -- | Like runBinderT, but get the initial scope from the current -- monad. runBinderT' :: (MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => BinderT lore m a -> m (a, Stms lore) -- | Like runBinderT_, but get the initial scope from the current -- monad. runBinderT'_ :: (MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => BinderT lore m a -> m (Stms lore) -- | A BinderT (and by extension, a Binder) is only an -- instance of MonadBinder for lores that implement this type -- class, which contains methods for constructing statements. class ASTLore lore => BinderOps lore mkExpDecB :: (BinderOps lore, MonadBinder m, Lore m ~ lore) => Pattern lore -> Exp lore -> m (ExpDec lore) mkBodyB :: (BinderOps lore, MonadBinder m, Lore m ~ lore) => Stms lore -> Result -> m (Body lore) mkLetNamesB :: (BinderOps lore, MonadBinder m, Lore m ~ lore) => [VName] -> Exp lore -> m (Stm lore) mkExpDecB :: (BinderOps lore, MonadBinder m, Bindable lore) => Pattern lore -> Exp lore -> m (ExpDec lore) mkBodyB :: (BinderOps lore, MonadBinder m, Bindable lore) => Stms lore -> Result -> m (Body lore) mkLetNamesB :: (BinderOps lore, MonadBinder m, Lore m ~ lore, Bindable lore) => [VName] -> Exp lore -> m (Stm lore) -- | The most commonly used binder monad. type Binder lore = BinderT lore (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. runBinder :: (MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => Binder lore a -> m (a, Stms lore) -- | Like runBinder, but throw away the result and just return the -- added statements. runBinder_ :: (MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => Binder lore a -> m (Stms lore) -- | Run a binder that produces a Body, and prefix that Body -- by the statements produced during execution of the action. runBodyBinder :: (Bindable lore, MonadFreshNames m, HasScope somelore m, SameScope somelore lore) => Binder lore (Body lore) -> m (Body lore) instance GHC.Base.Monad m => GHC.Base.Applicative (Futhark.Binder.BinderT lore m) instance GHC.Base.Monad m => GHC.Base.Monad (Futhark.Binder.BinderT lore m) instance GHC.Base.Functor m => GHC.Base.Functor (Futhark.Binder.BinderT lore m) instance Control.Monad.Trans.Class.MonadTrans (Futhark.Binder.BinderT lore) instance Futhark.MonadFreshNames.MonadFreshNames m => Futhark.MonadFreshNames.MonadFreshNames (Futhark.Binder.BinderT lore m) instance (Futhark.IR.Prop.ASTLore lore, GHC.Base.Monad m) => Futhark.IR.Prop.Scope.HasScope lore (Futhark.Binder.BinderT lore m) instance (Futhark.IR.Prop.ASTLore lore, GHC.Base.Monad m) => Futhark.IR.Prop.Scope.LocalScope lore (Futhark.Binder.BinderT lore m) instance (Futhark.IR.Prop.ASTLore lore, Futhark.MonadFreshNames.MonadFreshNames m, Futhark.Binder.BinderOps lore) => Futhark.Binder.Class.MonadBinder (Futhark.Binder.BinderT lore m) instance Control.Monad.Reader.Class.MonadReader r m => Control.Monad.Reader.Class.MonadReader r (Futhark.Binder.BinderT lore m) instance Control.Monad.State.Class.MonadState s m => Control.Monad.State.Class.MonadState s (Futhark.Binder.BinderT lore m) instance Control.Monad.Writer.Class.MonadWriter w m => Control.Monad.Writer.Class.MonadWriter w (Futhark.Binder.BinderT lore m) instance Control.Monad.Error.Class.MonadError e m => Control.Monad.Error.Class.MonadError e (Futhark.Binder.BinderT lore m) -- | A representation where all bindings are annotated with aliasing -- information. module Futhark.IR.Aliases -- | The lore for the basic representation. data Aliases lore -- | 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) addAliasesToPattern :: (ASTLore lore, CanBeAliased (Op lore), Typed dec) => PatternT dec -> Exp (Aliases lore) -> PatternT (VarAliases, dec) mkAliasedLetStm :: (ASTLore lore, CanBeAliased (Op lore)) => Pattern lore -> StmAux (ExpDec lore) -> Exp (Aliases lore) -> Stm (Aliases lore) mkAliasedBody :: (ASTLore lore, CanBeAliased (Op lore)) => BodyDec lore -> Stms (Aliases lore) -> Result -> Body (Aliases lore) mkPatternAliases :: (Aliased lore, Typed dec) => PatternT dec -> Exp lore -> ([PatElemT (VarAliases, dec)], [PatElemT (VarAliases, dec)]) mkBodyAliases :: Aliased lore => Stms lore -> Result -> BodyAliasing removeProgAliases :: CanBeAliased (Op lore) => Prog (Aliases lore) -> Prog lore removeFunDefAliases :: CanBeAliased (Op lore) => FunDef (Aliases lore) -> FunDef lore removeExpAliases :: CanBeAliased (Op lore) => Exp (Aliases lore) -> Exp lore removeStmAliases :: CanBeAliased (Op lore) => Stm (Aliases lore) -> Stm lore removeLambdaAliases :: CanBeAliased (Op lore) => Lambda (Aliases lore) -> Lambda lore removePatternAliases :: PatternT (AliasDec, a) -> PatternT a removeScopeAliases :: Scope (Aliases lore) -> Scope lore type AliasesAndConsumed = (Map VName Names, Names) trackAliases :: Aliased lore => AliasesAndConsumed -> Stm lore -> AliasesAndConsumed -- | Everything consumed in the given statements and result (even -- transitively). consumedInStms :: Aliased lore => Stms lore -> Names instance GHC.Show.Show Futhark.IR.Aliases.AliasDec instance (Futhark.IR.Decorations.Decorations lore, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Decorations.Decorations (Futhark.IR.Aliases.Aliases lore) instance Futhark.IR.Prop.Aliases.AliasesOf (Futhark.IR.Aliases.VarAliases, dec) instance Futhark.IR.Pretty.PrettyAnnot (Futhark.IR.Syntax.Core.PatElemT dec) => Futhark.IR.Pretty.PrettyAnnot (Futhark.IR.Syntax.Core.PatElemT (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.ASTLore lore, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Prop.Aliases.Aliased (Futhark.IR.Aliases.Aliases lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Pretty.PrettyLore (Futhark.IR.Aliases.Aliases lore) instance (Futhark.Binder.Class.Bindable lore, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Decorations.Op lore)) => Futhark.Binder.Class.Bindable (Futhark.IR.Aliases.Aliases lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Prop.ASTLore (Futhark.IR.Aliases.Aliases lore) instance (Futhark.IR.Prop.ASTLore (Futhark.IR.Aliases.Aliases lore), Futhark.Binder.Class.Bindable (Futhark.IR.Aliases.Aliases lore)) => Futhark.Binder.BinderOps (Futhark.IR.Aliases.Aliases lore) -- | Definition of the lore used by the simplification engine. module Futhark.Optimise.Simplify.Lore data Wise lore -- | The wisdom of the let-bound variable. newtype VarWisdom VarWisdom :: VarAliases -> VarWisdom [varWisdomAliases] :: VarWisdom -> VarAliases -- | Wisdom about an expression. data ExpWisdom removeStmWisdom :: CanBeWise (Op lore) => Stm (Wise lore) -> Stm lore removeLambdaWisdom :: CanBeWise (Op lore) => Lambda (Wise lore) -> Lambda lore removeFunDefWisdom :: CanBeWise (Op lore) => FunDef (Wise lore) -> FunDef lore removeExpWisdom :: CanBeWise (Op lore) => Exp (Wise lore) -> Exp lore removePatternWisdom :: PatternT (VarWisdom, a) -> PatternT a removeBodyWisdom :: CanBeWise (Op lore) => Body (Wise lore) -> Body lore removeScopeWisdom :: Scope (Wise lore) -> Scope lore addScopeWisdom :: Scope lore -> Scope (Wise lore) addWisdomToPattern :: (ASTLore lore, CanBeWise (Op lore)) => Pattern lore -> Exp (Wise lore) -> Pattern (Wise lore) mkWiseBody :: (ASTLore lore, CanBeWise (Op lore)) => BodyDec lore -> Stms (Wise lore) -> Result -> Body (Wise lore) mkWiseLetStm :: (ASTLore lore, CanBeWise (Op lore)) => Pattern lore -> StmAux (ExpDec lore) -> Exp (Wise lore) -> Stm (Wise lore) mkWiseExpDec :: (ASTLore lore, CanBeWise (Op lore)) => Pattern (Wise lore) -> ExpDec lore -> Exp (Wise lore) -> ExpDec (Wise lore) 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.Lore.VarWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Lore.VarWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Lore.VarWisdom instance GHC.Show.Show Futhark.Optimise.Simplify.Lore.ExpWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Lore.ExpWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Lore.ExpWisdom instance GHC.Show.Show Futhark.Optimise.Simplify.Lore.BodyWisdom instance GHC.Classes.Ord Futhark.Optimise.Simplify.Lore.BodyWisdom instance GHC.Classes.Eq Futhark.Optimise.Simplify.Lore.BodyWisdom instance (Futhark.IR.Decorations.Decorations lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Decorations.Decorations (Futhark.Optimise.Simplify.Lore.Wise lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Prop.ASTLore (Futhark.Optimise.Simplify.Lore.Wise lore) instance (Futhark.IR.Pretty.PrettyLore lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Pretty.PrettyLore (Futhark.Optimise.Simplify.Lore.Wise lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Prop.Aliases.Aliased (Futhark.Optimise.Simplify.Lore.Wise lore) instance (Futhark.Binder.Class.Bindable lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.Decorations.Op lore)) => Futhark.Binder.Class.Bindable (Futhark.Optimise.Simplify.Lore.Wise lore) instance Futhark.Optimise.Simplify.Lore.CanBeWise () instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Lore.BodyWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Lore.BodyWisdom instance Futhark.IR.Prop.Names.FreeIn Futhark.Optimise.Simplify.Lore.BodyWisdom instance Futhark.IR.Prop.Names.FreeDec Futhark.Optimise.Simplify.Lore.BodyWisdom instance Futhark.IR.Prop.Names.FreeIn Futhark.Optimise.Simplify.Lore.ExpWisdom instance Futhark.IR.Prop.Names.FreeDec Futhark.Optimise.Simplify.Lore.ExpWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Lore.ExpWisdom instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Lore.ExpWisdom instance Futhark.Transform.Rename.Rename Futhark.Optimise.Simplify.Lore.VarWisdom instance Futhark.Transform.Substitute.Substitute Futhark.Optimise.Simplify.Lore.VarWisdom instance Futhark.IR.Prop.Names.FreeIn Futhark.Optimise.Simplify.Lore.VarWisdom instance Futhark.IR.Pretty.PrettyAnnot (Futhark.IR.Syntax.Core.PatElemT dec) => Futhark.IR.Pretty.PrettyAnnot (Futhark.IR.Syntax.Core.PatElemT (Futhark.Optimise.Simplify.Lore.VarWisdom, dec)) instance Futhark.IR.Prop.Aliases.AliasesOf (Futhark.Optimise.Simplify.Lore.VarWisdom, dec) -- | Alias analysis of a full Futhark program. Takes as input a program -- with an arbitrary lore 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 :: (ASTLore lore, CanBeAliased (Op lore)) => Prog lore -> Prog (Aliases lore) -- | Pre-existing aliases for variables. Used to add transitive aliases. type AliasTable = Map VName Names analyseFun :: (ASTLore lore, CanBeAliased (Op lore)) => FunDef lore -> FunDef (Aliases lore) analyseStms :: (ASTLore lore, CanBeAliased (Op lore)) => AliasTable -> Stms lore -> (Stms (Aliases lore), AliasesAndConsumed) analyseExp :: (ASTLore lore, CanBeAliased (Op lore)) => AliasTable -> Exp lore -> Exp (Aliases lore) analyseBody :: (ASTLore lore, CanBeAliased (Op lore)) => AliasTable -> Body lore -> Body (Aliases lore) analyseLambda :: (ASTLore lore, CanBeAliased (Op lore)) => Lambda lore -> Lambda (Aliases lore) -- |
-- z <- letExp "z" $ BasicOp $ BinOp (Add Int32) (Var x) (Var y) ---- --
-- Scatter cs length lambda index and value arrays ---- -- <input/output arrays along with their sizes and number of values to -- write for that array> -- -- length is the length of each index array and value array, since -- they all must be the same length for any fusion to make sense. If you -- have a list of index-value array pairs of different sizes, you need to -- use multiple writes instead. -- -- The lambda body returns the output in this 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 lore] -> Lambda lore -> [VName] -> SOAC lore -- | A combination of scan, reduction, and map. The first SubExp is -- the size of the input arrays. Screma :: SubExp -> ScremaForm lore -> [VName] -> SOAC lore -- | 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 lore Parallel :: StreamOrd -> Commutativity -> Lambda lore -> [SubExp] -> StreamForm lore Sequential :: [SubExp] -> StreamForm lore -- | The essential parts of a Screma factored out (everything except -- the input arrays). data ScremaForm lore ScremaForm :: [Scan lore] -> [Reduce lore] -> Lambda lore -> ScremaForm lore -- | Information about computing a single histogram. data HistOp lore HistOp :: SubExp -> SubExp -> [VName] -> [SubExp] -> Lambda lore -> HistOp lore [histWidth] :: HistOp lore -> SubExp -- | Race factor RF means that only 1/RF bins are used. [histRaceFactor] :: HistOp lore -> SubExp [histDest] :: HistOp lore -> [VName] [histNeutral] :: HistOp lore -> [SubExp] [histOp] :: HistOp lore -> Lambda lore -- | How to compute a single scan result. data Scan lore Scan :: Lambda lore -> [SubExp] -> Scan lore [scanLambda] :: Scan lore -> Lambda lore [scanNeutral] :: Scan lore -> [SubExp] -- | How many reduction results are produced by these Scans? scanResults :: [Scan lore] -> Int -- | Combine multiple scan operators to a single operator. singleScan :: Bindable lore => [Scan lore] -> Scan lore -- | How to compute a single reduction result. data Reduce lore Reduce :: Commutativity -> Lambda lore -> [SubExp] -> Reduce lore [redComm] :: Reduce lore -> Commutativity [redLambda] :: Reduce lore -> Lambda lore [redNeutral] :: Reduce lore -> [SubExp] -- | How many reduction results are produced by these Reduces? redResults :: [Reduce lore] -> Int -- | Combine multiple reduction operators to a single operator. singleReduce :: Bindable lore => [Reduce lore] -> Reduce lore -- | Get Stream's accumulators as a sub-expression list getStreamAccums :: StreamForm lore -> [SubExp] -- | The types produced by a single Screma, given the size of the -- input array. scremaType :: SubExp -> ScremaForm lore -> [Type] -- | The type of a SOAC. soacType :: SOAC lore -> [Type] -- | Type-check a SOAC. typeCheckSOAC :: Checkable lore => SOAC (Aliases lore) -> TypeM lore () -- | Construct a lambda that takes parameters of the given types and simply -- returns them unchanged. mkIdentityLambda :: (Bindable lore, MonadFreshNames m) => [Type] -> m (Lambda lore) -- | Is the given lambda an identity lambda? isIdentityLambda :: Lambda lore -> Bool -- | A lambda with no parameters that returns no values. nilFn :: Bindable lore => Lambda lore -- | Construct a Screma with possibly multiple scans, and the given map -- function. scanomapSOAC :: [Scan lore] -> Lambda lore -> ScremaForm lore -- | Construct a Screma with possibly multiple reductions, and the given -- map function. redomapSOAC :: [Reduce lore] -> Lambda lore -> ScremaForm lore -- | Construct a Screma with possibly multiple scans, and identity map -- function. scanSOAC :: (Bindable lore, MonadFreshNames m) => [Scan lore] -> m (ScremaForm lore) -- | Construct a Screma with possibly multiple reductions, and identity map -- function. reduceSOAC :: (Bindable lore, MonadFreshNames m) => [Reduce lore] -> m (ScremaForm lore) -- | Construct a Screma corresponding to a map. mapSOAC :: Lambda lore -> ScremaForm lore -- | Does this Screma correspond to a scan-map composition? isScanomapSOAC :: ScremaForm lore -> Maybe ([Scan lore], Lambda lore) -- | Does this Screma correspond to a reduce-map composition? isRedomapSOAC :: ScremaForm lore -> Maybe ([Reduce lore], Lambda lore) -- | Does this Screma correspond to pure scan? isScanSOAC :: ScremaForm lore -> Maybe [Scan lore] -- | Does this Screma correspond to a pure reduce? isReduceSOAC :: ScremaForm lore -> Maybe [Reduce lore] -- | Does this Screma correspond to a simple map, without any reduction or -- scan results? isMapSOAC :: ScremaForm lore -> Maybe (Lambda lore) -- | Prettyprint the given Screma. ppScrema :: (PrettyLore lore, Pretty inp) => SubExp -> ScremaForm lore -> [inp] -> Doc -- | Prettyprint the given histogram operation. ppHist :: (PrettyLore lore, Pretty inp) => SubExp -> [HistOp lore] -> Lambda lore -> [inp] -> Doc -- | Like Mapper, but just for SOACs. data SOACMapper flore tlore m SOACMapper :: (SubExp -> m SubExp) -> (Lambda flore -> m (Lambda tlore)) -> (VName -> m VName) -> SOACMapper flore tlore m [mapOnSOACSubExp] :: SOACMapper flore tlore m -> SubExp -> m SubExp [mapOnSOACLambda] :: SOACMapper flore tlore m -> Lambda flore -> m (Lambda tlore) [mapOnSOACVName] :: SOACMapper flore tlore m -> VName -> m VName -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper lore lore 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 flore tlore m -> SOAC flore -> m (SOAC tlore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SOACS.SOAC.HistOp lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.HistOp lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.HistOp lore) 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.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SOACS.SOAC.StreamForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.StreamForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.StreamForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SOACS.SOAC.Scan lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.Scan lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.Scan lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SOACS.SOAC.Reduce lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.Reduce lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.Reduce lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SOACS.SOAC.ScremaForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.ScremaForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.ScremaForm lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Prop.ASTLore lore => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Prop.ASTLore lore => Futhark.Transform.Substitute.Substitute (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Prop.ASTLore lore => Futhark.Transform.Rename.Rename (Futhark.IR.SOACS.SOAC.SOAC lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.ASTLore (Futhark.IR.Aliases.Aliases lore), Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Decorations.Op lore)) => Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.SOACS.SOAC.SOAC lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.Decorations.Op lore)) => Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Prop.TypeOf.TypedOp (Futhark.IR.SOACS.SOAC.SOAC lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.Aliases.Aliased lore) => Futhark.IR.Prop.Aliases.AliasedOp (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Prop.ASTLore lore => Futhark.IR.Prop.IsOp (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Decorations.Decorations lore => Futhark.Analysis.SymbolTable.IndexOp (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.Decorations.Op lore) => Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SOACS.SOAC.SOAC lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SOACS.SOAC.Reduce lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SOACS.SOAC.Scan lore) -- | 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. -- -- Only handles a pattern with an empty patternContextElements. redomapToMapAndReduce :: (MonadFreshNames m, Bindable lore, ExpDec lore ~ (), Op lore ~ SOAC lore) => Pattern lore -> (SubExp, Commutativity, LambdaT lore, LambdaT lore, [SubExp], [VName]) -> m (Stm lore, Stm lore) -- | 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 :: (MonadBinder m, Op (Lore m) ~ SOAC (Lore m), Bindable (Lore m)) => Pattern (Lore m) -> SubExp -> ScremaForm (Lore m) -> [VName] -> m () -- | Turn a stream SOAC into statements that apply the stream lambda to the -- entire input. sequentialStreamWholeArray :: (MonadBinder m, Bindable (Lore m)) => Pattern (Lore m) -> SubExp -> [SubExp] -> LambdaT (Lore 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 lore for the basic representation. data SOACS type Body = Body SOACS type Stm = Stm SOACS type Pattern = Pattern 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 -- | 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 -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data 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 Cert :: PrimType -- | A floating point type. data 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 -- | 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 -- | 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 -- | 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 integer value. ErrorInt32 :: 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 -- | A list of DimFixs, 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. type 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 Certificates Certificates :: [VName] -> Certificates [unCertificates] :: Certificates -> [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 -- | A Futhark type is either an array or an element type. When comparing -- types for equality with ==, shapes must match. data TypeBase shape u Prim :: PrimType -> 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] -- | 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 -- | 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 value parameter types, produce the -- types of arguments accepted. expectedTypes :: Typed t => [VName] -> [t] -> [SubExp] -> [Type] -- | A collection of type families, 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)) => Decorations 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 lore Prog :: Stms lore -> [FunDef lore] -> Prog lore -- | Top-level constants that are computed at program startup, and which -- are in scope inside all functions. [progConsts] :: Prog lore -> Stms lore -- | 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 lore -> [FunDef lore] -- | 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 :: EntryPointType -- | A black box type comprising this many core values. The string is a -- human-readable description with no other semantics. TypeOpaque :: String -> Int -> EntryPointType -- | Maps directly. TypeDirect :: 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 = ([EntryPointType], [EntryPointType]) -- | Function Declarations data FunDef lore FunDef :: Maybe EntryPoint -> Attrs -> Name -> [RetType lore] -> [FParam lore] -> BodyT lore -> FunDef lore -- | Contains a value if this function is an entry point. [funDefEntryPoint] :: FunDef lore -> Maybe EntryPoint [funDefAttrs] :: FunDef lore -> Attrs [funDefName] :: FunDef lore -> Name [funDefRetType] :: FunDef lore -> [RetType lore] [funDefParams] :: FunDef lore -> [FParam lore] [funDefBody] :: FunDef lore -> BodyT lore -- | Anonymous function for use in a SOAC. data LambdaT lore -- | 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 lore ForLoop :: VName -> IntType -> SubExp -> [(LParam lore, VName)] -> LoopForm lore WhileLoop :: VName -> LoopForm lore -- | The root Futhark expression type. The Op constructor contains a -- lore-specific operation. Do-loops, branches and function calls are -- special. Everything else is a simple BasicOp. data ExpT lore -- | A simple (non-recursive) operation. BasicOp :: BasicOp -> ExpT lore Apply :: Name -> [(SubExp, Diet)] -> [RetType lore] -> (Safety, SrcLoc, [SrcLoc]) -> ExpT lore If :: SubExp -> BodyT lore -> BodyT lore -> IfDec (BranchType lore) -> ExpT lore -- | loop {a} = {v} (for i < n|while b) do b. The merge -- parameters are divided into context and value part. DoLoop :: [(FParam lore, SubExp)] -> [(FParam lore, SubExp)] -> LoopForm lore -> BodyT lore -> ExpT lore Op :: Op lore -> ExpT lore -- | 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 is just a -- hack to avoid optimisation (so, to work around compiler limitations). Opaque :: SubExp -> BasicOp -- | Array literals, e.g., [ [1+x, 3], [2, 1+4] ]. Second arg is -- the element type of the rows of the array. Scalar operations 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. Update :: VName -> Slice SubExp -> SubExp -> 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 -- | 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 lore -- | The result of a body is a sequence of subexpressions. type Result = [SubExp] -- | A sequence of statements. type Stms lore = Seq (Stm lore) pattern Let :: () => Pattern lore -> StmAux (ExpDec lore) -> Exp lore -> Stm lore -- | Expression. stmExp :: Stm lore -> Exp lore -- | Pattern. stmPattern :: Stm lore -> Pattern lore -- | Auxiliary information statement. stmAux :: Stm lore -> StmAux (ExpDec lore) -- | Auxilliary Information associated with a statement. data StmAux dec StmAux :: !Certificates -> Attrs -> dec -> StmAux dec [stmAuxCerts] :: StmAux dec -> !Certificates [stmAuxAttrs] :: StmAux dec -> Attrs [stmAuxDec] :: StmAux dec -> dec -- | A pattern is conceptually just a list of names and their types. data PatternT 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 lore -> Stms lore -- | Convert a statement list to a statement sequence. stmsFromList :: [Stm lore] -> Stms lore -- | Convert a statement sequence to a statement list. stmsToList :: Stms lore -> [Stm lore] -- | The first statement in the sequence, if any. stmsHead :: Stms lore -> Maybe (Stm lore, Stms lore) -- | Anonymous function for use in a SOAC. data LambdaT lore Lambda :: [LParam lore] -> BodyT lore -> [Type] -> LambdaT lore -- | A body consists of a number of bindings, terminating in a result -- (essentially a tuple literal). data BodyT lore Body :: BodyDec lore -> Stms lore -> Result -> BodyT lore -- | A pattern is conceptually just a list of names and their types. data PatternT dec Pattern :: [PatElemT dec] -> [PatElemT dec] -> PatternT 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.Decorations.Decorations Futhark.IR.SOACS.SOACS instance Futhark.IR.Prop.ASTLore Futhark.IR.SOACS.SOACS instance Futhark.TypeCheck.CheckableOp Futhark.IR.SOACS.SOACS instance Futhark.TypeCheck.Checkable Futhark.IR.SOACS.SOACS instance Futhark.Binder.Class.Bindable Futhark.IR.SOACS.SOACS instance Futhark.Binder.BinderOps Futhark.IR.SOACS.SOACS instance Futhark.IR.Pretty.PrettyLore 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, FirstOrderLore tolore) => Scope tolore -> FunDef SOACS -> m (FunDef tolore) -- | First-order-transform these top-level constants. transformConsts :: (MonadFreshNames m, FirstOrderLore tolore) => Stms SOACS -> m (Stms tolore) -- | The constraints that must hold for a lore in order to be the target of -- first-order transformation. type FirstOrderLore lore = (Bindable lore, BinderOps lore, LetDec SOACS ~ LetDec lore, LParamInfo SOACS ~ LParamInfo lore) -- | The constraints that a monad must uphold in order to be used for -- first-order transformation. type Transformer m = (MonadBinder m, LocalScope (Lore m) m, Bindable (Lore m), BinderOps (Lore m), LParamInfo SOACS ~ LParamInfo (Lore m)) -- | First transform any nested Body or Lambda elements, then -- apply transformSOAC if the expression is a SOAC. transformStmRecursively :: (Transformer m, LetDec (Lore m) ~ LetDec SOACS) => Stm -> m () -- | Recursively first-order-transform a lambda. transformLambda :: (MonadFreshNames m, Bindable lore, BinderOps lore, LocalScope somelore m, SameScope somelore lore, LetDec lore ~ LetDec SOACS) => Lambda -> m (Lambda lore) -- | 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 lore. transformSOAC :: Transformer m => Pattern (Lore m) -> SOAC (Lore 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 :: FirstOrderLore lore => Pass SOACS lore -- | 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 :: (MonadBinder m, Lore m ~ SOACS) => Pattern -> SubExp -> Lambda -> [(SubExp, VName)] -> Maybe (m ()) -- | Interchange Reduce With Inner Map. Tries to turn a -- reduce(map) into a @map(reduce) irwim :: (MonadBinder m, Lore m ~ SOACS) => Pattern -> 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 (Pattern, Certificates, 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 VarSubstitutions = Map VName [SubExp] data InternaliseEnv InternaliseEnv :: VarSubstitutions -> Bool -> Bool -> Attrs -> InternaliseEnv [envSubsts] :: InternaliseEnv -> VarSubstitutions [envDoBoundsChecks] :: InternaliseEnv -> Bool [envSafe] :: InternaliseEnv -> Bool [envAttrs] :: InternaliseEnv -> Attrs -- | Extra parameters to pass when calling this function. This corresponds -- to the closure of a locally defined function. type Closure = [VName] type FunInfo = (Name, Closure, [VName], [DeclType], [FParam], [(SubExp, Type)] -> Maybe [DeclExtType]) substitutingVars :: VarSubstitutions -> 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]) allConsts :: InternaliseM Names 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 Certificates data InternaliseTypeM a liftInternaliseM :: InternaliseM a -> InternaliseTypeM a runInternaliseTypeM :: InternaliseTypeM a -> InternaliseM a lookupDim :: VName -> InternaliseTypeM (Maybe ExtSize) withDims :: DimTable -> InternaliseTypeM a -> InternaliseTypeM a type DimTable = Map VName ExtSize 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 Control.Monad.State.Class.MonadState Futhark.Internalise.Monad.TypeState Futhark.Internalise.Monad.InternaliseTypeM instance Control.Monad.Reader.Class.MonadReader Futhark.Internalise.Monad.TypeEnv Futhark.Internalise.Monad.InternaliseTypeM instance GHC.Base.Monad Futhark.Internalise.Monad.InternaliseTypeM instance GHC.Base.Applicative Futhark.Internalise.Monad.InternaliseTypeM instance GHC.Base.Functor Futhark.Internalise.Monad.InternaliseTypeM instance Futhark.Binder.Class.MonadBinder Futhark.Internalise.Monad.InternaliseM instance GHC.Base.Semigroup Futhark.Internalise.Monad.InternaliseResult instance GHC.Base.Monoid Futhark.Internalise.Monad.InternaliseResult instance (GHC.Base.Monoid w, GHC.Base.Monad m) => Futhark.MonadFreshNames.MonadFreshNames (Control.Monad.Trans.RWS.Lazy.RWST r w Futhark.Internalise.Monad.InternaliseState m) module Futhark.Internalise.AccurateSizes argShapes :: [VName] -> [TypeBase Shape u0] -> [TypeBase Shape u1] -> [SubExp] ensureResultShape :: ErrorMsg SubExp -> SrcLoc -> [Type] -> Body -> InternaliseM Body ensureResultExtShape :: ErrorMsg SubExp -> SrcLoc -> [ExtType] -> Body -> InternaliseM Body 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 :: SimplifiableLore lore => SimplifyOp lore (SOAC lore) soacRules :: RuleBook (Wise SOACS) -- | Does this lore contain SOACs in its Ops? A lore must be -- an instance of this class for the simplification rules to work. class HasSOAC lore asSOAC :: HasSOAC lore => Op lore -> Maybe (SOAC lore) soacOp :: HasSOAC lore => SOAC lore -> Op lore simplifyKnownIterationSOAC :: (Bindable lore, SimplifiableLore lore, HasSOAC (Wise lore)) => TopDownRuleOp (Wise lore) -- | Remove all arguments to the map that are simply replicates. These can -- be turned into free variables instead. removeReplicateMapping :: (Bindable lore, SimplifiableLore lore, HasSOAC (Wise lore)) => TopDownRuleOp (Wise lore) liftIdentityMapping :: forall lore. (Bindable lore, SimplifiableLore lore, HasSOAC (Wise lore)) => BottomUpRuleOp (Wise lore) -- | The lore 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.Lore.Wise Futhark.IR.SOACS.SOACS) instance Futhark.Binder.BinderOps (Futhark.Optimise.Simplify.Lore.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 set 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 -- | The set of all functions that are called noinline somewhere, or have a -- noinline attribute on their definition. findNoninlined :: Prog SOACS -> Set Name -- | 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. This really should not be an expression, but -- what are you gonna do... 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 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 (PrimExp VName) -- | An index function that may contain existential variables. type ExtIxFun = IxFun (PrimExp (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 lore = (AllocOp (Op lore), FParamInfo lore ~ FParamMem, LParamInfo lore ~ LParamMem, LetDec lore ~ LetDecMem, RetType lore ~ RetTypeMem, BranchType lore ~ BranchTypeMem, CanBeAliased (Op lore), ASTLore lore, Decorations lore, Checkable lore, OpReturns lore) -- | The class of ops that have memory allocation. class AllocOp op allocOp :: AllocOp op => SubExp -> Space -> op class TypedOp (Op lore) => OpReturns lore opReturns :: (OpReturns lore, Monad m, HasScope lore m) => Op lore -> m [ExpReturns] varReturns :: (HasScope lore m, Monad m, Mem lore) => 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, HasScope lore m, Mem lore) => Exp lore -> m [ExpReturns] extReturns :: [ExtType] -> [ExpReturns] lookupMemInfo :: (HasScope lore m, Mem lore) => VName -> m (MemInfo SubExp NoUniqueness MemBind) subExpMemInfo :: (HasScope lore m, Monad m, Mem lore) => SubExp -> m (MemInfo SubExp NoUniqueness MemBind) lookupArraySummary :: (Mem lore, HasScope lore m, Monad m) => VName -> m (VName, IxFun (PrimExp VName)) existentialiseIxFun :: [VName] -> IxFun -> ExtIxFun matchBranchReturnType :: Mem lore => [BodyReturns] -> Body (Aliases lore) -> TypeM lore () matchPatternToExp :: Mem lore => Pattern (Aliases lore) -> Exp (Aliases lore) -> TypeM lore () matchFunctionReturnType :: Mem lore => [FunReturns] -> Result -> TypeM lore () matchLoopResultMem :: Mem lore => [FParam (Aliases lore)] -> [FParam (Aliases lore)] -> [SubExp] -> TypeM lore () bodyReturnsFromPattern :: PatternT (MemBound NoUniqueness) -> ([(VName, BodyReturns)], [(VName, BodyReturns)]) checkMemInfo :: Checkable lore => VName -> MemInfo SubExp u MemBind -> TypeM lore () 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.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 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.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 Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Param (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.SubExp Language.Futhark.Core.Uniqueness ret)) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.Param (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.SubExp Futhark.IR.Syntax.Core.NoUniqueness ret)) instance Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.Syntax.Core.PatElemT (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.SubExp Futhark.IR.Syntax.Core.NoUniqueness ret)) instance (Text.PrettyPrint.Mainland.Class.Pretty u, Text.PrettyPrint.Mainland.Class.Pretty r) => Futhark.IR.Pretty.PrettyAnnot (Futhark.IR.Syntax.Core.PatElemT (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.SubExp u r)) instance (Text.PrettyPrint.Mainland.Class.Pretty u, Text.PrettyPrint.Mainland.Class.Pretty r) => Futhark.IR.Pretty.PrettyAnnot (Futhark.IR.Syntax.Core.Param (Futhark.IR.Mem.MemInfo Futhark.IR.Syntax.Core.SubExp u r)) instance Futhark.IR.Mem.AllocOp (Futhark.IR.Mem.MemOp inner) 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.Lore.CanBeWise inner => Futhark.Optimise.Simplify.Lore.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 fromlore tolore, Allocator tolore (AllocM fromlore tolore)) => (Op fromlore -> AllocM fromlore tolore (Op tolore)) -> (Exp tolore -> AllocM fromlore tolore [ExpHint]) -> Pass fromlore tolore explicitAllocationsInStmsGeneric :: (MonadFreshNames m, HasScope tolore m, Allocable fromlore tolore) => (Op fromlore -> AllocM fromlore tolore (Op tolore)) -> (Exp tolore -> AllocM fromlore tolore [ExpHint]) -> Stms fromlore -> m (Stms tolore) data ExpHint NoHint :: ExpHint Hint :: IxFun -> Space -> ExpHint defaultExpHints :: (Monad m, ASTLore lore) => Exp lore -> m [ExpHint] type Allocable fromlore tolore = (PrettyLore fromlore, PrettyLore tolore, Mem tolore, FParamInfo fromlore ~ DeclType, LParamInfo fromlore ~ Type, BranchType fromlore ~ ExtType, RetType fromlore ~ DeclExtType, BodyDec fromlore ~ (), BodyDec tolore ~ (), ExpDec tolore ~ (), SizeSubst (Op tolore), BinderOps tolore) class (MonadFreshNames m, HasScope lore m, Mem lore) => Allocator lore m addAllocStm :: Allocator lore m => AllocStm -> m () askDefaultSpace :: Allocator lore m => m Space addAllocStm :: (Allocator lore m, Allocable fromlore lore, m ~ AllocM fromlore lore) => AllocStm -> m () -- | The subexpression giving the number of elements we should allocate -- space for. See ChunkMap comment. dimAllocationSize :: Allocator lore m => SubExp -> m SubExp -- | The subexpression giving the number of elements we should allocate -- space for. See ChunkMap comment. dimAllocationSize :: (Allocator lore m, m ~ AllocM fromlore lore) => SubExp -> m SubExp -- | Get those names that are known to be constants at run-time. askConsts :: Allocator lore m => m (Set VName) expHints :: Allocator lore m => Exp lore -> m [ExpHint] -- | Monad for adding allocations to an entire program. data AllocM fromlore tolore a data AllocEnv fromlore tolore AllocEnv :: ChunkMap -> Bool -> Space -> Set VName -> (Op fromlore -> AllocM fromlore tolore (Op tolore)) -> (Exp tolore -> AllocM fromlore tolore [ExpHint]) -> AllocEnv fromlore tolore [chunkMap] :: AllocEnv fromlore tolore -> ChunkMap -- | Aggressively try to reuse memory in do-loops - should be True inside -- kernels, False outside. [aggressiveReuse] :: AllocEnv fromlore tolore -> 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 fromlore tolore -> Space -- | The set of names that are known to be constants at kernel compile -- time. [envConsts] :: AllocEnv fromlore tolore -> Set VName [allocInOp] :: AllocEnv fromlore tolore -> Op fromlore -> AllocM fromlore tolore (Op tolore) [envExpHints] :: AllocEnv fromlore tolore -> Exp tolore -> AllocM fromlore tolore [ExpHint] class SizeSubst op opSizeSubst :: SizeSubst op => PatternT dec -> op -> ChunkMap opIsConst :: SizeSubst op => op -> Bool allocInStms :: Allocable fromlore tolore => Stms fromlore -> (Stms tolore -> AllocM fromlore tolore a) -> AllocM fromlore tolore a -- | Allocate memory for a value of the given type. allocForArray :: Allocator lore m => Type -> Space -> m VName simplifiable :: (SimplifiableLore lore, ExpDec lore ~ (), BodyDec lore ~ (), Op lore ~ MemOp inner, Allocator lore (PatAllocM lore)) => (OpWithWisdom inner -> UsageTable) -> (inner -> SimpleM lore (OpWithWisdom inner, Stms (Wise lore))) -> SimpleOps lore arraySizeInBytesExp :: Type -> PrimExp VName mkLetNamesB' :: (Op (Lore m) ~ MemOp inner, MonadBinder m, ExpDec (Lore m) ~ (), Allocator (Lore m) (PatAllocM (Lore m))) => ExpDec (Lore m) -> [VName] -> Exp (Lore m) -> m (Stm (Lore m)) mkLetNamesB'' :: (Op (Lore m) ~ MemOp inner, ExpDec lore ~ (), HasScope (Wise lore) m, Allocator lore (PatAllocM lore), MonadBinder m, CanBeWise (Op lore)) => [VName] -> Exp (Wise lore) -> m (Stm (Wise lore)) instance GHC.Show.Show Futhark.Pass.ExplicitAllocations.AllocStm instance GHC.Classes.Ord Futhark.Pass.ExplicitAllocations.AllocStm instance GHC.Classes.Eq Futhark.Pass.ExplicitAllocations.AllocStm instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance Control.Monad.Writer.Class.MonadWriter [Futhark.Pass.ExplicitAllocations.AllocStm] (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance Futhark.IR.Decorations.Decorations lore => Futhark.IR.Prop.Scope.HasScope lore (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance GHC.Base.Monad (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance GHC.Base.Functor (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance GHC.Base.Applicative (Futhark.Pass.ExplicitAllocations.PatAllocM lore) instance Control.Monad.Reader.Class.MonadReader (Futhark.Pass.ExplicitAllocations.AllocEnv fromlore tolore) (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.IR.Prop.ASTLore tolore => Futhark.IR.Prop.Scope.LocalScope tolore (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.IR.Prop.ASTLore tolore => Futhark.IR.Prop.Scope.HasScope tolore (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance GHC.Base.Monad (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance GHC.Base.Functor (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance GHC.Base.Applicative (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance (Futhark.Pass.ExplicitAllocations.Allocable fromlore tolore, Futhark.Pass.ExplicitAllocations.Allocator tolore (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore)) => Futhark.Binder.Class.MonadBinder (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.Pass.ExplicitAllocations.Allocable fromlore tolore => Futhark.Pass.ExplicitAllocations.Allocator tolore (Futhark.Pass.ExplicitAllocations.AllocM fromlore tolore) instance Futhark.IR.Mem.Mem lore => Futhark.Pass.ExplicitAllocations.Allocator lore (Futhark.Pass.ExplicitAllocations.PatAllocM lore) 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 lore SegMap :: lvl -> SegSpace -> [Type] -> KernelBody lore -> SegOp lvl lore -- | The KernelSpace must always have at least two dimensions, implying -- that the result of a SegRed is always an array. SegRed :: lvl -> SegSpace -> [SegBinOp lore] -> [Type] -> KernelBody lore -> SegOp lvl lore SegScan :: lvl -> SegSpace -> [SegBinOp lore] -> [Type] -> KernelBody lore -> SegOp lvl lore SegHist :: lvl -> SegSpace -> [HistOp lore] -> [Type] -> KernelBody lore -> SegOp lvl lore -- | 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 lore -> lvl -- | The space of a SegOp. segSpace :: SegOp lvl lore -> SegSpace -- | Type check a SegOp, given a checker for its level. typeCheckSegOp :: Checkable lore => (lvl -> TypeM lore ()) -> SegOp lvl (Aliases lore) -> TypeM lore () -- | 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 lore -- | The sizes spanned by the indexes of the SegSpace. segSpaceDims :: SegSpace -> [SubExp] -- | An operator for SegHist. data HistOp lore HistOp :: SubExp -> SubExp -> [VName] -> [SubExp] -> Shape -> Lambda lore -> HistOp lore [histWidth] :: HistOp lore -> SubExp [histRaceFactor] :: HistOp lore -> SubExp [histDest] :: HistOp lore -> [VName] [histNeutral] :: HistOp lore -> [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 lore -> Shape [histOp] :: HistOp lore -> Lambda lore -- | 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 lore -> [Type] -- | An operator for SegScan and SegRed. data SegBinOp lore SegBinOp :: Commutativity -> Lambda lore -> [SubExp] -> Shape -> SegBinOp lore [segBinOpComm] :: SegBinOp lore -> Commutativity [segBinOpLambda] :: SegBinOp lore -> Lambda lore [segBinOpNeutral] :: SegBinOp lore -> [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 lore -> Shape -- | How many reduction results are produced by these SegBinOps? segBinOpResults :: [SegBinOp lore] -> Int -- | Split some list into chunks equal to the number of values returned by -- each SegBinOp segBinOpChunks :: [SegBinOp lore] -> [a] -> [[a]] -- | The body of a SegOp. data KernelBody lore KernelBody :: BodyDec lore -> Stms lore -> [KernelResult] -> KernelBody lore [kernelBodyLore] :: KernelBody lore -> BodyDec lore [kernelBodyStms] :: KernelBody lore -> Stms lore [kernelBodyResult] :: KernelBody lore -> [KernelResult] -- | Perform alias analysis on a KernelBody. aliasAnalyseKernelBody :: (ASTLore lore, CanBeAliased (Op lore)) => KernelBody lore -> KernelBody (Aliases lore) -- | The variables consumed in the kernel body. consumedInKernelBody :: Aliased lore => KernelBody lore -> 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 -> SubExp -> KernelResult WriteReturns :: [SubExp] -> VName -> [(Slice SubExp, SubExp)] -> KernelResult ConcatReturns :: SplitOrdering -> SubExp -> SubExp -> VName -> KernelResult TileReturns :: [(SubExp, SubExp)] -> VName -> KernelResult -- | 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 flore tlore m SegOpMapper :: (SubExp -> m SubExp) -> (Lambda flore -> m (Lambda tlore)) -> (KernelBody flore -> m (KernelBody tlore)) -> (VName -> m VName) -> (lvl -> m lvl) -> SegOpMapper lvl flore tlore m [mapOnSegOpSubExp] :: SegOpMapper lvl flore tlore m -> SubExp -> m SubExp [mapOnSegOpLambda] :: SegOpMapper lvl flore tlore m -> Lambda flore -> m (Lambda tlore) [mapOnSegOpBody] :: SegOpMapper lvl flore tlore m -> KernelBody flore -> m (KernelBody tlore) [mapOnSegOpVName] :: SegOpMapper lvl flore tlore m -> VName -> m VName [mapOnSegOpLevel] :: SegOpMapper lvl flore tlore m -> lvl -> m lvl -- | A mapper that simply returns the SegOp verbatim. identitySegOpMapper :: Monad m => SegOpMapper lvl lore lore m -- | Apply a SegOpMapper to the given SegOp. mapSegOpM :: (Applicative m, Monad m) => SegOpMapper lvl flore tlore m -> SegOp lvl flore -> m (SegOp lvl tlore) -- | Simplify the given SegOp. simplifySegOp :: (SimplifiableLore lore, BodyDec lore ~ (), Simplifiable lvl) => SegOp lvl lore -> SimpleM lore (SegOp lvl (Wise lore), Stms (Wise lore)) -- | Does this lore contain SegOps in its Ops? A lore must be -- an instance of this class for the simplification rules to work. class HasSegOp lore where { type family SegOpLevel lore; } asSegOp :: HasSegOp lore => Op lore -> Maybe (SegOp (SegOpLevel lore) lore) segOp :: HasSegOp lore => SegOp (SegOpLevel lore) lore -> Op lore -- | Simplification rules for simplifying SegOps. segOpRules :: (HasSegOp lore, BinderOps lore, Bindable lore) => RuleBook lore -- | Like segOpType, but for memory representations. segOpReturns :: (Mem lore, Monad m, HasScope lore m) => SegOp lvl lore -> 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.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SegOp.HistOp lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SegOp.HistOp lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SegOp.HistOp lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SegOp.SegBinOp lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SegOp.SegBinOp lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SegOp.SegBinOp lore) 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.Decorations.Decorations lore, GHC.Show.Show lvl) => GHC.Show.Show (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.IR.Decorations.Decorations lore, GHC.Classes.Ord lvl) => GHC.Classes.Ord (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.IR.Decorations.Decorations lore, GHC.Classes.Eq lvl) => GHC.Classes.Eq (Futhark.IR.SegOp.SegOp lvl lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Ord (Futhark.IR.SegOp.KernelBody lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.IR.SegOp.KernelBody lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.IR.SegOp.KernelBody lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.Transform.Substitute.Substitute lvl) => Futhark.Transform.Substitute.Substitute (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.ASTConstraints lvl) => Futhark.Transform.Rename.Rename (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.Names.FreeIn (Futhark.IR.Decorations.LParamInfo lore), Futhark.IR.Prop.Names.FreeIn lvl) => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.ASTLore (Futhark.IR.Aliases.Aliases lore), Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Decorations.Op lore), Futhark.IR.Prop.ASTConstraints lvl) => Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.Decorations.Op lore), Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.ASTConstraints lvl) => Futhark.Optimise.Simplify.Lore.CanBeWise (Futhark.IR.SegOp.SegOp lvl lore) instance Futhark.IR.Prop.TypeOf.TypedOp (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.Aliases.Aliased lore, Futhark.IR.Prop.ASTConstraints lvl) => Futhark.IR.Prop.Aliases.AliasedOp (Futhark.IR.SegOp.SegOp lvl lore) instance Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.Decorations.Op lore) => Futhark.Analysis.Metrics.OpMetrics (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.IR.Pretty.PrettyLore lore, Text.PrettyPrint.Mainland.Class.Pretty lvl) => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SegOp.SegOp lvl lore) instance Futhark.IR.Prop.ASTLore lore => Futhark.Analysis.SymbolTable.IndexOp (Futhark.IR.SegOp.SegOp lvl lore) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.ASTConstraints lvl) => Futhark.IR.Prop.IsOp (Futhark.IR.SegOp.SegOp lvl lore) instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.IR.SegOp.SegSpace instance Futhark.Optimise.Simplify.Engine.Simplifiable Futhark.IR.SegOp.SegSpace instance Futhark.IR.Prop.ASTLore lore => Futhark.IR.Prop.Names.FreeIn (Futhark.IR.SegOp.KernelBody lore) instance Futhark.IR.Prop.ASTLore lore => Futhark.Transform.Substitute.Substitute (Futhark.IR.SegOp.KernelBody lore) instance Futhark.IR.Prop.ASTLore lore => Futhark.Transform.Rename.Rename (Futhark.IR.SegOp.KernelBody lore) instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SegOp.KernelBody lore) 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.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.IR.SegOp.SegBinOp lore) 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 DistLore lore = (Bindable lore, HasSegOp lore, BinderOps lore, LetDec lore ~ Type, ExpDec lore ~ (), BodyDec lore ~ ()) type MkSegLevel lore m = [SubExp] -> String -> ThreadRecommendation -> BinderT lore m (SegOpLevel lore) data ThreadRecommendation ManyThreads :: ThreadRecommendation NoRecommendation :: SegVirt -> ThreadRecommendation segRed :: (MonadFreshNames m, DistLore lore, HasScope lore m) => SegOpLevel lore -> Pattern lore -> SubExp -> [SegBinOp lore] -> Lambda lore -> [VName] -> [(VName, SubExp)] -> [KernelInput] -> m (Stms lore) nonSegRed :: (MonadFreshNames m, DistLore lore, HasScope lore m) => SegOpLevel lore -> Pattern lore -> SubExp -> [SegBinOp lore] -> Lambda lore -> [VName] -> m (Stms lore) segScan :: (MonadFreshNames m, DistLore lore, HasScope lore m) => SegOpLevel lore -> Pattern lore -> SubExp -> [SegBinOp lore] -> Lambda lore -> [VName] -> [(VName, SubExp)] -> [KernelInput] -> m (Stms lore) segHist :: (DistLore lore, MonadFreshNames m, HasScope lore m) => SegOpLevel lore -> Pattern lore -> SubExp -> [(VName, SubExp)] -> [KernelInput] -> [HistOp lore] -> Lambda lore -> [VName] -> m (Stms lore) segMap :: (MonadFreshNames m, DistLore lore, HasScope lore m) => SegOpLevel lore -> Pattern lore -> SubExp -> Lambda lore -> [VName] -> [(VName, SubExp)] -> [KernelInput] -> m (Stms lore) mapKernel :: (DistLore lore, HasScope lore m, MonadFreshNames m) => MkSegLevel lore m -> [(VName, SubExp)] -> [KernelInput] -> [Type] -> KernelBody lore -> m (SegOp (SegOpLevel lore) lore, Stms lore) data KernelInput KernelInput :: VName -> Type -> VName -> [SubExp] -> KernelInput [kernelInputName] :: KernelInput -> VName [kernelInputType] :: KernelInput -> Type [kernelInputArray] :: KernelInput -> VName [kernelInputIndices] :: KernelInput -> [SubExp] readKernelInput :: (DistLore (Lore m), MonadBinder m) => KernelInput -> m () mkSegSpace :: MonadFreshNames m => [(VName, SubExp)] -> m SegSpace dummyDim :: (MonadFreshNames m, MonadBinder m, DistLore (Lore m)) => Pattern (Lore m) -> m (Pattern (Lore m), [(VName, SubExp)], m ()) instance GHC.Show.Show Futhark.Pass.ExtractKernels.BlockedKernel.KernelInput module Futhark.Pass.ExtractKernels.Distribution type Target = (PatternT 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 :: DistLore lore => Targets -> Scope lore data LoopNesting MapNesting :: PatternT Type -> StmAux () -> SubExp -> [(Param Type, VName)] -> LoopNesting [loopNestingPattern] :: LoopNesting -> PatternT Type [loopNestingAux] :: LoopNesting -> StmAux () [loopNestingWidth] :: LoopNesting -> SubExp [loopNestingParamsAndArrs] :: LoopNesting -> [(Param Type, VName)] ppLoopNesting :: LoopNesting -> String scopeOfLoopNesting :: DistLore lore => LoopNesting -> Scope lore 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: -- --
-- 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. performCSE :: (ASTLore lore, CanBeAliased (Op lore), CSEInOp (OpWithAliases (Op lore))) => Bool -> Pass lore lore -- | Perform CSE on a single function. performCSEOnFunDef :: (ASTLore lore, CanBeAliased (Op lore), CSEInOp (OpWithAliases (Op lore))) => Bool -> FunDef lore -> FunDef lore -- | Perform CSE on some statements. performCSEOnStms :: (ASTLore lore, CanBeAliased (Op lore), CSEInOp (OpWithAliases (Op lore))) => Bool -> Stms lore -> Stms lore -- | The operations that permit CSE. class CSEInOp op instance Futhark.Optimise.CSE.CSEInOp () instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.Aliases.Aliased lore, Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Decorations.Op lore), Futhark.Optimise.CSE.CSEInOp op) => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Kernels.Kernel.HostOp lore op) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.Aliases.Aliased lore, Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Decorations.Op lore)) => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.SegOp.SegOp lvl lore) instance Futhark.Optimise.CSE.CSEInOp op => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Mem.MemOp op) instance (Futhark.IR.Prop.ASTLore lore, Futhark.IR.Prop.Aliases.CanBeAliased (Futhark.IR.Decorations.Op lore), Futhark.Optimise.CSE.CSEInOp (Futhark.IR.Prop.Aliases.OpWithAliases (Futhark.IR.Decorations.Op lore))) => Futhark.Optimise.CSE.CSEInOp (Futhark.IR.SOACS.SOAC.SOAC (Futhark.IR.Aliases.Aliases lore)) -- | 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. inlineFunctions :: Pass SOACS SOACS -- | removeDeadFunctions prog removes the functions that are -- unreachable from the main function from the program. removeDeadFunctions :: Pass SOACS SOACS module Futhark.IR.SeqMem data SeqMem simplifyProg :: Prog SeqMem -> PassM (Prog SeqMem) simpleSeqMem :: SimpleOps SeqMem instance Futhark.IR.Decorations.Decorations Futhark.IR.SeqMem.SeqMem instance Futhark.IR.Prop.ASTLore Futhark.IR.SeqMem.SeqMem instance Futhark.IR.Mem.OpReturns Futhark.IR.SeqMem.SeqMem instance Futhark.IR.Pretty.PrettyLore Futhark.IR.SeqMem.SeqMem instance Futhark.TypeCheck.CheckableOp Futhark.IR.SeqMem.SeqMem instance Futhark.TypeCheck.Checkable Futhark.IR.SeqMem.SeqMem instance Futhark.Binder.BinderOps Futhark.IR.SeqMem.SeqMem instance Futhark.Binder.BinderOps (Futhark.Optimise.Simplify.Lore.Wise Futhark.IR.SeqMem.SeqMem) module Futhark.Pass.ExplicitAllocations.Seq explicitAllocations :: Pass Seq SeqMem simplifiable :: (SimplifiableLore lore, ExpDec lore ~ (), BodyDec lore ~ (), Op lore ~ MemOp inner, Allocator lore (PatAllocM lore)) => (OpWithWisdom inner -> UsageTable) -> (inner -> SimpleM lore (OpWithWisdom inner, Stms (Wise lore))) -> SimpleOps lore -- | A representation with flat parallelism via GPU-oriented kernels. module Futhark.IR.Kernels -- | The phantom data type for the kernels representation. data Kernels -- | Like Mapper, but just for SOACs. data SOACMapper flore tlore m SOACMapper :: (SubExp -> m SubExp) -> (Lambda flore -> m (Lambda tlore)) -> (VName -> m VName) -> SOACMapper flore tlore m [mapOnSOACSubExp] :: SOACMapper flore tlore m -> SubExp -> m SubExp [mapOnSOACLambda] :: SOACMapper flore tlore m -> Lambda flore -> m (Lambda tlore) [mapOnSOACVName] :: SOACMapper flore tlore m -> VName -> m VName -- | How to compute a single reduction result. data Reduce lore Reduce :: Commutativity -> Lambda lore -> [SubExp] -> Reduce lore [redComm] :: Reduce lore -> Commutativity [redLambda] :: Reduce lore -> Lambda lore [redNeutral] :: Reduce lore -> [SubExp] -- | How to compute a single scan result. data Scan lore Scan :: Lambda lore -> [SubExp] -> Scan lore [scanLambda] :: Scan lore -> Lambda lore [scanNeutral] :: Scan lore -> [SubExp] -- | The essential parts of a Screma factored out (everything except -- the input arrays). data ScremaForm lore ScremaForm :: [Scan lore] -> [Reduce lore] -> Lambda lore -> ScremaForm lore -- | What kind of stream is this? data StreamForm lore Parallel :: StreamOrd -> Commutativity -> Lambda lore -> [SubExp] -> StreamForm lore Sequential :: [SubExp] -> StreamForm lore -- | 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 lore Stream :: SubExp -> StreamForm lore -> Lambda lore -> [VName] -> SOAC lore -- |
-- Scatter cs length lambda index and value arrays ---- -- <input/output arrays along with their sizes and number of values to -- write for that array> -- -- length is the length of each index array and value array, since -- they all must be the same length for any fusion to make sense. If you -- have a list of index-value array pairs of different sizes, you need to -- use multiple writes instead. -- -- The lambda body returns the output in this 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 lore] -> Lambda lore -> [VName] -> SOAC lore -- | A combination of scan, reduction, and map. The first SubExp is -- the size of the input arrays. Screma :: SubExp -> ScremaForm lore -> [VName] -> SOAC lore -- | How many reduction results are produced by these Scans? scanResults :: [Scan lore] -> Int -- | Combine multiple scan operators to a single operator. singleScan :: Bindable lore => [Scan lore] -> Scan lore -- | How many reduction results are produced by these Reduces? redResults :: [Reduce lore] -> Int -- | Combine multiple reduction operators to a single operator. singleReduce :: Bindable lore => [Reduce lore] -> Reduce lore -- | The types produced by a single Screma, given the size of the -- input array. scremaType :: SubExp -> ScremaForm lore -> [Type] -- | Construct a lambda that takes parameters of the given types and simply -- returns them unchanged. mkIdentityLambda :: (Bindable lore, MonadFreshNames m) => [Type] -> m (Lambda lore) -- | Is the given lambda an identity lambda? isIdentityLambda :: Lambda lore -> Bool -- | A lambda with no parameters that returns no values. nilFn :: Bindable lore => Lambda lore -- | Construct a Screma with possibly multiple scans, and the given map -- function. scanomapSOAC :: [Scan lore] -> Lambda lore -> ScremaForm lore -- | Construct a Screma with possibly multiple reductions, and the given -- map function. redomapSOAC :: [Reduce lore] -> Lambda lore -> ScremaForm lore -- | Construct a Screma with possibly multiple scans, and identity map -- function. scanSOAC :: (Bindable lore, MonadFreshNames m) => [Scan lore] -> m (ScremaForm lore) -- | Construct a Screma with possibly multiple reductions, and identity map -- function. reduceSOAC :: (Bindable lore, MonadFreshNames m) => [Reduce lore] -> m (ScremaForm lore) -- | Construct a Screma corresponding to a map. mapSOAC :: Lambda lore -> ScremaForm lore -- | Does this Screma correspond to a scan-map composition? isScanomapSOAC :: ScremaForm lore -> Maybe ([Scan lore], Lambda lore) -- | Does this Screma correspond to pure scan? isScanSOAC :: ScremaForm lore -> Maybe [Scan lore] -- | Does this Screma correspond to a reduce-map composition? isRedomapSOAC :: ScremaForm lore -> Maybe ([Reduce lore], Lambda lore) -- | Does this Screma correspond to a pure reduce? isReduceSOAC :: ScremaForm lore -> Maybe [Reduce lore] -- | Does this Screma correspond to a simple map, without any reduction or -- scan results? isMapSOAC :: ScremaForm lore -> Maybe (Lambda lore) -- | A mapper that simply returns the SOAC verbatim. identitySOACMapper :: Monad m => SOACMapper lore lore 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 flore tlore m -> SOAC flore -> m (SOAC tlore) -- | The type of a SOAC. soacType :: SOAC lore -> [Type] -- | Type-check a SOAC. typeCheckSOAC :: Checkable lore => SOAC (Aliases lore) -> TypeM lore () -- | Get Stream's accumulators as a sub-expression list getStreamAccums :: StreamForm lore -> [SubExp] -- | Prettyprint the given Screma. ppScrema :: (PrettyLore lore, Pretty inp) => SubExp -> ScremaForm lore -> [inp] -> Doc -- | Prettyprint the given histogram operation. ppHist :: (PrettyLore lore, Pretty inp) => SubExp -> [HistOp lore] -> Lambda lore -> [inp] -> Doc instance Futhark.IR.Decorations.Decorations Futhark.IR.Kernels.Kernels instance Futhark.IR.Prop.ASTLore Futhark.IR.Kernels.Kernels instance Futhark.TypeCheck.CheckableOp Futhark.IR.Kernels.Kernels instance Futhark.TypeCheck.Checkable Futhark.IR.Kernels.Kernels instance Futhark.Binder.Class.Bindable Futhark.IR.Kernels.Kernels instance Futhark.Binder.BinderOps Futhark.IR.Kernels.Kernels instance Futhark.IR.Pretty.PrettyLore Futhark.IR.Kernels.Kernels instance Futhark.IR.SegOp.HasSegOp Futhark.IR.Kernels.Kernels -- | Do various kernel optimisations - mostly related to coalescing. module Futhark.Pass.KernelBabysitting -- | The pass definition. babysitKernels :: Pass Kernels Kernels module Futhark.Pass.ExtractKernels.ToKernels getSize :: (MonadBinder m, Op (Lore m) ~ HostOp (Lore m) inner) => String -> SizeClass -> m SubExp segThread :: (MonadBinder m, Op (Lore m) ~ HostOp (Lore m) inner) => String -> m SegLevel soacsLambdaToKernels :: Lambda SOACS -> Lambda Kernels soacsStmToKernels :: Stm SOACS -> Stm Kernels scopeForKernels :: Scope SOACS -> Scope Kernels scopeForSOACs :: Scope Kernels -> Scope SOACS 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 Kernels m streamRed :: (MonadFreshNames m, HasScope Kernels m) => MkSegLevel Kernels m -> Pattern Kernels -> SubExp -> Commutativity -> Lambda Kernels -> Lambda Kernels -> [SubExp] -> [VName] -> m (Stms Kernels) streamMap :: (MonadFreshNames m, HasScope Kernels m) => MkSegLevel Kernels m -> [String] -> [PatElem Kernels] -> SubExp -> Commutativity -> Lambda Kernels -> [SubExp] -> [VName] -> m ((SubExp, [VName]), Stms Kernels) 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 Kernels m) => KernelNest -> Lambda -> m (Maybe ((SubExp, SubExp), SubExp, Log, Stms Kernels, Stms Kernels)) instance Futhark.Util.Log.MonadLogger Futhark.Pass.ExtractKernels.Intragroup.IntraGroupM instance GHC.Base.Semigroup Futhark.Pass.ExtractKernels.Intragroup.Acc instance GHC.Base.Monoid Futhark.Pass.ExtractKernels.Intragroup.Acc -- | 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) -- bnds_a... -- map(g) ---- -- Then we want to distribute to: -- --
-- map -- map(f) -- map -- bnds_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 Kernels 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.Kernels.Kernels Futhark.Pass.ExtractKernels.DistribM instance Futhark.IR.Prop.Scope.HasScope Futhark.IR.Kernels.Kernels 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 -- | 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 Kernels Kernels instance GHC.Base.Semigroup Futhark.Optimise.TileLoops.PrivStms instance GHC.Base.Monoid Futhark.Optimise.TileLoops.PrivStms -- | 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 the Kernels representation. This is not
-- because we do anything kernel-specific here, but simply because more
-- explicit indexing is going on after SOACs are gone.
module Futhark.Optimise.Sink
-- | The pass definition.
sink :: Pass Kernels Kernels
module Futhark.Optimise.InPlaceLowering.LowerIntoStm
lowerUpdateKernels :: MonadFreshNames m => LowerUpdate Kernels m
lowerUpdate :: (MonadFreshNames m, Bindable lore, LetDec lore ~ Type, CanBeAliased (Op lore)) => LowerUpdate lore m
type LowerUpdate lore m = Scope (Aliases lore) -> Stm (Aliases lore) -> [DesiredUpdate (LetDec (Aliases lore))] -> Maybe (m [Stm (Aliases lore)])
data DesiredUpdate dec
DesiredUpdate :: VName -> dec -> Certificates -> VName -> Slice SubExp -> VName -> DesiredUpdate dec
-- | Name of result.
[updateName] :: DesiredUpdate dec -> VName
-- | Type of result.
[updateType] :: DesiredUpdate dec -> dec
[updateCertificates] :: DesiredUpdate dec -> Certificates
[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] in -- let r1[i] = a * i in -- r1 -- in -- ... -- 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] in -- let x[k,i] = a * i in -- x -- in -- let r = x[y] 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: -- --
-- 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 lore Stream :: SubExp -> StreamForm lore -> Lambda lore -> [Input] -> SOAC lore Scatter :: SubExp -> Lambda lore -> [Input] -> [(SubExp, Int, VName)] -> SOAC lore Screma :: SubExp -> ScremaForm lore -> [Input] -> SOAC lore Hist :: SubExp -> [HistOp lore] -> Lambda lore -> [Input] -> SOAC lore -- | The essential parts of a Screma factored out (everything except -- the input arrays). data ScremaForm lore ScremaForm :: [Scan lore] -> [Reduce lore] -> Lambda lore -> ScremaForm lore -- | Returns the inputs used in a SOAC. inputs :: SOAC lore -> [Input] -- | Set the inputs to a SOAC. setInputs :: [Input] -> SOAC lore -> SOAC lore -- | The lambda used in a given SOAC. lambda :: SOAC lore -> Lambda lore -- | Set the lambda used in the SOAC. setLambda :: Lambda lore -> SOAC lore -> SOAC lore -- | The return type of a SOAC. typeOf :: SOAC lore -> [Type] -- | The "width" of a SOAC is the expected outer size of its array inputs -- _after_ input-transforms have been carried out. width :: SOAC lore -> 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 lore ~ SOAC lore, HasScope lore m) => Exp lore -> m (Either NotSOAC (SOAC lore)) -- | Convert a SOAC to the corresponding expression. toExp :: (MonadBinder m, Op (Lore m) ~ SOAC (Lore m)) => SOAC (Lore m) -> m (Exp (Lore m)) -- | Convert a SOAC to a Futhark-level SOAC. toSOAC :: MonadBinder m => SOAC (Lore m) -> m (SOAC (Lore 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 :: Certificates -> [Int] -> ArrayTransform -- | A reshaping of an otherwise valid input. Reshape :: Certificates -> ShapeChange SubExp -> ArrayTransform -- | A reshaping of the outer dimension. ReshapeOuter :: Certificates -> ShapeChange SubExp -> ArrayTransform -- | A reshaping of everything but the outer dimension. ReshapeInner :: Certificates -> ShapeChange SubExp -> ArrayTransform -- | Replicate the rows of the array a number of times. Replicate :: Certificates -> 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 :: Certificates -> Exp lore -> Maybe (VName, ArrayTransform) -- | To-Stream translation of SOACs. Returns the Stream SOAC and the -- extra-accumulator body-result ident if any. soacToStream :: (MonadFreshNames m, Bindable lore, Op lore ~ SOAC lore) => SOAC lore -> m (SOAC lore, [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.Decorations.Decorations lore => GHC.Show.Show (Futhark.Analysis.HORep.SOAC.SOAC lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Classes.Eq (Futhark.Analysis.HORep.SOAC.SOAC lore) instance GHC.Show.Show Futhark.Analysis.HORep.SOAC.NotSOAC instance Futhark.IR.Pretty.PrettyLore lore => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.Analysis.HORep.SOAC.SOAC lore) 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 :: Bindable lore => Names -> Lambda lore -> [Input] -> [(VName, Ident)] -> Lambda lore -> [Input] -> (Lambda lore, [Input]) fuseRedomap :: Bindable lore => Names -> [VName] -> Lambda lore -> [SubExp] -> [SubExp] -> [Input] -> [(VName, Ident)] -> Lambda lore -> [SubExp] -> [SubExp] -> [Input] -> (Lambda lore, [Input]) mergeReduceOps :: Lambda lore -> Lambda lore -> Lambda lore module Futhark.Analysis.HORep.MapNest data Nesting lore Nesting :: [VName] -> [VName] -> [Type] -> SubExp -> Nesting lore [nestingParamNames] :: Nesting lore -> [VName] [nestingResult] :: Nesting lore -> [VName] [nestingReturnType] :: Nesting lore -> [Type] [nestingWidth] :: Nesting lore -> SubExp data MapNest lore MapNest :: SubExp -> Lambda lore -> [Nesting lore] -> [Input] -> MapNest lore typeOf :: MapNest lore -> [Type] params :: MapNest lore -> [VName] inputs :: MapNest lore -> [Input] setInputs :: [Input] -> MapNest lore -> MapNest lore fromSOAC :: (Bindable lore, MonadFreshNames m, LocalScope lore m, Op lore ~ SOAC lore) => SOAC lore -> m (Maybe (MapNest lore)) toSOAC :: (MonadFreshNames m, HasScope lore m, Bindable lore, BinderOps lore, Op lore ~ SOAC lore) => MapNest lore -> m (SOAC lore) instance GHC.Show.Show (Futhark.Analysis.HORep.MapNest.Nesting lore) instance GHC.Classes.Ord (Futhark.Analysis.HORep.MapNest.Nesting lore) instance GHC.Classes.Eq (Futhark.Analysis.HORep.MapNest.Nesting lore) instance Futhark.IR.Decorations.Decorations lore => GHC.Show.Show (Futhark.Analysis.HORep.MapNest.MapNest lore) 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] -> Binder 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 Kernels sequentialCpuPipeline :: Pipeline SOACS SeqMem gpuPipeline :: Pipeline SOACS KernelsMem -- | 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 :: Bool -> [Param] -> [Param] -> Code a -> [ExternalValue] -> [ExternalValue] -> FunctionT a [functionEntry] :: FunctionT a -> Bool [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 block size, 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. data ExternalValue -- | The string is a human-readable description with no other semantics. OpaqueValue :: String -> [ValueDesc] -> ExternalValue TransparentValue :: 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 given type. The bound is -- evaluated just once, before the loop is entered. For :: VName -> IntType -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. While :: Exp -> 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 Exp -> 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 Exp -> Space -> VName -> Count Bytes Exp -> Space -> Count Bytes Exp -> 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 Exp -> 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 :: Exp -> 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 -- | 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 cert. Checked :: PrimValue -- | The leaves of an Exp. data ExpLeaf -- | A scalar variable. The type is stored in the LeafExp -- constructor itself. ScalarVar :: VName -> ExpLeaf -- | The size of a primitive type. SizeOf :: PrimType -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements Exp -> PrimType -> Space -> Volatility -> ExpLeaf -- | A side-effect free expression whose execution will produce a single -- primitive value. type Exp = PrimExp 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 -> Exp -- | Concise wrapper for using Index. index :: VName -> Count Elements Exp -> 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 integer value. ErrorInt32 :: 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 -- | 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. 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 :: Exp -> Count Elements Exp -- | This expression counts bytes. bytes :: Exp -> Count Bytes Exp -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements Exp -> PrimType -> Count Bytes Exp -- | 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.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 Text.PrettyPrint.Mainland.Class.Pretty op => Text.PrettyPrint.Mainland.Class.Pretty (Futhark.CodeGen.ImpCode.Definitions op) 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 Text.PrettyPrint.Mainland.Class.Pretty 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 -- | 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 :: Bool -> [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 -- | 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 -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data 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 Cert :: PrimType -- | A floating point type. data 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 -- | 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 -- | 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 -- | 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 integer value. ErrorInt32 :: 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 lore), FreeIn (LetDec lore), FreeIn (LParamInfo lore), FreeIn (FParamInfo lore), FreeDec (BodyDec lore), FreeDec (ExpDec lore)) => Stms lore -> 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 lore -> Names -- | The names bound by a binding. boundByStm :: Stm lore -> Names -- | The names bound by the bindings. boundByStms :: Stms lore -> Names -- | The names of the lambda parameters plus the index parameter. boundByLambda :: Lambda lore -> [VName] -- | 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 -- | 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. (.&&.) :: PrimExp v -> PrimExp v -> PrimExp v infixr 3 .&&. -- | Lifted logical conjunction. (.||.) :: PrimExp v -> PrimExp v -> PrimExp v infixr 2 .||. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .<. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<=.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .<=. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.==.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .==. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .>. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>=.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .>=. -- | Lifted bitwise operators. (.&.) :: PrimExp v -> PrimExp v -> PrimExp v -- | Lifted bitwise operators. (.|.) :: PrimExp v -> PrimExp v -> PrimExp v -- | Lifted bitwise operators. (.^.) :: PrimExp v -> 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 :: PrimExp v -- | Boolean-valued PrimExps. false :: PrimExp 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 -- | 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 -- | The size of a primitive type. SizeOf :: PrimType -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements Exp -> 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 -- | 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 -- | Function call. The results are written to the provided VName -- variables. pattern Call :: () => [VName] -> Name -> [Arg] -> 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 -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. pattern Copy :: () => VName -> Count Bytes Exp -> Space -> VName -> Count Bytes Exp -> Space -> Count Bytes Exp -> Code a -- | Memory space must match the corresponding DeclareMem. pattern Allocate :: () => VName -> Count Bytes Exp -> 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 given type. The bound is -- evaluated just once, before the loop is entered. pattern For :: () => VName -> IntType -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. pattern While :: () => Exp -> 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 Exp -> PrimType -> Space -> Volatility -> Exp -> Code a -- | Conditional execution. pattern If :: () => Exp -> 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. data ExternalValue -- | The string is a human-readable description with no other semantics. OpaqueValue :: String -> [ValueDesc] -> ExternalValue TransparentValue :: ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block, memory block size, 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. 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 :: Exp -> Count Elements Exp -- | This expression counts bytes. bytes :: Exp -> Count Bytes Exp -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements Exp -> PrimType -> Count Bytes Exp -- | Turn a VName into a ScalarVar. var :: VName -> PrimType -> Exp -- | Turn a VName into a Int32 ScalarVar. vi32 :: VName -> Exp -- | Concise wrapper for using Index. index :: VName -> Count Elements Exp -> PrimType -> Space -> Volatility -> Exp 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 :: String -> String -> Map KernelName KernelSafety -> [PrimType] -> Map Name SizeClass -> [FailureMsg] -> Definitions OpenCL -> Program [openClProgram] :: Program -> String -- | Must be prepended to the program. [openClPrelude] :: Program -> String [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 :: Bool -> [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 -- | 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 -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data 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 Cert :: PrimType -- | A floating point type. data 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 -- | 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 -- | 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 -- | 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 integer value. ErrorInt32 :: 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 lore), FreeIn (LetDec lore), FreeIn (LParamInfo lore), FreeIn (FParamInfo lore), FreeDec (BodyDec lore), FreeDec (ExpDec lore)) => Stms lore -> 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 lore -> Names -- | The names bound by a binding. boundByStm :: Stm lore -> Names -- | The names bound by the bindings. boundByStms :: Stms lore -> Names -- | The names of the lambda parameters plus the index parameter. boundByLambda :: Lambda lore -> [VName] -- | 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 -- | 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. (.&&.) :: PrimExp v -> PrimExp v -> PrimExp v infixr 3 .&&. -- | Lifted logical conjunction. (.||.) :: PrimExp v -> PrimExp v -> PrimExp v infixr 2 .||. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .<. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<=.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .<=. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.==.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .==. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .>. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>=.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .>=. -- | Lifted bitwise operators. (.&.) :: PrimExp v -> PrimExp v -> PrimExp v -- | Lifted bitwise operators. (.|.) :: PrimExp v -> PrimExp v -> PrimExp v -- | Lifted bitwise operators. (.^.) :: PrimExp v -> 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 :: PrimExp v -- | Boolean-valued PrimExps. false :: PrimExp 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 -- | 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 -- | The size of a primitive type. SizeOf :: PrimType -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements Exp -> 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 -- | 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 -- | Function call. The results are written to the provided VName -- variables. pattern Call :: () => [VName] -> Name -> [Arg] -> 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 -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. pattern Copy :: () => VName -> Count Bytes Exp -> Space -> VName -> Count Bytes Exp -> Space -> Count Bytes Exp -> Code a -- | Memory space must match the corresponding DeclareMem. pattern Allocate :: () => VName -> Count Bytes Exp -> 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 given type. The bound is -- evaluated just once, before the loop is entered. pattern For :: () => VName -> IntType -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. pattern While :: () => Exp -> 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 Exp -> PrimType -> Space -> Volatility -> Exp -> Code a -- | Conditional execution. pattern If :: () => Exp -> 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. data ExternalValue -- | The string is a human-readable description with no other semantics. OpaqueValue :: String -> [ValueDesc] -> ExternalValue TransparentValue :: ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block, memory block size, 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. 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 :: Exp -> Count Elements Exp -- | This expression counts bytes. bytes :: Exp -> Count Bytes Exp -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements Exp -> PrimType -> Count Bytes Exp -- | Turn a VName into a ScalarVar. var :: VName -> PrimType -> Exp -- | Turn a VName into a Int32 ScalarVar. vi32 :: VName -> Exp -- | Concise wrapper for using Index. index :: VName -> Count Elements Exp -> PrimType -> Space -> Volatility -> Exp 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 -- | Variation of Futhark.CodeGen.ImpCode that contains the notion -- of a kernel invocation. module Futhark.CodeGen.ImpCode.Kernels -- | 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 :: Bool -> [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 Exp -> 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 Exp -> Exp -> AtomicOp AtomicFAdd :: FloatType -> VName -> VName -> Count Elements Exp -> Exp -> AtomicOp AtomicSMax :: IntType -> VName -> VName -> Count Elements Exp -> Exp -> AtomicOp AtomicSMin :: IntType -> VName -> VName -> Count Elements Exp -> Exp -> AtomicOp AtomicUMax :: IntType -> VName -> VName -> Count Elements Exp -> Exp -> AtomicOp AtomicUMin :: IntType -> VName -> VName -> Count Elements Exp -> Exp -> AtomicOp AtomicAnd :: IntType -> VName -> VName -> Count Elements Exp -> Exp -> AtomicOp AtomicOr :: IntType -> VName -> VName -> Count Elements Exp -> Exp -> AtomicOp AtomicXor :: IntType -> VName -> VName -> Count Elements Exp -> Exp -> AtomicOp AtomicCmpXchg :: PrimType -> VName -> VName -> Count Elements Exp -> Exp -> Exp -> AtomicOp AtomicXchg :: PrimType -> VName -> VName -> Count Elements Exp -> 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 -- | 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 -- | Non-array values. data PrimValue IntValue :: !IntValue -> PrimValue FloatValue :: !FloatValue -> PrimValue BoolValue :: !Bool -> PrimValue -- | The only value of type cert. Checked :: PrimValue -- | A floating-point value. data 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 Cert :: PrimType -- | A floating point type. data 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 -- | 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 -- | 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 -- | 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 integer value. ErrorInt32 :: 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 lore), FreeIn (LetDec lore), FreeIn (LParamInfo lore), FreeIn (FParamInfo lore), FreeDec (BodyDec lore), FreeDec (ExpDec lore)) => Stms lore -> 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 lore -> Names -- | The names bound by a binding. boundByStm :: Stm lore -> Names -- | The names bound by the bindings. boundByStms :: Stms lore -> Names -- | The names of the lambda parameters plus the index parameter. boundByLambda :: Lambda lore -> [VName] -- | 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 -- | 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. (.&&.) :: PrimExp v -> PrimExp v -> PrimExp v infixr 3 .&&. -- | Lifted logical conjunction. (.||.) :: PrimExp v -> PrimExp v -> PrimExp v infixr 2 .||. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .<. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.<=.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .<=. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.==.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .==. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .>. -- | Lifted relational operators; assuming signed numbers in case of -- integers. (.>=.) :: PrimExp v -> PrimExp v -> PrimExp v infix 4 .>=. -- | Lifted bitwise operators. (.&.) :: PrimExp v -> PrimExp v -> PrimExp v -- | Lifted bitwise operators. (.|.) :: PrimExp v -> PrimExp v -> PrimExp v -- | Lifted bitwise operators. (.^.) :: PrimExp v -> 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 :: PrimExp v -- | Boolean-valued PrimExps. false :: PrimExp 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 -- | 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 -- | The size of a primitive type. SizeOf :: PrimType -> ExpLeaf -- | Reading a value from memory. The arguments have the same meaning as -- with Write. Index :: VName -> Count Elements Exp -> 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 -- | 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 -- | Function call. The results are written to the provided VName -- variables. pattern Call :: () => [VName] -> Name -> [Arg] -> 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 -- | Destination, offset in destination, destination space, source, offset -- in source, offset space, number of bytes. pattern Copy :: () => VName -> Count Bytes Exp -> Space -> VName -> Count Bytes Exp -> Space -> Count Bytes Exp -> Code a -- | Memory space must match the corresponding DeclareMem. pattern Allocate :: () => VName -> Count Bytes Exp -> 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 given type. The bound is -- evaluated just once, before the loop is entered. pattern For :: () => VName -> IntType -> Exp -> Code a -> Code a -- | While loop. The conditional is (of course) re-evaluated before every -- iteration of the loop. pattern While :: () => Exp -> 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 Exp -> PrimType -> Space -> Volatility -> Exp -> Code a -- | Conditional execution. pattern If :: () => Exp -> 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. data ExternalValue -- | The string is a human-readable description with no other semantics. OpaqueValue :: String -> [ValueDesc] -> ExternalValue TransparentValue :: ValueDesc -> ExternalValue -- | A description of an externally meaningful value. data ValueDesc -- | An array with memory block, memory block size, 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. 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 :: Exp -> Count Elements Exp -- | This expression counts bytes. bytes :: Exp -> Count Bytes Exp -- | Convert a count of elements into a count of bytes, given the -- per-element size. withElemType :: Count Elements Exp -> PrimType -> Count Bytes Exp -- | Turn a VName into a ScalarVar. var :: VName -> PrimType -> Exp -- | Turn a VName into a Int32 ScalarVar. vi32 :: VName -> Exp -- | Concise wrapper for using Index. index :: VName -> Count Elements Exp -> PrimType -> Space -> Volatility -> Exp instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.KernelConst instance GHC.Classes.Ord Futhark.CodeGen.ImpCode.Kernels.KernelConst instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Kernels.KernelConst instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.KernelUse instance GHC.Classes.Eq Futhark.CodeGen.ImpCode.Kernels.KernelUse instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.Fence instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.AtomicOp instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.KernelOp instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.Kernel instance GHC.Show.Show Futhark.CodeGen.ImpCode.Kernels.HostOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.HostOp instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.HostOp instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.Kernel instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.Kernel instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.KernelOp instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.KernelOp instance Futhark.IR.Prop.Names.FreeIn Futhark.CodeGen.ImpCode.Kernels.AtomicOp instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.KernelUse instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.CodeGen.ImpCode.Kernels.KernelConst -- | Carefully optimised implementations of GPU transpositions. Written in -- ImpCode so we can compile it to both CUDA and OpenCL. module Futhark.CodeGen.ImpGen.Kernels.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, Exp, VName, Exp, Exp, Exp, Exp, Exp, Exp, Exp, Exp, 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. -- -- Note that input_size and output_size may not equal width*height if we -- are dealing with a truncated array - this happens sometimes for -- coalescing optimisations. mapTransposeKernel :: String -> Integer -> TransposeArgs -> PrimType -> TransposeType -> Kernel instance GHC.Show.Show Futhark.CodeGen.ImpGen.Kernels.Transpose.TransposeType instance GHC.Classes.Ord Futhark.CodeGen.ImpGen.Kernels.Transpose.TransposeType instance GHC.Classes.Eq Futhark.CodeGen.ImpGen.Kernels.Transpose.TransposeType -- | Simple C runtime representation. 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 primitive type. Integers are assumed to -- be unsigned. primTypeToCType :: PrimType -> Type -- | The C type corresponding to a primitive type. Integers are assumed to -- have the specified sign. signedPrimTypeToCType :: Signedness -> PrimType -> Type cIntOps :: [Definition] cFloat32Ops :: [Definition] cFloat32Funs :: [Definition] cFloat64Ops :: [Definition] cFloat64Funs :: [Definition] cFloatConvOps :: [Definition] -- | 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 => String -> Operations op () -> CompilerM op () () -> String -> [Space] -> [Option] -> Definitions op -> m CParts -- | The result of compilation to C is four 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 :: String -> String -> String -> String -> CParts [cHeader] :: CParts -> String -- | Utility definitions that must be visible to both CLI and library -- parts. [cUtils] :: CParts -> String [cCLI] :: CParts -> String [cLib] :: CParts -> String -- | Produce header and implementation files. asLibrary :: CParts -> (String, String) -- | As executable with command-line interface. asExecutable :: CParts -> String 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 -> 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 -- | 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) 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 compilePrimValue :: PrimValue -> 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 () -- | 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 () -- | The C type corresponding to a primitive type. Integers are assumed to -- be unsigned. primTypeToCType :: PrimType -> Type copyMemoryDefaultSpace :: Exp -> Exp -> Exp -> Exp -> Exp -> CompilerM op s () instance GHC.Classes.Ord Futhark.CodeGen.Backends.GenericC.HeaderSection instance GHC.Classes.Eq Futhark.CodeGen.Backends.GenericC.HeaderSection instance Control.Monad.Writer.Class.MonadWriter (Futhark.CodeGen.Backends.GenericC.CompilerAcc op s) (Futhark.CodeGen.Backends.GenericC.CompilerM op s) 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) instance GHC.Base.Semigroup (Futhark.CodeGen.Backends.GenericC.CompilerAcc op s) instance GHC.Base.Monoid (Futhark.CodeGen.Backends.GenericC.CompilerAcc op s) 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 -- | This module defines a translation from imperative code with kernels to -- imperative code with OpenCL calls. module Futhark.CodeGen.ImpGen.Kernels.ToOpenCL kernelsToOpenCL :: Program -> Program kernelsToCUDA :: Program -> Program instance GHC.Classes.Eq Futhark.CodeGen.ImpGen.Kernels.ToOpenCL.OpsMode module Futhark.CodeGen.Backends.COpenCL.Boilerplate -- | Called after most code has been generated to generate the bulk of the -- boilerplate. generateBoilerplate :: String -> String -> [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 -- | 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 :: String -> String -> [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 :: String -> 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 :: String -> 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] -- | A generic Python code generator which is polymorphic in the type of -- the operations. Concretely, we use this to handle both sequential and -- PyOpenCL Python code. module Futhark.CodeGen.Backends.GenericPython compileProg :: MonadFreshNames m => Maybe String -> Constructor -> [PyStmt] -> [PyStmt] -> Operations op s -> s -> [PyStmt] -> [Option] -> Definitions op -> m String -- | The class generated by the code generator must have a constructor, -- although it can be vacuous. data Constructor Constructor :: [String] -> [PyStmt] -> Constructor -- | A constructor that takes no arguments and does nothing. emptyConstructor :: Constructor compileName :: VName -> String compileVar :: VName -> CompilerM op s PyExp compileDim :: DimSize -> PyExp compileExp :: Exp -> CompilerM op s PyExp -- | Tell me how to compile a v, and I'll Compile any PrimExp -- v for you. compilePrimExp :: Monad m => (v -> m PyExp) -> PrimExp v -> m PyExp compileCode :: Code op -> CompilerM op s () compilePrimValue :: PrimValue -> PyExp -- | The ctypes type corresponding to a PrimType. compilePrimType :: PrimType -> String -- | The ctypes type corresponding to a PrimType, taking sign into -- account. compilePrimTypeExt :: PrimType -> Signedness -> String -- | The Numpy type corresponding to a PrimType. compilePrimToNp :: PrimType -> String -- | The Numpy type corresponding to a PrimType, taking sign into -- account. compilePrimToExtNp :: PrimType -> Signedness -> String data Operations op s Operations :: WriteScalar op s -> ReadScalar op s -> Allocate op s -> Copy op s -> StaticArray op s -> OpCompiler op s -> EntryOutput op s -> EntryInput op s -> Operations op s [opsWriteScalar] :: Operations op s -> WriteScalar op s [opsReadScalar] :: Operations op s -> ReadScalar op s [opsAllocate] :: Operations op s -> Allocate op s [opsCopy] :: Operations op s -> Copy op s [opsStaticArray] :: Operations op s -> StaticArray op s [opsCompiler] :: Operations op s -> OpCompiler op s [opsEntryOutput] :: Operations op s -> EntryOutput op s [opsEntryInput] :: Operations op s -> EntryInput op s -- | 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 unpackDim :: PyExp -> DimSize -> Int32 -> CompilerM op s () newtype CompilerM op s a CompilerM :: RWS (CompilerEnv op s) [PyStmt] (CompilerState s) a -> CompilerM op s a -- | A substitute expression compiler, tried before the main compilation -- function. type OpCompiler op s = op -> CompilerM op s () -- | Write a scalar to the given memory block with the given index and in -- the given memory space. type WriteScalar op s = PyExp -> PyExp -> PrimType -> SpaceId -> PyExp -> CompilerM op s () -- | Read a scalar from the given memory block with the given index and in -- the given memory space. type ReadScalar op s = PyExp -> PyExp -> PrimType -> SpaceId -> CompilerM op s PyExp -- | Allocate a memory block of the given size in the given memory space, -- saving a reference in the given variable name. type Allocate op s = PyExp -> PyExp -> SpaceId -> CompilerM op s () -- | Copy from one memory block to another. type Copy op s = PyExp -> PyExp -> Space -> PyExp -> PyExp -> Space -> PyExp -> PrimType -> CompilerM op s () -- | Create a static array of values - initialised at load time. type StaticArray op s = VName -> SpaceId -> PrimType -> ArrayContents -> CompilerM op s () -- | Construct the Python array being returned from an entry point. type EntryOutput op s = VName -> SpaceId -> PrimType -> Signedness -> [DimSize] -> CompilerM op s PyExp -- | Unpack the array being passed to an entry point. type EntryInput op s = PyExp -> SpaceId -> PrimType -> Signedness -> [DimSize] -> PyExp -> CompilerM op s () data CompilerEnv op s CompilerEnv :: Operations op s -> Map VName PyExp -> CompilerEnv op s [envOperations] :: CompilerEnv op s -> Operations op s [envVarExp] :: CompilerEnv op s -> Map VName PyExp data CompilerState s CompilerState :: VNameSource -> [PyStmt] -> s -> CompilerState s [compNameSrc] :: CompilerState s -> VNameSource [compInit] :: CompilerState s -> [PyStmt] [compUserState] :: CompilerState s -> s stm :: PyStmt -> CompilerM op s () atInit :: PyStmt -> CompilerM op s () collect' :: CompilerM op s a -> CompilerM op s (a, [PyStmt]) collect :: CompilerM op s () -> CompilerM op s [PyStmt] -- | A Call where the function is a variable and every argument is a -- simple Arg. simpleCall :: String -> [PyExp] -> PyExp copyMemoryDefaultSpace :: PyExp -> PyExp -> PyExp -> PyExp -> PyExp -> CompilerM op s () instance Control.Monad.Writer.Class.MonadWriter [Futhark.CodeGen.Backends.GenericPython.AST.PyStmt] (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance Control.Monad.Reader.Class.MonadReader (Futhark.CodeGen.Backends.GenericPython.CompilerEnv op s) (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance Control.Monad.State.Class.MonadState (Futhark.CodeGen.Backends.GenericPython.CompilerState s) (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance GHC.Base.Monad (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance GHC.Base.Applicative (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance GHC.Base.Functor (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) instance Futhark.MonadFreshNames.MonadFreshNames (Futhark.CodeGen.Backends.GenericPython.CompilerM op s) -- | Various boilerplate definitions for the PyOpenCL backend. module Futhark.CodeGen.Backends.PyOpenCL.Boilerplate -- | Python code (as a string) that calls the -- initiatialize_opencl_object procedure. Should be put in the -- class constructor. openClInit :: [PrimType] -> String -> Map Name SizeClass -> [FailureMsg] -> String -- | rtspythonopencl.py embedded as a string. openClPrelude :: String -- | 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. -- See the https://futhark.readthedocs.org@ for a language -- reference, or this module may be a little hard to understand. module Language.Futhark.Syntax -- | 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 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 dimension declaration. AnyDim :: 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) -- | unifyShapes x y combines x and y to contain -- their maximum common information, and fails if they conflict. unifyShapes :: ArrayDim dim => ShapeDecl dim -> 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 PatternType = 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 Int32 () -- | 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 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 PatternType -> SrcLoc -> IdentBase f vn [identName] :: IdentBase f vn -> vn [identType] :: IdentBase f vn -> f PatternType [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 -- | The Futhark expression language. -- -- In a value of type Exp f vn, annotations are wrapped in the -- functor f, and all names are of type vn. -- -- 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 PatternType -> SrcLoc -> ExpBase f vn -- | A polymorphic decimal literal. FloatLit :: Double -> f PatternType -> SrcLoc -> ExpBase f vn -- | A string literal is just a fancy syntax for an array of bytes. StringLit :: [Word8] -> 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 PatternType -> SrcLoc -> ExpBase f vn Range :: ExpBase f vn -> Maybe (ExpBase f vn) -> Inclusiveness (ExpBase f vn) -> (f PatternType, f [VName]) -> SrcLoc -> ExpBase f vn Var :: QualName vn -> f PatternType -> SrcLoc -> ExpBase f vn -- | Type ascription: e : t. Ascript :: ExpBase f vn -> TypeDeclBase f vn -> SrcLoc -> ExpBase f vn -- | Size coercion: e :> t. Coerce :: ExpBase f vn -> TypeDeclBase f vn -> (f PatternType, f [VName]) -> SrcLoc -> ExpBase f vn LetPat :: PatternBase f vn -> ExpBase f vn -> ExpBase f vn -> (f PatternType, f [VName]) -> SrcLoc -> ExpBase f vn LetFun :: vn -> ([TypeParamBase vn], [PatternBase f vn], Maybe (TypeExp vn), f StructType, ExpBase f vn) -> ExpBase f vn -> f PatternType -> SrcLoc -> ExpBase f vn If :: ExpBase f vn -> ExpBase f vn -> ExpBase f vn -> (f PatternType, f [VName]) -> SrcLoc -> ExpBase f vn -- | The Maybe VName is a possible existential size that is -- instantiated by this argument.. -- -- The [VName] are the existential sizes that come into being at -- this call site. Apply :: ExpBase f vn -> ExpBase f vn -> f (Diet, Maybe VName) -> (f PatternType, f [VName]) -> SrcLoc -> ExpBase f vn -- | Numeric negation (ugly special case; Haskell did it first). Negate :: ExpBase f vn -> SrcLoc -> ExpBase f vn Lambda :: [PatternBase 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 PatternType -> SrcLoc -> ExpBase f vn -- | 2+; first type is operand, second is result. OpSectionLeft :: QualName vn -> f PatternType -> ExpBase f vn -> (f (StructType, Maybe VName), f StructType) -> (f PatternType, f [VName]) -> SrcLoc -> ExpBase f vn -- | +2; first type is operand, second is result. OpSectionRight :: QualName vn -> f PatternType -> ExpBase f vn -> (f StructType, f (StructType, Maybe VName)) -> f PatternType -> SrcLoc -> ExpBase f vn -- | Field projection as a section: (.x.y.z). ProjectSection :: [Name] -> f PatternType -> SrcLoc -> ExpBase f vn -- | Array indexing as a section: (.[i,j]). IndexSection :: [DimIndexBase f vn] -> f PatternType -> SrcLoc -> ExpBase f vn DoLoop :: [VName] -> PatternBase f vn -> ExpBase f vn -> LoopFormBase f vn -> ExpBase f vn -> f (PatternType, [VName]) -> SrcLoc -> ExpBase f vn BinOp :: (QualName vn, SrcLoc) -> f PatternType -> (ExpBase f vn, f (StructType, Maybe VName)) -> (ExpBase f vn, f (StructType, Maybe VName)) -> f PatternType -> f [VName] -> SrcLoc -> ExpBase f vn Project :: Name -> ExpBase f vn -> f PatternType -> SrcLoc -> ExpBase f vn LetWith :: IdentBase f vn -> IdentBase f vn -> [DimIndexBase f vn] -> ExpBase f vn -> ExpBase f vn -> f PatternType -> SrcLoc -> ExpBase f vn Index :: ExpBase f vn -> [DimIndexBase f vn] -> (f PatternType, f [VName]) -> SrcLoc -> ExpBase f vn Update :: ExpBase f vn -> [DimIndexBase f vn] -> ExpBase f vn -> SrcLoc -> ExpBase f vn RecordUpdate :: ExpBase f vn -> [Name] -> ExpBase f vn -> f PatternType -> 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 PatternType -> SrcLoc -> ExpBase f vn -- | A match expression. Match :: ExpBase f vn -> NonEmpty (CaseBase f vn) -> (f PatternType, f [VName]) -> SrcLoc -> ExpBase f vn -- | An attribute applied to the following expression. Attr :: AttrInfo -> ExpBase f vn -> SrcLoc -> 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 PatternType -> SrcLoc -> FieldBase f vn -- | A case in a match expression. data CaseBase f vn CasePat :: PatternBase 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 :: PatternBase f vn -> ExpBase f vn -> LoopFormBase f vn While :: ExpBase f vn -> LoopFormBase f vn -- | A pattern as used most places where variables are bound (function -- parameters, let expressions, etc). data PatternBase f vn TuplePattern :: [PatternBase f vn] -> SrcLoc -> PatternBase f vn RecordPattern :: [(Name, PatternBase f vn)] -> SrcLoc -> PatternBase f vn PatternParens :: PatternBase f vn -> SrcLoc -> PatternBase f vn Id :: vn -> f PatternType -> SrcLoc -> PatternBase f vn Wildcard :: f PatternType -> SrcLoc -> PatternBase f vn PatternAscription :: PatternBase f vn -> TypeDeclBase f vn -> SrcLoc -> PatternBase f vn PatternLit :: ExpBase f vn -> f PatternType -> SrcLoc -> PatternBase f vn PatternConstr :: Name -> f PatternType -> [PatternBase f vn] -> SrcLoc -> PatternBase 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. 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] -> [PatternBase 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 -> [PatternBase 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 PatternType), Show (f (PatternType, [VName])), Show (f (StructType, [VName])), Show (f EntryPoint), Show (f Int), Show (f StructType), Show (f (StructType, Maybe VName)), Show (f (Aliasing, StructType)), Show (f (Map VName VName)), Show (f Uniqueness)) => 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 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.Name) instance GHC.Classes.Eq (Language.Futhark.Syntax.DimDecl Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.DimDecl Language.Futhark.Core.Name) 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.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.PatternBase f vn) instance GHC.Classes.Eq (Language.Futhark.Syntax.PatternBase Language.Futhark.Syntax.NoInfo Language.Futhark.Core.VName) instance GHC.Classes.Ord (Language.Futhark.Syntax.PatternBase 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.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.PatternBase 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 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. 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 :: PrimType -> 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 -> PatternType -- | The set of identifiers bound in a pattern. patternIdents :: (Functor f, Ord vn) => PatternBase f vn -> Set (IdentBase f vn) -- | The set of names bound in a pattern. patternNames :: (Functor f, Ord vn) => PatternBase f vn -> Set vn -- | A mapping from names bound in a map to their identifier. patternMap :: Functor f => PatternBase f VName -> Map VName (IdentBase f VName) -- | The type of values bound by the pattern. patternType :: PatternBase Info VName -> PatternType -- | The type matched by the pattern, including shape declarations if -- present. patternStructType :: PatternBase Info VName -> StructType -- | When viewed as a function parameter, does this pattern correspond to a -- named parameter of some type? patternParam :: PatternBase Info VName -> (PName, StructType) -- | patternOrderZero pat is True if all of the types in -- the given pattern have order 0. patternOrderZero :: PatternBase Info vn -> Bool -- | Extract all the shape names that occur in a given pattern. patternDimNames :: PatternBase 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 -- | The size of values of this type, in bytes. primByteSize :: Num a => PrimType -> a -- | Construct a ShapeDecl with the given number of AnyDim -- dimensions. rank :: Int -> ShapeDecl (DimDecl 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 -- | Add size annotations that are all AnyDim. addSizes :: TypeBase () as -> TypeBase (DimDecl vn) 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) -- | The type is leaving a scope, so clean up any aliases that reference -- the bound variables, and turn any dimensions that name them into -- AnyDim instead. unscopeType :: Set VName -> PatternType -> PatternType -- | Perform some operation on a given record field. Returns Nothing -- if that field does not exist. onRecordField :: (TypeBase dim als -> TypeBase dim als) -> [Name] -> TypeBase dim als -> Maybe (TypeBase dim als) -- | 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 -- | 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 UncheckedPattern = PatternBase 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.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.PatternBase 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 (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.Int32) 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.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 UNOP :: Name -> Token QUALUNOP :: [Name] -> Name -> Token SYMBOL :: BinOp -> [Name] -> Name -> Token CONSTRUCTOR :: Name -> Token PROJ_FIELD :: Name -> Token PROJ_INDEX :: Token INTLIT :: Integer -> Token STRINGLIT :: String -> 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 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 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 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 -- | An expression with type information. type Exp = ExpBase Info VName -- | A pattern with type information. type Pattern = PatternBase 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 :: Loc -> String -> a -> ExtOp a ExtOpBreak :: 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 -- | The names that are bound for some types, either implicitly or -- explicitly. data BoundInTypes -- | Determine the names bound for some types. boundInTypes :: [TypeParam] -> BoundInTypes internaliseReturnType :: TypeBase (DimDecl VName) () -> InternaliseM [TypeBase ExtShape Uniqueness] -- | As internaliseReturnType, but returns components of a top-level -- tuple type piecemeal. internaliseEntryReturnType :: TypeBase (DimDecl VName) () -> InternaliseM [[TypeBase ExtShape Uniqueness]] internaliseParamTypes :: BoundInTypes -> Map VName VName -> [TypeBase (DimDecl VName) ()] -> InternaliseM [[TypeBase ExtShape Uniqueness]] internaliseType :: TypeBase (DimDecl VName) () -> InternaliseM [TypeBase ExtShape 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) () -> 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 GHC.Base.Monoid Futhark.Internalise.TypesValues.BoundInTypes instance GHC.Base.Semigroup Futhark.Internalise.TypesValues.BoundInTypes module Futhark.Internalise.Lambdas -- | A function for internalising lambdas. type InternaliseLambda = Exp -> [Type] -> InternaliseM ([LParam], Body, [ExtType]) 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 -- | Defunctionalization of typed, monomorphic Futhark programs without -- modules. module Futhark.Internalise.Defunctionalise -- | Transform a list of top-level value bindings. May produce new lifted -- function definitions, which are placed in front of the resulting list -- of declarations. transformProg :: MonadFreshNames m => [ValBind] -> m [ValBind] instance GHC.Show.Show Futhark.Internalise.Defunctionalise.ExtExp instance GHC.Show.Show Futhark.Internalise.Defunctionalise.StaticVal instance Futhark.MonadFreshNames.MonadFreshNames Futhark.Internalise.Defunctionalise.DefM instance Control.Monad.Writer.Class.MonadWriter (Data.Sequence.Internal.Seq Language.Futhark.ValBind) Futhark.Internalise.Defunctionalise.DefM instance Control.Monad.Reader.Class.MonadReader (Data.Set.Internal.Set Language.Futhark.Core.VName, Futhark.Internalise.Defunctionalise.Env) Futhark.Internalise.Defunctionalise.DefM instance GHC.Base.Monad Futhark.Internalise.Defunctionalise.DefM instance GHC.Base.Applicative Futhark.Internalise.Defunctionalise.DefM instance GHC.Base.Functor Futhark.Internalise.Defunctionalise.DefM instance GHC.Show.Show Futhark.Internalise.Defunctionalise.NameSet instance GHC.Base.Semigroup Futhark.Internalise.Defunctionalise.NameSet instance GHC.Base.Monoid Futhark.Internalise.Defunctionalise.NameSet module Futhark.Internalise.Bindings bindingParams :: [TypeParam] -> [Pattern] -> ([FParam] -> [[FParam]] -> InternaliseM a) -> InternaliseM a bindingLambdaParams :: [Pattern] -> [Type] -> ([LParam] -> InternaliseM a) -> InternaliseM a stmPattern :: Pattern -> [ExtType] -> ([VName] -> MatchPattern -> InternaliseM a) -> InternaliseM a type MatchPattern = SrcLoc -> [SubExp] -> InternaliseM [SubExp] -- | This module defines an efficient value representation as well as -- parsing and comparison functions. This is because the standard Futhark -- parser is not able to cope with large values (like arrays that are -- tens of megabytes in size). The representation defined here does not -- support tuples, so don't use those as input/output for your test -- programs. module Futhark.Test.Values -- | An efficiently represented Futhark value. Use pretty to get a -- human-readable representation, and put to obtain binary a -- representation. data Value Int8Value :: Vector Int -> Vector Int8 -> Value Int16Value :: Vector Int -> Vector Int16 -> Value Int32Value :: Vector Int -> Vector Int32 -> Value Int64Value :: Vector Int -> Vector Int64 -> Value Word8Value :: Vector Int -> Vector Word8 -> Value Word16Value :: Vector Int -> Vector Word16 -> Value Word32Value :: Vector Int -> Vector Word32 -> Value Word64Value :: Vector Int -> Vector Word64 -> Value Float32Value :: Vector Int -> Vector Float -> Value Float64Value :: Vector Int -> Vector Double -> Value BoolValue :: Vector Int -> Vector Bool -> Value -- | An Unboxed vector. type Vector = Vector -- | Parse Futhark values from the given bytestring. readValues :: ByteString -> Maybe [Value] -- | A representation of the simple values we represent in this module. data ValueType ValueType :: [Int] -> PrimType -> ValueType -- | A textual description of the type of a value. Follows Futhark type -- notation, and contains the exact dimension sizes if an array. valueType :: Value -> ValueType -- | Compare two sets of Futhark values for equality. Shapes and types must -- also match. compareValues :: [Value] -> [Value] -> [Mismatch] -- | As compareValues, but only reports one mismatch. compareValues1 :: [Value] -> [Value] -> Maybe Mismatch -- | Two values differ in some way. The Show instance produces a -- human-readable explanation. data Mismatch instance GHC.Show.Show Futhark.Test.Values.Value instance GHC.Show.Show Futhark.Test.Values.ValueType instance GHC.Show.Show Futhark.Test.Values.Mismatch instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Test.Values.ValueType instance Data.Binary.Class.Binary Futhark.Test.Values.Value instance Text.PrettyPrint.Mainland.Class.Pretty Futhark.Test.Values.Value -- | 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] -- | Get the actual core Futhark values corresponding to a Values -- specification. The FilePath is the directory which file paths -- are read relative to. getValues :: (MonadFail m, MonadIO m) => 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 :: MonadIO m => FilePath -> Values -> m ByteString -- | Compare two sets of Futhark values for equality. Shapes and types must -- also match. compareValues :: [Value] -> [Value] -> [Mismatch] -- | As compareValues, but only reports one mismatch. compareValues1 :: [Value] -> [Value] -> Maybe Mismatch -- | 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) => 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] -> FilePath -> String -> FilePath -> m (ByteString, ByteString) -- | runProgram 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 :: MonadIO m => String -> [String] -> String -> Text -> Values -> m (ExitCode, ByteString, ByteString) -- | 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 -> FilePath -> 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 -- | 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 -- | 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. data Values Values :: [Value] -> Values InFile :: FilePath -> Values GenValues :: [GenValue] -> Values -- | An efficiently represented Futhark value. Use pretty to get a -- human-readable representation, and put to obtain binary a -- representation. data Value 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.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 along the stderr that was produced. data DataResult DataResult :: String -> Either Text ([RunResult], Text) -> DataResult -- | The results for all datasets for some benchmark program. data BenchResult BenchResult :: FilePath -> [DataResult] -> BenchResult -- | 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 :: RunOptions -> FilePath -> Text -> Values -> Maybe Success -> FilePath -> IO (Either Text ([RunResult], Text)) -- | How to run a benchmark. data RunOptions RunOptions :: String -> Int -> [String] -> Int -> Int -> Maybe (Int -> IO ()) -> RunOptions [runRunner] :: RunOptions -> String [runRuns] :: RunOptions -> Int [runExtraOptions] :: RunOptions -> [String] [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.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.RunResult instance Data.Aeson.Types.FromJSON.FromJSON Futhark.Bench.RunResult -- | 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 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 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 () -- |
-- 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 dataget --mainDataget :: 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 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 -- |
-- 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