4956d8d5afb4ae6bb3c32f2f310f7245096b862d
[ghc-hetmet.git] / compiler / llvmGen / Llvm / Types.hs
1 --------------------------------------------------------------------------------
2 -- | The LLVM Type System.
3 --
4
5 module Llvm.Types where
6
7 #include "HsVersions.h"
8 #include "ghcconfig.h"
9
10 import Data.Char
11 import Numeric
12
13 import Constants
14 import FastString
15 import Unique
16
17 -- from NCG
18 import PprBase
19
20 -- -----------------------------------------------------------------------------
21 -- * LLVM Basic Types and Variables
22 --
23
24 -- | A global mutable variable. Maybe defined or external
25 type LMGlobal   = (LlvmVar, Maybe LlvmStatic)
26 -- | A String in LLVM
27 type LMString   = FastString
28
29
30 -- | Llvm Types.
31 data LlvmType
32   = LMInt Int                 -- ^ An integer with a given width in bits.
33   | LMFloat                   -- ^ 32 bit floating point
34   | LMDouble                  -- ^ 64 bit floating point
35   | LMFloat80                 -- ^ 80 bit (x86 only) floating point
36   | LMFloat128                -- ^ 128 bit floating point
37   | LMPointer LlvmType        -- ^ A pointer to a 'LlvmType'
38   | LMArray Int LlvmType      -- ^ An array of 'LlvmType'
39   | LMLabel                   -- ^ A 'LlvmVar' can represent a label (address)
40   | LMVoid                    -- ^ Void type
41   | LMStruct [LlvmType]       -- ^ Structure type
42   | LMAlias LMString LlvmType -- ^ A type alias
43
44   -- | Function type, used to create pointers to functions
45   | LMFunction LlvmFunctionDecl
46   deriving (Eq)
47
48 instance Show LlvmType where
49   show (LMInt size    ) = "i" ++ show size
50   show (LMFloat       ) = "float"
51   show (LMDouble      ) = "double"
52   show (LMFloat80     ) = "x86_fp80"
53   show (LMFloat128    ) = "fp128"
54   show (LMPointer x   ) = show x ++ "*"
55   show (LMArray nr tp ) = "[" ++ show nr ++ " x " ++ show tp ++ "]"
56   show (LMLabel       ) = "label"
57   show (LMVoid        ) = "void"
58   show (LMStruct tys  ) = "{" ++ (commaCat tys) ++ "}"
59
60   show (LMFunction (LlvmFunctionDecl _ _ _ r varg p _))
61     = let args = ((drop 1).concat) $ -- use drop since it can handle empty lists
62                   map (\(t,a) -> "," ++ show t ++ " " ++ spaceCat a) p
63           varg' = case varg of
64                         VarArgs | not (null args) -> ", ..."
65                                 | otherwise       -> "..."
66                         _otherwise                -> ""
67       in show r ++ " (" ++ args ++ varg' ++ ")"
68
69   show (LMAlias s _   ) = "%" ++ unpackFS s
70
71 -- | An LLVM section defenition. If Nothing then let LLVM decide the section
72 type LMSection = Maybe LMString
73 type LMAlign = Maybe Int
74 type LMConst = Bool -- ^ is a variable constant or not
75
76 -- | Llvm Variables
77 data LlvmVar
78   -- | Variables with a global scope.
79   = LMGlobalVar LMString LlvmType LlvmLinkageType LMSection LMAlign LMConst
80   -- | Variables local to a function or parameters.
81   | LMLocalVar Unique LlvmType
82   -- | Named local variables. Sometimes we need to be able to explicitly name
83   -- variables (e.g for function arguments).
84   | LMNLocalVar LMString LlvmType
85   -- | A constant variable
86   | LMLitVar LlvmLit
87   deriving (Eq)
88
89 instance Show LlvmVar where
90   show (LMLitVar x) = show x
91   show (x         ) = show (getVarType x) ++ " " ++ getName x
92
93
94 -- | Llvm Literal Data.
95 --
96 -- These can be used inline in expressions.
97 data LlvmLit
98   -- | Refers to an integer constant (i64 42).
99   = LMIntLit Integer LlvmType
100   -- | Floating point literal
101   | LMFloatLit Double LlvmType
102   deriving (Eq)
103
104 instance Show LlvmLit where
105   show l = show (getLitType l) ++ " " ++ getLit l
106
107
108 -- | Llvm Static Data.
109 --
110 -- These represent the possible global level variables and constants.
111 data LlvmStatic
112   = LMComment LMString                  -- ^ A comment in a static section
113   | LMStaticLit LlvmLit                 -- ^ A static variant of a literal value
114   | LMUninitType LlvmType               -- ^ For uninitialised data
115   | LMStaticStr LMString LlvmType       -- ^ Defines a static 'LMString'
116   | LMStaticArray [LlvmStatic] LlvmType -- ^ A static array
117   | LMStaticStruc [LlvmStatic] LlvmType -- ^ A static structure type
118   | LMStaticPointer LlvmVar             -- ^ A pointer to other data
119
120   -- static expressions, could split out but leave
121   -- for moment for ease of use. Not many of them.
122
123   | LMBitc LlvmStatic LlvmType         -- ^ Pointer to Pointer conversion
124   | LMPtoI LlvmStatic LlvmType         -- ^ Pointer to Integer conversion
125   | LMAdd LlvmStatic LlvmStatic        -- ^ Constant addition operation
126   | LMSub LlvmStatic LlvmStatic        -- ^ Constant subtraction operation
127
128 instance Show LlvmStatic where
129   show (LMComment       s) = "; " ++ unpackFS s
130   show (LMStaticLit   l  ) = show l
131   show (LMUninitType    t) = show t ++ " undef"
132   show (LMStaticStr   s t) = show t ++ " c\"" ++ unpackFS s ++ "\\00\""
133
134   show (LMStaticArray d t)
135       = let struc = case d of
136               [] -> "[]"
137               ts -> "[" ++ show (head ts) ++
138                       concat (map (\x -> "," ++ show x) (tail ts)) ++ "]"
139         in show t ++ " " ++ struc
140
141   show (LMStaticStruc d t)
142       = let struc = case d of
143               [] -> "{}"
144               ts -> "{" ++ show (head ts) ++
145                       concat (map (\x -> "," ++ show x) (tail ts)) ++ "}"
146         in show t ++ " " ++ struc
147
148   show (LMStaticPointer v) = show v
149
150   show (LMBitc v t)
151       = show t ++ " bitcast (" ++ show v ++ " to " ++ show t ++ ")"
152
153   show (LMPtoI v t)
154       = show t ++ " ptrtoint (" ++ show v ++ " to " ++ show t ++ ")"
155
156   show (LMAdd s1 s2)
157       = let ty1 = getStatType s1
158         in if ty1 == getStatType s2
159                 then show ty1 ++ " add (" ++ show s1 ++ "," ++ show s2 ++ ")"
160                 else error $ "LMAdd with different types! s1: "
161                         ++ show s1 ++ ", s2: " ++ show s2
162   show (LMSub s1 s2)
163       = let ty1 = getStatType s1
164         in if ty1 == getStatType s2
165                 then show ty1 ++ " sub (" ++ show s1 ++ "," ++ show s2 ++ ")"
166                 else error $ "LMSub with different types! s1: "
167                         ++ show s1 ++ ", s2: " ++ show s2
168
169
170 -- | Concatenate an array together, separated by commas
171 commaCat :: Show a => [a] -> String
172 commaCat [] = ""
173 commaCat x  = show (head x) ++ (concat $ map (\y -> "," ++ show y) (tail x))
174
175 -- | Concatenate an array together, separated by commas
176 spaceCat :: Show a => [a] -> String
177 spaceCat [] = ""
178 spaceCat x  = show (head x) ++ (concat $ map (\y -> " " ++ show y) (tail x))
179
180 -- -----------------------------------------------------------------------------
181 -- ** Operations on LLVM Basic Types and Variables
182 --
183
184 -- | Return the variable name or value of the 'LlvmVar'
185 -- in Llvm IR textual representation (e.g. @\@x@, @%y@ or @42@).
186 getName :: LlvmVar -> String
187 getName v@(LMGlobalVar _ _ _ _ _ _) = "@" ++ getPlainName v
188 getName v@(LMLocalVar  _ _        ) = "%" ++ getPlainName v
189 getName v@(LMNLocalVar _ _        ) = "%" ++ getPlainName v
190 getName v@(LMLitVar    _          ) = getPlainName v
191
192 -- | Return the variable name or value of the 'LlvmVar'
193 -- in a plain textual representation (e.g. @x@, @y@ or @42@).
194 getPlainName :: LlvmVar -> String
195 getPlainName (LMGlobalVar x _ _ _ _ _) = unpackFS x
196 getPlainName (LMLocalVar  x _        ) = show x
197 getPlainName (LMNLocalVar x _        ) = unpackFS x
198 getPlainName (LMLitVar    x          ) = getLit x
199
200 -- | Print a literal value. No type.
201 getLit :: LlvmLit -> String
202 getLit (LMIntLit   i _) = show ((fromInteger i)::Int)
203 getLit (LMFloatLit r LMFloat ) = fToStr $ realToFrac r
204 getLit (LMFloatLit r LMDouble) = dToStr r
205 getLit f@(LMFloatLit _ _) = error $ "Can't print this float literal!" ++ show f
206
207 -- | Return the 'LlvmType' of the 'LlvmVar'
208 getVarType :: LlvmVar -> LlvmType
209 getVarType (LMGlobalVar _ y _ _ _ _) = y
210 getVarType (LMLocalVar  _ y        ) = y
211 getVarType (LMNLocalVar _ y        ) = y
212 getVarType (LMLitVar    l          ) = getLitType l
213
214 -- | Return the 'LlvmType' of a 'LlvmLit'
215 getLitType :: LlvmLit -> LlvmType
216 getLitType (LMIntLit   _ t) = t
217 getLitType (LMFloatLit _ t) = t
218
219 -- | Return the 'LlvmType' of the 'LlvmStatic'
220 getStatType :: LlvmStatic -> LlvmType
221 getStatType (LMStaticLit   l  ) = getLitType l
222 getStatType (LMUninitType    t) = t
223 getStatType (LMStaticStr   _ t) = t
224 getStatType (LMStaticArray _ t) = t
225 getStatType (LMStaticStruc _ t) = t
226 getStatType (LMStaticPointer v) = getVarType v
227 getStatType (LMBitc        _ t) = t
228 getStatType (LMPtoI        _ t) = t
229 getStatType (LMAdd         t _) = getStatType t
230 getStatType (LMSub         t _) = getStatType t
231 getStatType (LMComment       _) = error "Can't call getStatType on LMComment!"
232
233 -- | Return the 'LlvmType' of the 'LMGlobal'
234 getGlobalType :: LMGlobal -> LlvmType
235 getGlobalType (v, _) = getVarType v
236
237 -- | Return the 'LlvmVar' part of a 'LMGlobal'
238 getGlobalVar :: LMGlobal -> LlvmVar
239 getGlobalVar (v, _) = v
240
241 -- | Return the 'LlvmLinkageType' for a 'LlvmVar'
242 getLink :: LlvmVar -> LlvmLinkageType
243 getLink (LMGlobalVar _ _ l _ _ _) = l
244 getLink _                         = Internal
245
246 -- | Add a pointer indirection to the supplied type. 'LMLabel' and 'LMVoid'
247 -- cannot be lifted.
248 pLift :: LlvmType -> LlvmType
249 pLift (LMLabel) = error "Labels are unliftable"
250 pLift (LMVoid)  = error "Voids are unliftable"
251 pLift x         = LMPointer x
252
253 -- | Lower a variable of 'LMPointer' type.
254 pVarLift :: LlvmVar -> LlvmVar
255 pVarLift (LMGlobalVar s t l x a c) = LMGlobalVar s (pLift t) l x a c
256 pVarLift (LMLocalVar  s t        ) = LMLocalVar  s (pLift t)
257 pVarLift (LMNLocalVar s t        ) = LMNLocalVar s (pLift t)
258 pVarLift (LMLitVar    _          ) = error $ "Can't lower a literal type!"
259
260 -- | Remove the pointer indirection of the supplied type. Only 'LMPointer'
261 -- constructors can be lowered.
262 pLower :: LlvmType -> LlvmType
263 pLower (LMPointer x) = x
264 pLower x  = error $ show x ++ " is a unlowerable type, need a pointer"
265
266 -- | Lower a variable of 'LMPointer' type.
267 pVarLower :: LlvmVar -> LlvmVar
268 pVarLower (LMGlobalVar s t l x a c) = LMGlobalVar s (pLower t) l x a c
269 pVarLower (LMLocalVar  s t        ) = LMLocalVar  s (pLower t)
270 pVarLower (LMNLocalVar s t        ) = LMNLocalVar s (pLower t)
271 pVarLower (LMLitVar    _          ) = error $ "Can't lower a literal type!"
272
273 -- | Test if the given 'LlvmType' is an integer
274 isInt :: LlvmType -> Bool
275 isInt (LMInt _) = True
276 isInt _         = False
277
278 -- | Test if the given 'LlvmType' is a floating point type
279 isFloat :: LlvmType -> Bool
280 isFloat LMFloat    = True
281 isFloat LMDouble   = True
282 isFloat LMFloat80  = True
283 isFloat LMFloat128 = True
284 isFloat _          = False
285
286 -- | Test if the given 'LlvmType' is an 'LMPointer' construct
287 isPointer :: LlvmType -> Bool
288 isPointer (LMPointer _) = True
289 isPointer _             = False
290
291 -- | Test if a 'LlvmVar' is global.
292 isGlobal :: LlvmVar -> Bool
293 isGlobal (LMGlobalVar _ _ _ _ _ _) = True
294 isGlobal _                         = False
295
296 -- | Width in bits of an 'LlvmType', returns 0 if not applicable
297 llvmWidthInBits :: LlvmType -> Int
298 llvmWidthInBits (LMInt n)       = n
299 llvmWidthInBits (LMFloat)       = 32
300 llvmWidthInBits (LMDouble)      = 64
301 llvmWidthInBits (LMFloat80)     = 80
302 llvmWidthInBits (LMFloat128)    = 128
303 -- Could return either a pointer width here or the width of what
304 -- it points to. We will go with the former for now.
305 llvmWidthInBits (LMPointer _)   = llvmWidthInBits llvmWord
306 llvmWidthInBits (LMArray _ _)   = llvmWidthInBits llvmWord
307 llvmWidthInBits LMLabel         = 0
308 llvmWidthInBits LMVoid          = 0
309 llvmWidthInBits (LMStruct tys)  = sum $ map llvmWidthInBits tys
310 llvmWidthInBits (LMFunction  _) = 0
311 llvmWidthInBits (LMAlias _ t)   = llvmWidthInBits t
312
313
314 -- -----------------------------------------------------------------------------
315 -- ** Shortcut for Common Types
316 --
317
318 i128, i64, i32, i16, i8, i1, i8Ptr :: LlvmType
319 i128  = LMInt 128
320 i64   = LMInt  64
321 i32   = LMInt  32
322 i16   = LMInt  16
323 i8    = LMInt   8
324 i1    = LMInt   1
325 i8Ptr = pLift i8
326
327 -- | The target architectures word size
328 llvmWord, llvmWordPtr :: LlvmType
329 llvmWord    = LMInt (wORD_SIZE * 8)
330 llvmWordPtr = pLift llvmWord
331
332 -- -----------------------------------------------------------------------------
333 -- * LLVM Function Types
334 --
335
336 -- | An LLVM Function
337 data LlvmFunctionDecl = LlvmFunctionDecl {
338         -- | Unique identifier of the function
339         decName       :: LMString,
340         -- | LinkageType of the function
341         funcLinkage   :: LlvmLinkageType,
342         -- | The calling convention of the function
343         funcCc        :: LlvmCallConvention,
344         -- | Type of the returned value
345         decReturnType :: LlvmType,
346         -- | Indicates if this function uses varargs
347         decVarargs    :: LlvmParameterListType,
348         -- | Parameter types and attributes
349         decParams     :: [LlvmParameter],
350         -- | Function align value, must be power of 2
351         funcAlign     :: LMAlign
352   }
353   deriving (Eq)
354
355 instance Show LlvmFunctionDecl where
356   show (LlvmFunctionDecl n l c r varg p a)
357     = let args = ((drop 1).concat) $ -- use drop since it can handle empty lists
358                   map (\(t,a) -> "," ++ show t ++ " " ++ spaceCat a) p
359           varg' = case varg of
360                         VarArgs | not (null args) -> ", ..."
361                                 | otherwise       -> "..."
362                         _otherwise                -> ""
363           align = case a of
364                        Just a' -> " align " ++ show a'
365                        Nothing -> ""
366       in show l ++ " " ++ show c ++ " " ++ show r ++ " @" ++ unpackFS n ++
367              "(" ++ args ++ varg' ++ ")" ++ align
368
369 type LlvmFunctionDecls = [LlvmFunctionDecl]
370
371 type LlvmParameter = (LlvmType, [LlvmParamAttr])
372
373 -- | LLVM Parameter Attributes.
374 --
375 -- Parameter attributes are used to communicate additional information about
376 -- the result or parameters of a function
377 data LlvmParamAttr
378   -- | This indicates to the code generator that the parameter or return value
379   -- should be zero-extended to a 32-bit value by the caller (for a parameter)
380   -- or the callee (for a return value).
381   = ZeroExt
382   -- | This indicates to the code generator that the parameter or return value
383   -- should be sign-extended to a 32-bit value by the caller (for a parameter)
384   -- or the callee (for a return value).
385   | SignExt
386   -- | This indicates that this parameter or return value should be treated in
387   -- a special target-dependent fashion during while emitting code for a
388   -- function call or return (usually, by putting it in a register as opposed
389   -- to memory).
390   | InReg
391   -- | This indicates that the pointer parameter should really be passed by
392   -- value to the function.
393   | ByVal
394   -- | This indicates that the pointer parameter specifies the address of a
395   -- structure that is the return value of the function in the source program.
396   | SRet
397   -- | This indicates that the pointer does not alias any global or any other
398   -- parameter.
399   | NoAlias
400   -- | This indicates that the callee does not make any copies of the pointer
401   -- that outlive the callee itself
402   | NoCapture
403   -- | This indicates that the pointer parameter can be excised using the
404   -- trampoline intrinsics.
405   | Nest
406   deriving (Eq)
407
408 instance Show LlvmParamAttr where
409   show ZeroExt   = "zeroext"
410   show SignExt   = "signext"
411   show InReg     = "inreg"
412   show ByVal     = "byval"
413   show SRet      = "sret"
414   show NoAlias   = "noalias"
415   show NoCapture = "nocapture"
416   show Nest      = "nest"
417
418 -- | Llvm Function Attributes.
419 --
420 -- Function attributes are set to communicate additional information about a
421 -- function. Function attributes are considered to be part of the function,
422 -- not of the function type, so functions with different parameter attributes
423 -- can have the same function type. Functions can have multiple attributes.
424 --
425 -- Descriptions taken from <http://llvm.org/docs/LangRef.html#fnattrs>
426 data LlvmFuncAttr
427   -- | This attribute indicates that the inliner should attempt to inline this
428   -- function into callers whenever possible, ignoring any active inlining
429   -- size threshold for this caller.
430   = AlwaysInline
431   -- | This attribute indicates that the source code contained a hint that
432   -- inlining this function is desirable (such as the \"inline\" keyword in
433   -- C/C++). It is just a hint; it imposes no requirements on the inliner.
434   | InlineHint
435   -- | This attribute indicates that the inliner should never inline this
436   -- function in any situation. This attribute may not be used together
437   -- with the alwaysinline attribute.
438   | NoInline
439   -- | This attribute suggests that optimization passes and code generator
440   -- passes make choices that keep the code size of this function low, and
441   -- otherwise do optimizations specifically to reduce code size.
442   | OptSize
443   -- | This function attribute indicates that the function never returns
444   -- normally. This produces undefined behavior at runtime if the function
445   -- ever does dynamically return.
446   | NoReturn
447   -- | This function attribute indicates that the function never returns with
448   -- an unwind or exceptional control flow. If the function does unwind, its
449   -- runtime behavior is undefined.
450   | NoUnwind
451   -- | This attribute indicates that the function computes its result (or
452   -- decides to unwind an exception) based strictly on its arguments, without
453   -- dereferencing any pointer arguments or otherwise accessing any mutable
454   -- state (e.g. memory, control registers, etc) visible to caller functions.
455   -- It does not write through any pointer arguments (including byval
456   -- arguments) and never changes any state visible to callers. This means
457   -- that it cannot unwind exceptions by calling the C++ exception throwing
458   -- methods, but could use the unwind instruction.
459   | ReadNone
460   -- | This attribute indicates that the function does not write through any
461   -- pointer arguments (including byval arguments) or otherwise modify any
462   -- state (e.g. memory, control registers, etc) visible to caller functions.
463   -- It may dereference pointer arguments and read state that may be set in
464   -- the caller. A readonly function always returns the same value (or unwinds
465   -- an exception identically) when called with the same set of arguments and
466   -- global state. It cannot unwind an exception by calling the C++ exception
467   -- throwing methods, but may use the unwind instruction.
468   | ReadOnly
469   -- | This attribute indicates that the function should emit a stack smashing
470   -- protector. It is in the form of a \"canary\"—a random value placed on the
471   -- stack before the local variables that's checked upon return from the
472   -- function to see if it has been overwritten. A heuristic is used to
473   -- determine if a function needs stack protectors or not.
474   --
475   -- If a function that has an ssp attribute is inlined into a function that
476   -- doesn't have an ssp attribute, then the resulting function will have an
477   -- ssp attribute.
478   | Ssp
479   -- | This attribute indicates that the function should always emit a stack
480   -- smashing protector. This overrides the ssp function attribute.
481   --
482   -- If a function that has an sspreq attribute is inlined into a function
483   -- that doesn't have an sspreq attribute or which has an ssp attribute,
484   -- then the resulting function will have an sspreq attribute.
485   | SspReq
486   -- | This attribute indicates that the code generator should not use a red
487   -- zone, even if the target-specific ABI normally permits it.
488   | NoRedZone
489   -- | This attributes disables implicit floating point instructions.
490   | NoImplicitFloat
491   -- | This attribute disables prologue / epilogue emission for the function.
492   -- This can have very system-specific consequences.
493   | Naked
494   deriving (Eq)
495
496 instance Show LlvmFuncAttr where
497   show AlwaysInline       = "alwaysinline"
498   show InlineHint         = "inlinehint"
499   show NoInline           = "noinline"
500   show OptSize            = "optsize"
501   show NoReturn           = "noreturn"
502   show NoUnwind           = "nounwind"
503   show ReadNone           = "readnon"
504   show ReadOnly           = "readonly"
505   show Ssp                = "ssp"
506   show SspReq             = "ssqreq"
507   show NoRedZone          = "noredzone"
508   show NoImplicitFloat    = "noimplicitfloat"
509   show Naked              = "naked"
510
511
512 -- | Different types to call a function.
513 data LlvmCallType
514   -- | Normal call, allocate a new stack frame.
515   = StdCall
516   -- | Tail call, perform the call in the current stack frame.
517   | TailCall
518   deriving (Eq,Show)
519
520 -- | Different calling conventions a function can use.
521 data LlvmCallConvention
522   -- | The C calling convention.
523   -- This calling convention (the default if no other calling convention is
524   -- specified) matches the target C calling conventions. This calling
525   -- convention supports varargs function calls and tolerates some mismatch in
526   -- the declared prototype and implemented declaration of the function (as
527   -- does normal C).
528   = CC_Ccc
529   -- | This calling convention attempts to make calls as fast as possible
530   -- (e.g. by passing things in registers). This calling convention allows
531   -- the target to use whatever tricks it wants to produce fast code for the
532   -- target, without having to conform to an externally specified ABI
533   -- (Application Binary Interface). Implementations of this convention should
534   -- allow arbitrary tail call optimization to be supported. This calling
535   -- convention does not support varargs and requires the prototype of al
536   -- callees to exactly match the prototype of the function definition.
537   | CC_Fastcc
538   -- | This calling convention attempts to make code in the caller as efficient
539   -- as possible under the assumption that the call is not commonly executed.
540   -- As such, these calls often preserve all registers so that the call does
541   -- not break any live ranges in the caller side. This calling convention
542   -- does not support varargs and requires the prototype of all callees to
543   -- exactly match the prototype of the function definition.
544   | CC_Coldcc
545   -- | Any calling convention may be specified by number, allowing
546   -- target-specific calling conventions to be used. Target specific calling
547   -- conventions start at 64.
548   | CC_Ncc Int
549   -- | X86 Specific 'StdCall' convention. LLVM includes a specific alias for it
550   -- rather than just using CC_Ncc.
551   | CC_X86_Stdcc
552   deriving (Eq)
553
554 instance Show LlvmCallConvention where
555   show CC_Ccc       = "ccc"
556   show CC_Fastcc    = "fastcc"
557   show CC_Coldcc    = "coldcc"
558   show (CC_Ncc i)   = "cc " ++ show i
559   show CC_X86_Stdcc = "x86_stdcallcc"
560
561
562 -- | Functions can have a fixed amount of parameters, or a variable amount.
563 data LlvmParameterListType
564   -- Fixed amount of arguments.
565   = FixedArgs
566   -- Variable amount of arguments.
567   | VarArgs
568   deriving (Eq,Show)
569
570
571 -- | Linkage type of a symbol.
572 --
573 -- The description of the constructors is copied from the Llvm Assembly Language
574 -- Reference Manual <http://www.llvm.org/docs/LangRef.html#linkage>, because
575 -- they correspond to the Llvm linkage types.
576 data LlvmLinkageType
577   -- | Global values with internal linkage are only directly accessible by
578   -- objects in the current module. In particular, linking code into a module
579   -- with an internal global value may cause the internal to be renamed as
580   -- necessary to avoid collisions. Because the symbol is internal to the
581   -- module, all references can be updated. This corresponds to the notion
582   -- of the @static@ keyword in C.
583   = Internal
584   -- | Globals with @linkonce@ linkage are merged with other globals of the
585   -- same name when linkage occurs. This is typically used to implement
586   -- inline functions, templates, or other code which must be generated
587   -- in each translation unit that uses it. Unreferenced linkonce globals are
588   -- allowed to be discarded.
589   | LinkOnce
590   -- | @weak@ linkage is exactly the same as linkonce linkage, except that
591   -- unreferenced weak globals may not be discarded. This is used for globals
592   -- that may be emitted in multiple translation units, but that are not
593   -- guaranteed to be emitted into every translation unit that uses them. One
594   -- example of this are common globals in C, such as @int X;@ at global
595   -- scope.
596   | Weak
597   -- | @appending@ linkage may only be applied to global variables of pointer
598   -- to array type. When two global variables with appending linkage are
599   -- linked together, the two global arrays are appended together. This is
600   -- the Llvm, typesafe, equivalent of having the system linker append
601   -- together @sections@ with identical names when .o files are linked.
602   | Appending
603   -- | The semantics of this linkage follow the ELF model: the symbol is weak
604   -- until linked, if not linked, the symbol becomes null instead of being an
605   -- undefined reference.
606   | ExternWeak
607   -- | The symbol participates in linkage and can be used to resolve external
608   --  symbol references.
609   | ExternallyVisible
610   -- | Alias for 'ExternallyVisible' but with explicit textual form in LLVM
611   --  assembly.
612   | External
613   deriving (Eq)
614
615 instance Show LlvmLinkageType where
616   show Internal          = "internal"
617   show LinkOnce          = "linkonce"
618   show Weak              = "weak"
619   show Appending         = "appending"
620   show ExternWeak        = "extern_weak"
621   -- ExternallyVisible does not have a textual representation, it is
622   -- the linkage type a function resolves to if no other is specified
623   -- in Llvm.
624   show ExternallyVisible = ""
625   show External          = "external"
626
627
628 -- -----------------------------------------------------------------------------
629 -- * LLVM Operations
630 --
631
632 -- | Llvm binary operators machine operations.
633 data LlvmMachOp
634   = LM_MO_Add  -- ^ add two integer, floating point or vector values.
635   | LM_MO_Sub  -- ^ subtract two ...
636   | LM_MO_Mul  -- ^ multiply ..
637   | LM_MO_UDiv -- ^ unsigned integer or vector division.
638   | LM_MO_SDiv -- ^ signed integer ..
639   | LM_MO_FDiv -- ^ floating point ..
640   | LM_MO_URem -- ^ unsigned integer or vector remainder (mod)
641   | LM_MO_SRem -- ^ signed ...
642   | LM_MO_FRem -- ^ floating point ...
643
644   -- | Left shift
645   | LM_MO_Shl
646   -- | Logical shift right
647   -- Shift right, filling with zero
648   | LM_MO_LShr
649   -- | Arithmetic shift right
650   -- The most significant bits of the result will be equal to the sign bit of
651   -- the left operand.
652   | LM_MO_AShr
653
654   | LM_MO_And -- ^ AND bitwise logical operation.
655   | LM_MO_Or  -- ^ OR bitwise logical operation.
656   | LM_MO_Xor -- ^ XOR bitwise logical operation.
657   deriving (Eq)
658
659 instance Show LlvmMachOp where
660   show LM_MO_Add  = "add"
661   show LM_MO_Sub  = "sub"
662   show LM_MO_Mul  = "mul"
663   show LM_MO_UDiv = "udiv"
664   show LM_MO_SDiv = "sdiv"
665   show LM_MO_FDiv = "fdiv"
666   show LM_MO_URem = "urem"
667   show LM_MO_SRem = "srem"
668   show LM_MO_FRem = "frem"
669   show LM_MO_Shl  = "shl"
670   show LM_MO_LShr = "lshr"
671   show LM_MO_AShr = "ashr"
672   show LM_MO_And  = "and"
673   show LM_MO_Or   = "or"
674   show LM_MO_Xor  = "xor"
675
676
677 -- | Llvm compare operations.
678 data LlvmCmpOp
679   = LM_CMP_Eq  -- ^ Equal (Signed and Unsigned)
680   | LM_CMP_Ne  -- ^ Not equal (Signed and Unsigned)
681   | LM_CMP_Ugt -- ^ Unsigned greater than
682   | LM_CMP_Uge -- ^ Unsigned greater than or equal
683   | LM_CMP_Ult -- ^ Unsigned less than
684   | LM_CMP_Ule -- ^ Unsigned less than or equal
685   | LM_CMP_Sgt -- ^ Signed greater than
686   | LM_CMP_Sge -- ^ Signed greater than or equal
687   | LM_CMP_Slt -- ^ Signed less than
688   | LM_CMP_Sle -- ^ Signed less than or equal
689
690   -- Float comparisons. GHC uses a mix of ordered and unordered float
691   -- comparisons.
692   | LM_CMP_Feq -- ^ Float equal
693   | LM_CMP_Fne -- ^ Float not equal
694   | LM_CMP_Fgt -- ^ Float greater than
695   | LM_CMP_Fge -- ^ Float greater than or equal
696   | LM_CMP_Flt -- ^ Float less than
697   | LM_CMP_Fle -- ^ Float less than or equal
698   deriving (Eq)
699
700 instance Show LlvmCmpOp where
701   show LM_CMP_Eq  = "eq"
702   show LM_CMP_Ne  = "ne"
703   show LM_CMP_Ugt = "ugt"
704   show LM_CMP_Uge = "uge"
705   show LM_CMP_Ult = "ult"
706   show LM_CMP_Ule = "ule"
707   show LM_CMP_Sgt = "sgt"
708   show LM_CMP_Sge = "sge"
709   show LM_CMP_Slt = "slt"
710   show LM_CMP_Sle = "sle"
711   show LM_CMP_Feq = "oeq"
712   show LM_CMP_Fne = "une"
713   show LM_CMP_Fgt = "ogt"
714   show LM_CMP_Fge = "oge"
715   show LM_CMP_Flt = "olt"
716   show LM_CMP_Fle = "ole"
717
718
719 -- | Llvm cast operations.
720 data LlvmCastOp
721   = LM_Trunc    -- ^ Integer truncate
722   | LM_Zext     -- ^ Integer extend (zero fill)
723   | LM_Sext     -- ^ Integer extend (sign fill)
724   | LM_Fptrunc  -- ^ Float truncate
725   | LM_Fpext    -- ^ Float extend
726   | LM_Fptoui   -- ^ Float to unsigned Integer
727   | LM_Fptosi   -- ^ Float to signed Integer
728   | LM_Uitofp   -- ^ Unsigned Integer to Float
729   | LM_Sitofp   -- ^ Signed Int to Float
730   | LM_Ptrtoint -- ^ Pointer to Integer
731   | LM_Inttoptr -- ^ Integer to Pointer
732   | LM_Bitcast  -- ^ Cast between types where no bit manipulation is needed
733   deriving (Eq)
734
735 instance Show LlvmCastOp where
736   show LM_Trunc    = "trunc"
737   show LM_Zext     = "zext"
738   show LM_Sext     = "sext"
739   show LM_Fptrunc  = "fptrunc"
740   show LM_Fpext    = "fpext"
741   show LM_Fptoui   = "fptoui"
742   show LM_Fptosi   = "fptosi"
743   show LM_Uitofp   = "uitofp"
744   show LM_Sitofp   = "sitofp"
745   show LM_Ptrtoint = "ptrtoint"
746   show LM_Inttoptr = "inttoptr"
747   show LM_Bitcast  = "bitcast"
748
749
750 -- -----------------------------------------------------------------------------
751 -- * Floating point conversion
752 --
753
754 -- | Convert a Haskell Double to an LLVM hex encoded floating point form. In
755 -- Llvm float literals can be printed in a big-endian hexadecimal format,
756 -- regardless of underlying architecture.
757 dToStr :: Double -> String
758 dToStr d
759   = let bs     = doubleToBytes d
760         hex d' = case showHex d' "" of
761                      []    -> error "dToStr: too few hex digits for float"
762                      [x]   -> ['0',x]
763                      [x,y] -> [x,y]
764                      _     -> error "dToStr: too many hex digits for float"
765
766         str  = map toUpper $ concat . fixEndian . (map hex) $ bs
767     in  "0x" ++ str
768
769 -- | Convert a Haskell Float to an LLVM hex encoded floating point form.
770 -- LLVM uses the same encoding for both floats and doubles (16 digit hex
771 -- string) but floats must have the last half all zeroes so it can fit into
772 -- a float size type.
773 {-# NOINLINE fToStr #-}
774 fToStr :: Float -> String
775 fToStr = (dToStr . realToFrac)
776
777 -- | Reverse or leave byte data alone to fix endianness on this target.
778 fixEndian :: [a] -> [a]
779 #ifdef WORDS_BIGENDIAN
780 fixEndian = id
781 #else
782 fixEndian = reverse
783 #endif
784