aboutsummaryrefslogtreecommitdiffhomepage
path: root/src-backend/include/csbe.h
blob: 8b10345f9f6de090a9520f203624250262e35fcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919

/*

  csbe.h -- Compiler backend for cslul

  Copyright © 2022-2024 Samuel Lidén Borell <samuel@kodafritt.se>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

#ifndef CSBE_H
#define CSBE_H

#include <stddef.h>
#include <stdint.h>

#define CSBE_API_VERSION_0 0

typedef uint8_t CsbeUint8;
typedef uint16_t CsbeUint16;
typedef uint32_t CsbeUint32;
typedef uint64_t CsbeUint64;
typedef int8_t CsbeInt8;
typedef int16_t CsbeInt16;
typedef int32_t CsbeInt32;
typedef int64_t CsbeInt64;

struct Csbe;
struct CsbeLibrary;
struct CsbeSymVer;

/**
 * Type of the user-supplied allocation function.
 *
 * \param userctx  The userctx parameter that was passed to csbe_config_new.
 * \param size     Size of allocation in bytes.
 * \param align    Alignment requirement. Never larger than the largest
 *                 pointer type, so a normal malloc will always satisfy
 *                 this requirement.
 * \return  Pointer to the allocated data.
 */
typedef void *(CsbeAllocFunc)(void *userctx, size_t size, size_t align);

/**
 * Type of the optional user-supplied buffer allocation function to
 * csbe_output().
 *
 * \param userparam  Custom data.
 * \param size       Allocation size in bytes.
 * \return  Pointer the buffer (does not have to be aligned),
 *          or NULL on error.
 */
typedef void *(CsbeBufferAllocFunc)(void *userparam, size_t size);

struct CsbeFuncPtrs {
    /** Set to a function that tracks memory allocation (e.g. a arena
        allocator, or a garbage collecting allocator).

        If set to NULL, then memory is allocated with malloc and leaked,
        which might be acceptable for CLI applications. */
    CsbeAllocFunc *fptr_alloc;
    /* csbe_config_new must be updated if new fields are to be added */
};

enum CsbeErr {
    CSBEE_OK = 0, /**< No error. */
    CSBEE_OUT_OF_MEM, /**< Out of memory */
    CSBEE_INVALID_PARAM, /**< Invalid parameter to a function */
    CSBEE_TYPE_TOO_LARGE, /**< Too many fields (max 4096) or elems (2^31-1) */
    CSBEE_TOO_MANY_ITEMS, /**< Too many items, e.g. EBB's or func params */
    CSBEE_UNKNOWN_ARCH, /**< Unknown CPU or OS type. */
    CSBEE_ARCH_NOT_SUPPORTED, /**< E.g. unsupported CPU/OS for output format */
    CSBEE_UNSUPPORTED_FEATURE_PARAM, /**< CPU/OS does't support this feature */
    CSBEE_INTERNAL_ERROR /**< Internal error (i.e. a bug) */
};

/* FIXME this overlaps with CsbeOutputFormat! */
enum CsbeModuleType {
    CSBEMT_EXEC,        /**< Output is an executable file */
    CSBEMT_DYNLIB,      /**< Output is a dynamic library (.so or .dll) */
    CSBEMT_STATICLIB,   /**< Output is a static library (.a or .lib) */
    CSBEMT_DYNSTATICLIB,/**< Output is a static library for use in
                             dynamic libraries (somewhat uncommon case) */
    CSBEMT_STATICOBJ,   /**< Output is an object file for use in
                             executables or regular static libraries. */
    CSBEMT_DYNOBJ       /**< Output is an object file for use in
                             dynamic libraries */
};

enum CsbeSymverExportMode {
    /** Export versioned symbols as versioned if the target platform
        supports it. Symbol versioning is possible on ELF/SysV platforms */
    CSBESEM_DEFAULT,
    /** Disable symbol versioning for exported symbols. All current
        platforms support unversioned symbols. This option is useful if
        the language performs versioning using some other means, for
        example using "marker symbols". */
    CSBESEM_AVOID
};

enum CsbeOutputStatus {
    CSBEOS_ERROR = -1,
    CSBEOS_FINISHED = 0,
    CSBEOS_MORE = 1
};

enum CsbeTypeKind {
    CSBET_BOOL,
    CSBET_INT,
    CSBET_UINT,
    CSBET_LONG,
    CSBET_ULONG,
    CSBET_I8,
    CSBET_U8,
    CSBET_I16,
    CSBET_U16,
    CSBET_I32,
    CSBET_U32,
    CSBET_I64,
    CSBET_U64,
    CSBET_F32,
    CSBET_F64,
    CSBET_SSIZE,
    CSBET_USIZE,
    CSBET_DPTR,
    CSBET_DPTR_ALIASED,
    CSBET_DPTR_THREADED,
    CSBET_FPTR
};
#define NUM_TYPEKINDS (CSBET_FPTR+1)

enum CsbePackMode {
    /** C struct packing. Fields are always added last with necessary
        alignment padding between fields. */
    CSBEPM_CPACK,
    /** Union packing. All fields are placed at offset 0 */
    CSBEPM_UNION,
    /* Optimized stable struct packing. Fields are added last, unless they
        fit in an alignment hole. Smaller alignment holes are prioritized
        before larger ones, and if equally sized, ones with lower address
        are prioritized over ones with higher address. */
    /*CSBEPM_OPTSTABLEPACK,*/ /* TODO not yet implemented */
    /** Any struct packing. Can be optimized freely by the backend */
    CSBEPM_ANYPACK
};

/* XXX replace quals with a flag to operations? */
/*enum CsbeTypeQuals {
    CSBETQ_VAR      = 0x01,
    CSBETQ_ALIASED  = 0x02,
    CSBETQ_THREADED = 0x04,
};*/

enum CsbeAbi {
    CSBEABI_C_NORMAL,
    CSBEABI_ANYCALL
    /*CSBEABI_SLUL_NORMAL,
    CSBEABI_SLUL_TIGHTCALL*/ /* uses less regs */
};
#define CSBEFD_NORETURN  0x1 /**< Function never returns */
#define CSBEFD_OBJGLOBAL 0x2 /**< Available to other object files */
/**
 * Main function. This should have the following definition:
 *
 *    int main(int arg1, void *arg2)
 *
 * On systems that use a system-wide C library (Linux, BSD, etc.)
 * the parameters work as follows:
 *
 *      int arg1        Argument count, >= 0
 *      char **arg2     Arguments, != NULL
 *
 * On Windows, no argument information is passed at startup,
 * and the parameters are simply NULL:
 *
 *      int arg1        Reserved, always -1
 *      void *arg2      Reserved, always NULL
 *
 * Note that the main function is NOT the entry point. The entry point
 * consists of some system-specific glue code, that at least aligns the
 * stack before it calls the main function.
 */
#define CSBEFD_MAIN      0x4

#define CSBEDD_EXTERNAL    0x1 /**< External definition */
#define CSBEDD_OBJGLOBAL   0x2 /**< Available to other object files */
/*#define CSBEDD_MODIFIABLE  0x4 *< The data can be modified (TODO implement) */
#define CSBEDD_NON_UNIQUE  0x8 /**< Does NOT need a unique address */

enum CsbeCallMode {
    CSBECM_NORMAL,
    CSBECM_TAILCALL /* XXX remove, and auto-detect instead? */
};

enum CsbeBranchType {
    CSBEBT_Z,
    CSBEBT_NZ,
    CSBEBT_LZ,
    CSBEBT_GEZ,
    CSBEBT_GZ,
    CSBEBT_LEZ
};

enum CsbeBranchBalance {
    CSBEBB_UNKNOWN,
    CSBEBB_EQUAL,
    CSBEBB_NEVER,   /**< For very unlikely events such as errors */
    CSBEBB_ALWAYS,  /**< For very likely events, such as no error */
    CSBEBB_SOMEWHAT_UNLIKELY,
    CSBEBB_SOMEWHAT_LIKELY
};

enum CsbeSelectBalance {
    CSBESB_UNKNOWN,
    CSBESB_EQUAL,
    CSBESB_1_ONLY, /**< Only value 1 can be selected in normal conditions */
    CSBESB_2_ONLY,
    CSBESB_1_MAINLY,
    CSBESB_2_MAINLY
};

enum CsbeSizeofKind {
    CSBES_SIZEOF_ALIGNED,
    CSBES_SIZEOF_INNER,
    CSBES_ALIGNOF
};

#define CSBE_OPDEF0(op) op,
#define CSBE_OPDEF1(op,a) op,
#define CSBE_OPDEF2(op,a,b) op,
#define CSBE_OPDEF3(op,a,b,c) op,
#define CSBE_OPDEF4(op,a,b,c,d) op,
#define CSBE_OPDEF5(op,a,b,c,d,e) op,
#define CSBE_OPDEF_LAST CSBEO_LAST
enum CsbeOp {
#    include "csbe_ops.h"
};

enum CsbeSymbolType {
    /** Imports/exports the last function definition */
    CSBEST_LAST_FUNC,
    /** Imports/exports the last data definition */
    CSBEST_LAST_DATA,
    /** Imports/exports a "marker" (a symbol that has no real function body,
        but must be resolvable at load time). These can be used to require
        a particular version of a library, or a particular compile-time
        optional feature of a library, or similar. */
    CSBEST_MARKER
};

/* Values that are guaranteed to never be valid ID's.
   Can be used as sentinel/none values. */
#define CSBE_INVALID_TYPEDEF ((unsigned)-1)
#define CSBE_INVALID_FUNCDEF ((unsigned)-1)
#define CSBE_INVALID_DATADEF ((unsigned)-1)
#define CSBE_INVALID_VARIABLE ((unsigned)-1)
#define CSBE_INVALID_EBB ((unsigned)-1)

/* =======================================================================
   ||||||||||||||||||||||||||  Initialization  |||||||||||||||||||||||||||
   =======================================================================

   All CSBE operations work on a CSBE context object (struct Csbe *). The
   context object is created from a configuration object, which in turn
   decides which CPU architectures to target. Usually, at least one CPU
   architecture should be added using csbe_config_add_arch.

*/

/**
 * Creates a new CSBE context with the given configuration
 *
 * If you wish to be able to free allocated memory, you must do so by passing
 * a custom allocation function in funcptrs. For example an arena allocator
 * a garbage collecting allocator. CSBE does not free (or track) memory by
 * itself.
 *
 * \param api_version The version of CSBE API that the caller will use.
 * \param funcptrs    Optionally specifies a custom allocator. May be NULL
 * \param userctx     "User context" parameter that is passed to the
 *                    allocator and other callbacks
 * \return CsbeConfig or NULL on error
 */
struct CsbeConfig *csbe_config_new(int api_version,
                                   const struct CsbeFuncPtrs *funcptrs,
                                   void *userctx);

/* TODO add more CPU architectures */
enum CsbeCpu {
    CSBEC_IR_DUMP,
    CSBEC_I386,
    CSBEC_X86_64,
/*    CSBEC_ARM,*/
    CSBEC_AARCH64/*,
    CSBEC_MIPS,
    CSBEC_OR1K,
    CSBEC_PPC64,
    CSBEC_RV32,
    CSBEC_RV64,
    CSBEC_SH4*/
};

enum CsbeEndianness {
    CSBEEN_LITTLE_ENDIAN,
    CSBEEN_BIG_ENDIAN
};

enum CsbeOsType {
    CSBEOS_LINUX_GLIBC,
    CSBEOS_LINUX_MUSL,
    /* TODO BSDs, MacOS etc. */
    CSBEOS_WINDOWS
};
#define CSBEOS_NUM_OSTYPES (CSBEOS_WINDOWS+1)

enum CsbeOutputFormat {
    CSBEOF_RAW,         /**< Raw machine code. Also used when dumping IR */
    CSBEOF_ELF_EXE,     /**< ELF Position Independent Executable */
    CSBEOF_ELF_DYNLIB,  /**< ELF dynamic library (.so) */
    CSBEOF_ELF_OBJ,     /**< ELF object file (.o) */
/*    CSBEOF_ELF_STATLIB,
    CSBEOF_PE_EXE
    CSBEOF_PE_DLL*/
    CSBEOF_PE_OBJ
/*    CSBEOF_PE_STATLIB*/
};
#define CSBEOS_NUM_OUTFORMATS (CSBEOF_PE_OBJ+1)


#define CSBEF_COMMON_HARDFLOAT  -1

/**
 * Adds the given target architecture.
 *
 * \param cfg           CSBE configuration
 * \param cpu           Architecture, e.g. CSBEC_X86_64
 * \param endianness    Endianness, CSBEEN_LITTLE_ENDIAN or CSBEEN_BIG_ENDIAN
 * \param ostype        Operating system type (CSBEOS_SYSV or CSEBOS_WINDOWS)
 * \param outformat     File format of output file (CSBEOF_*)
 * \param elf_interp    Program interpeter (ld.so) path. Only for ELF format.
 * \return CSBEE_OK if supported, or an error code if not.
 */
enum CsbeErr csbe_config_add_arch(struct CsbeConfig *cfg, enum CsbeCpu cpu,
                                  enum CsbeEndianness endianness,
                                  enum CsbeOsType ostype,
                                  enum CsbeOutputFormat outformat);

/**
 * Checks whether an architecture feature can be enabled/disabled
 * for the last added architecture.
 *
 * \param cfg       CSBE configuration
 * \param feature   Architecture specific feature, CSBEF_*
 * \param state     Check if the feature can be: 1=enabled, 0=disabled
 * \return 1 if the given state is supported, 0 if not.
 */
int csbe_config_arch_has_feature_state(struct CsbeConfig *cfg,
                                       int feature, int state);

/**
 * Enables/disables an architecture feature for the last added architecture.
 *
 * \param cfg       CSBE configuration
 * \param feature   Architecture specific feature, CSBEF_*
 * \param state     1=enable, 0=disable
 * \return CSBEE_OK if feature is supported, or an error code if not.
 */
enum CsbeErr csbe_config_arch_feature(struct CsbeConfig *cfg,
                                      int feature, int state);

void csbe_config_set_moduletype(struct CsbeConfig *cfg,
                                enum CsbeModuleType modtype);

void csbe_config_set_symver_export(struct CsbeConfig *cfg,
                                   enum CsbeSymverExportMode mode);

/**
 * Creates a new CSBE context with the given configuration
 *
 * There is no csbe_free function. You must track the allocations yourself
 * (e.g. using an arena allocator or garbage collector) by passing a custom
 * allocation function in the CsbeFuncPtrs.
 */
struct Csbe *csbe_new(const struct CsbeConfig *cfg);

/** Checks if there is an error */
enum CsbeErr csbe_get_error(const struct Csbe *csbe);

/**
 * Sets the name of the input being compiled. This should be the source
 * filename when there is a single file per compilation unit. The value
 * is used in the FILE symbol in ELF object files.
 *
 * \param csbe  CSBE context.
 * \param name  Name. Do not free or modify while the CSBE context is in use.
 */
void csbe_set_input_name(struct Csbe *csbe, const char *name);

/* =======================================================================
   |||||||||||||||||||||||||||||||  Types  |||||||||||||||||||||||||||||||
   =======================================================================

   Each type fills one slot (nested types also fill one, but can contain
   multiple slots). Typedefs, global data definitions and variable
   definitions all have one slot for the type. Nested types such are
   function types and struct types are special:

   Function definitions instead have one slot for the return type and zero
   or more slots for the parameter types.

   Structs/unions have zero or more slots: One slot per field.
*/

/** Fills the next slot with a void type. Only applicable to function
    returns */
void csbe_type_void(struct Csbe *csbe);

/** Fills the next slot with a simple type such as int, bool or a pointer */
void csbe_type_simple(struct Csbe *csbe, enum CsbeTypeKind kind);

/** Fills the next slot with a "named type", i.e. a reference to a typedef */
enum CsbeErr csbe_type_named(struct Csbe *csbe, unsigned typedef_id);

/** Fills the next slot with an array. Multidimensional array types
    are automatically merged into a single array type, by multiplying
    the lengths. The element type is defined by the following slot,
    which can be any type (except void). */
enum CsbeErr csbe_type_array(struct Csbe *csbe, unsigned array_length);

/** Fills the next slot with a struct type. csbe_type_struct_done must be
    called after the last slot (=field) has been filled (=added). */
enum CsbeErr csbe_type_struct_start(struct Csbe *csbe, int num_fields,
                                    enum CsbePackMode packmode);
enum CsbeErr csbe_type_struct_end(struct Csbe *csbe);

/** Multiplies two array lengths, storing the result in prod_out.
    An error is returned if the array is larger than supported, or if
    overflow occurs. */
enum CsbeErr csbe_multiply_arraylengths(struct Csbe *csbe, unsigned *prod_out,
                                        unsigned l1, unsigned l2);

/* =======================================================================
   ||||||||||||||||||||||||  Imports and Exports  ||||||||||||||||||||||||
   ======================================================================= */
/**
 * Adds a library import.
 *
 * Note: The string is NOT copied. It must NOT be modified or free'd
 * until after the last CSBE call using the same struct Csbe.
 *
 * \param csbe       CSBE context
 * \param libname    Name of library, without "lib", ".so", ".dll", etc.
 * \param libnamelen Length of libname
 * \return Opaque CsbeLibrary object, or NULL on error.
 */
struct CsbeLibrary *csbe_add_libimport(struct Csbe *csbe,
                                       const char *libname,
                                       unsigned libnamelen);
/**
 * Defines a symbol version. The symbol versions MUST be defined in
 * ascending order.
 *
 * Note: The strings are NOT copied. It must NOT be modified or free'd
 * until after the last CSBE call using the same struct Csbe.
 *
 * \param csbe          CSBE context
 * \param lib           Library, or NULL for export.
 * \param verprefix     Version prefix, typically the module name in uppercase
 * \param verprefixlen  Length of verprefix
 * \param vername       Version
 * \param vernamelen    Length of vername
 * \return Error code, or CSBEE_OK if successful.
 */
struct CsbeSymVer *csbe_define_symver(struct Csbe *csbe,
                                      struct CsbeLibrary *lib,
                                      const char *verprefix,
                                      unsigned verprefixlen,
                                      const char *vername,
                                      unsigned vernamelen);
/**
 * Marks the last declaration as an exported declaration.
 *
 * Note: The strings are NOT copied. It must NOT be modified or free'd
 * until after the last CSBE call using the same struct Csbe.
 */
enum CsbeErr csbe_export_decl(struct Csbe *csbe, enum CsbeSymbolType symtype,
                              struct CsbeSymVer *symver,
                              const char *name, unsigned namelen);

/**
 * Marks the last declaration as an exported declaration.
 *
 * Note: The strings are NOT copied. It must NOT be modified or free'd
 * until after the last CSBE call using the same struct Csbe.
 */
enum CsbeErr csbe_import_decl(struct Csbe *csbe, enum CsbeSymbolType symtype,
                              struct CsbeLibrary *lib,
                              struct CsbeSymVer *symver,
                              const char *name, unsigned namelen);

/* =======================================================================
   |||||||||||||||||||||||  Top-level Declarations  ||||||||||||||||||||||
   ======================================================================= */
/**
 * Sets the number of typedefs. This allocates all typedefs, and makes it
 * possible to referencecs typedefs by ID (which is necessary when
 * creating mutually refential or self-referential definitions).
 *
 * \param csbe      CSBE context.
 * \param count     Number of typedefs (= maximum ID + 1)
 * \return  CSBEE_OK if successful, or CSBEE_OUT_OF_MEM if out of memory.
 */
enum CsbeErr csbe_set_num_typedefs(struct Csbe *csbe, unsigned count);
enum CsbeErr csbe_set_num_datadefs(struct Csbe *csbe, unsigned count);
enum CsbeErr csbe_set_num_funcdefs(struct Csbe *csbe, unsigned count);

void csbe_typedef_start(struct Csbe *csbe, unsigned id);
void csbe_typedef_end(struct Csbe *csbe);

/**
 * Starts a function declaration.
 *
 * Use csbe_type_* to add the function type type (can be void).
 * and then once for each parameter, from left to right.
 *
 * \param csbe          CSBE context.
 * \param id            ID of function declaration.
 * \param num_params    Number of parameters (excluding return type).
 * \param abi           Calling convention, CSBEABI_*
 * \param flags         Bitmask of CSBEFD_* flags.
 * \return  CSBEE_OK if successful, or an error code on error.
 */
enum CsbeErr csbe_funcdef_start(struct Csbe *csbe, unsigned id,
                                int num_params,
                                enum CsbeAbi abi, unsigned flags);
/**
 * Sets the name of a function. This will be added in the symbol table
 * (but it will be a local symbol, unless it is explicitly exported).
 *
 * \param csbe  CSBE context.
 * \param name  Name of function. The pointer is stored in the CSBE context.
 * \param len   Length of name.
 */
void csbe_funcdef_set_name(struct Csbe *csbe, const char *name, size_t len);
void csbe_funcdef_end(struct Csbe *csbe);

/**
 * Starts a data declaration.
 *
 * CSBE supports only non-pointers and constants only, but structs and
 * arrays are supported (if they don't contain pointers).
 *
 * After calling csbe_datadef_start, please call:
 * 1. csbe_type_* to define the type.
 *
 * And if there is an initial value:
 * 1. csbe_datadef_initval_start
 * 2. csbe_datadef_value_* to add value(s)
 * 3. csbe_datadef_initval_end.
 * For unions, the initial value applies to the first member.
 *
 * For external data, please include the flag CSBEDD_EXTERNAL
 * (and don't add any initial value).
 *
 * \param csbe   CSBE context.
 * \param id     ID of data declaration.
 * \param flags  CSBEDD_* flags.
 */
void csbe_datadef_start(struct Csbe *csbe, unsigned id, unsigned flags);

/**
 * Sets the name of a datadef. This will be added in the symbol table
 * (but it will be a local symbol, unless it is explicitly exported).
 *
 * \param csbe  CSBE context.
 * \param name  Name of datadef. The pointer is stored in the CSBE context.
 * \param len   Length of name.
 */
void csbe_datadef_set_name(struct Csbe *csbe, const char *name, size_t len);
enum CsbeErr csbe_datadef_initval_start(struct Csbe *csbe);
/** Adds a scalar value in an initial value. */
void csbe_datadef_value_int(struct Csbe *csbe, CsbeUint64 value);
/** Adds an array of int8/uint8/boolean in an initial value.
    The array pointer will be stored, so don't free it (or modify the
    contents) while the CSBE context is still in use. */
void csbe_datadef_value_bytearray(struct Csbe *csbe,
                                  const unsigned char *values,
                                  unsigned array_length);
/** Adds an array of int16 or greater in an initial value.
    The array pointer will be stored, so don't free it while
    the CSBE context is still in use. */
void csbe_datadef_value_intarray(struct Csbe *csbe,
                                 const CsbeUint64 *values,
                                 unsigned array_length);
void csbe_datadef_initval_end(struct Csbe *csbe);
void csbe_datadef_end(struct Csbe *csbe);

/**
 * Must be called after the definitions of types and functions are done,
 * and before any function bodies are added.
 *
 * Data definitions can still be added even after csbe_defs_done has been
 * called, in order to simplify generation of literals (e.g. inline string
 * constants).
 */
enum CsbeErr csbe_defs_done(struct Csbe *csbe);

/* =======================================================================
   ||||||||||||||||||||||||||  Function Bodies  ||||||||||||||||||||||||||
   ======================================================================= */

#if 0
/* TODO */
/** Function bodies can be generated in parallel (except inlined functions).
    This functions creates thread-safe "sub contexts" for processing function
    bodies */
struct Csbe *csbe_subctx_new(struct Csbe *csbe,
                             CsbeAllocFunc *fptr_alloc,
                             void *userctx);
/** Merges a subctx into a main ctx */
enum CsbeErr csbe_subctx_merge(struct Csbe *csbe, struct Csbe *subctx);
#endif

/**
 * Adds a function body to a function declaration.
 *
 * Optionally, all temporary allocations, that can be discarded after
 * the code for the function has been generated, can be diverted to a
 * separate allocator.
 *
 * \param func_id     ID of function declaration.
 * \param temp_alloc  Allocator of temporary data. NULL to use same allocator.
 * \param userctx     Parameter to allocator.
 * \param num_ebb     Number of bblocks (EBB = Extended Basic Block)
 * \param num_vars    Number of variable definitions
 *                    (including parameters and temporaries)
 * \return CSBEE_OK if successful, or an error code if not.
 */
enum CsbeErr csbe_funcbody_start(struct Csbe *csbe, unsigned func_id,
                                 CsbeAllocFunc *temp_alloc, void *userctx,
                                 unsigned num_ebb, unsigned num_vars);
enum CsbeErr csbe_funcbody_end(struct Csbe *csbe);

/* * * * * Variable definitions in functions. * * * * *
   Variables must be defined before being used.       */
#define CSBEVD_SIMPLE       0x0
#define CSBEVD_MULTI_READ   0x1 /* TODO get rid of this? */
#define CSBEVD_MULTI_WRITE  0x2 /* TODO get rid of this? */
#define CSBE_VARLANE_NONE 0

/**
 * Defines a parameter in a function. All parameters must be defined,
 * and in order.
 *
 * The parameters must be defined before any other variables.
 *
 * See csbe_funcbody_vardef_start() for details.
 */
void csbe_funcbody_paramdef(struct Csbe *csbe, unsigned flags,
                            unsigned var_id);

/**
 * Defines a variable in a function. The storage location is automatically
 * decided (stack, register, etc.).
 *
 * Note that temporaries and function parameters must be defined, in
 * addition to local variables. Function parameters can be defined
 * automatically (based on the type in the function declaration) using
 * csbe_funcbody_param()
 *
 * \param csbe  CSBE context
 * \param flags Bitwise OR of CSBEVD_* flags
 * \param var_id    Index of variable
 * \param var_lane  Variables that will never be used at the same time can
 *                  be placed in the same "lane". This information is used
 *                  for register allocation. This is a 1-based index or
 *                  CSBE_VARLANE_NONE.  TODO perhaps remove this and only
 *                  support automatic register allocation?
 *                  FIXME should placing different types in the same varlane be allowed or not?
 *                        - for temporaries, it makes things easier if it is allowed.
 *                        - if disallowed: need to track which varlanes are non-overlapping.
 */
void csbe_funcbody_vardef_start(struct Csbe *csbe, unsigned flags,
                                unsigned var_id, unsigned var_lane);
void csbe_funcbody_vardef_end(struct Csbe *csbe);

/* * * * * Extended Basic Block and code * * * * */
/**
 * Sets the basic block to jump to when a "trap" occurs. For example, if
 * an out-of-bounds error happens in any of the _TRAP operations.
 *
 * Must be called before calling csbe_ebb_start.
 *
 * \param csbe      CSBE context
 * \param trap_ebb  ID of basic block to jump to on error.
 */
void csbe_funcbody_set_trap_ebb(struct Csbe *csbe, unsigned trap_ebb);

/**
 * Marks the start of a basic block. CSBE uses "extended basic blocks",
 * which can outbound jumps/calls at any location, not just at the end.
 *
 * \param csbe     CSBE context.
 * \param ebb_id   ID of basic block.
 * \param flags    Bitwise OR of CSBEEF_* flags.
 * \return  CSBEE_OK if successful, or an error code if not.
 */
enum CsbeErr csbe_ebb_start(struct Csbe *csbe, unsigned ebb_id, unsigned flags);

#define CSBEEF_DEFAULT 0
/** Basic block is unlikely to be reached. It could be placed "far away"
    or could be optimized for size, for example. */
#define CSBEEF_UNLIKELY 0x1
/** The previously started EBB "flows into" this EBB. This will cause
    an implicit jump to be inserted if the EBB does not come directly
    after the previous one. */
#define CSBEEF_FLOWINTO 0x2

/**
 * If the EBB is the last one in the source language, but not the highest
 * numbered EBB in CSBE, then this function can be used to tell CSBE to
 * add a RETURN_VOID operation if the function is a void function.
 *
 * \param csbe  CSBE context
 * \return  CSBEE_OK if successful, or CSBEE_OUT_OF_MEM if out of memory.
 */
enum CsbeErr csbe_ebb_implicit_return(struct Csbe *csbe);

/* =======================================================================
   ||||||||||||||||||||||||||||  Operations  |||||||||||||||||||||||||||||
   ======================================================================= */
/**
 * Marks the beginning of an operation inside a bblock.
 * Operands should be set with csbe_operand_*, and then csbe_op_end()
 * should be called. The operands depend on the operations; see csbe_ops.h
 *
 * \param csbe  CSBE context
 * \param op    Operation, a CSBEO_* constant
 * \return  CSBEE_OK if successful, or CSBEE_OUT_OF_MEM if out of memory.
 */
enum CsbeErr csbe_op_start(struct Csbe *csbe, enum CsbeOp op);
void csbe_op_end(struct Csbe *csbe);

/**
 * Adds a variable input operand.
 *
 * If this is the last time the variable is used, then it can be discarded
 * using the flag CSBE_OPV_DISCARD. That can reduce unnecessary usage
 * of callee-saved registers (that need to be saved/restored).
 *
 * \param csbe     CSBE context
 * \param var_num  Variable number. 0-based index.
 * \param flags    Bitwise OR of CSBE_OPV_* flags.
 */
void csbe_operand_var_in(struct Csbe *csbe, unsigned var_num, unsigned flags);

/** Variable is discarded after use (input vars only) */
#define CSBE_OPV_DISCARD 0x1

/**
 * Adds a variable output/result operand.
 *
 * \param csbe     CSBE context
 * \param var_num  Variable number. 0-based index.
 * \param flags    Bitwise OR of CSBE_OPV_* flags
 *                 (none exists yet; must be 0).
 */
void csbe_operand_var_out(struct Csbe *csbe, unsigned var_num, unsigned flags);

/**
 * Diverts the result of the last operation to another variable.
 * More precisely, this modifies the last csbe_operand_var_out() call.
 *
 * This function will "delete" the previous result variable by marking
 * it as unused. So this function should ONLY be used when the previous
 * result went to a temporary variable.
 *
 * \param csbe     CSBE context
 * \param var_num  New variable number. 0-based index.
 * \param flags    Bitwise OR of CSBE_OPV_* flags
 *                 (none exists yet; must be 0).
 */
void csbe_divert_result(struct Csbe *csbe, unsigned var_num, unsigned flags);

/**
 * Adds an integer value as an operand.
 * Note that static indexes should be added with csbe_operand_index().
 *
 * \param csbe      CSBE context
 * \param typekind  Type of value (CSBET_*)
 * \param value     The value. Signed values are simply casted.
 */
void csbe_operand_immed(struct Csbe *csbe,
                        enum CsbeTypeKind typekind, CsbeUint64 value);

/** Adds an index as an operand. */
void csbe_operand_index(struct Csbe *csbe, unsigned index);

/**
 * Adds a basic block ID as an operand.
 *
 * \param csbe      CSBE context
 * \param ebb_num   ID of basic block.
 */
void csbe_operand_ebb(struct Csbe *csbe, unsigned ebb_num);

/** Adds a function ID as an operand. */
void csbe_operand_funcdef(struct Csbe *csbe, unsigned funcdef_num);

/** Adds a global datadef ID as an operand. */
void csbe_operand_datadef(struct Csbe *csbe, unsigned datadef_num);

/**
 * Adds an operation-specific bitmask as an operand.
 *
 * \param csbe      CSBE context
 * \param flags     Bitwise OR of operation-specific flags.
 */
void csbe_operand_flags(struct Csbe *csbe, unsigned flags);

/**
 * Adds an operation-specific enum value as an operand.
 *
 * \param csbe      CSBE context
 * \param enumval   Value from operation-specific enum.
 */
void csbe_operand_enum(struct Csbe *csbe, int enumval);

/**
 * Adds an operation-specific pointer as an operand.
 *
 * \param csbe      CSBE context
 * \param enumval   Operation-specific pointer.
 */
void csbe_operand_ptr(struct Csbe *csbe, void *p);

/**
 * Adds a type as an operand.
 * Must be followed by call(s) for csbe_type_...()
 * and finally csbe_operand_type_end()
 *
 * \param csbe      CSBE context
 * \return  CSBEE_OK if successful, or CSBEE_OUT_OF_MEM if out of memory.
 */
enum CsbeErr csbe_operand_type_start(struct Csbe *csbe);

/**
 * Finalizes a type operand started with csbe_operand_type_start().
 */
void csbe_operand_type_end(struct Csbe *csbe);

/**
 * Marks the start of a function. Internally, this adds a
 * CSBEO_CALL_START and sets some internal information.
 *
 * \param csbe      CSBE context
 * \param num_args  Number of arguments (including "this" parameter,
 *                  but excluding the return value)
 * \return  CSBEE_OK if successful, or an error code if not.
 */
enum CsbeErr csbe_call_start(struct Csbe *csbe, unsigned num_args);

/**
 * Marks the start of a function argument. Internally, this starts a
 * CSBEO_CALL_ARG operation and sets some internal information.
 *
 * After this function call, csbe_operand_var_in() or
 * csbe_operand_immed() should be called, and then csbe_call_arg_end().
 */
enum CsbeErr csbe_call_arg_start(struct Csbe *csbe);

/** Marks the end of a function argument */
void csbe_call_arg_end(struct Csbe *csbe);

/** This produces the first parameter to CSBEO_CALL_FUNC* */
void csbe_operand_callinfo(struct Csbe *csbe);


/* =======================================================================
   |||||||||||||||||||||||||  Output Generation  |||||||||||||||||||||||||
   ======================================================================= */

/**
 * Generates an output file (e.g. executable, library, etc) for the
 * architecture with the given index.
 *
 * \param csbe         CSBE context
 * \param arch_id      0-based index of the architecture, in the order they
 *                     were added with csbe_config_add_arch
 *                     Should be 0 if there is only one.
 * \param buffer_out   Result is allocated and placed here.
 * \param size_out     Size is placed here.
 * \param allocfn      Optional function to use for allocating the result
 *                     buffer. The buffer needs no alignment.
 *                     If NULL, then malloc is used.
 * \param userparam    User parameter to pass to the allocator.
 * \return  CSBEE_OK if successful, or an error code if not.
 */
enum CsbeErr csbe_output(struct Csbe *csbe, int arch_id,
                         unsigned char **buffer_out, size_t *size_out,
                         CsbeBufferAllocFunc *allocfn, void *userparam);

#endif