-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathscc.h
More file actions
751 lines (585 loc) · 17.2 KB
/
scc.h
File metadata and controls
751 lines (585 loc) · 17.2 KB
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
// ====================================
// ======== Hungarian notation ========
// ====================================
// s_* - stretchy buffer
// hm_* - hash map
// ==============================
// ======== Error codes =========
// ==============================
enum ErrorCode {
Ok = 0,
Fail = 1,
CouldNotReadFile,
CouldNotOpenDir,
NotADirectory,
WrongNumberOfArguments,
InvalidArgument,
// Argument parsing.
Filename,
Flag,
// Compiler work flow
IntParse,
CouldNotAssemble,
CouldNotLink,
} typedef ErrorCode;
static char* SccErrorMessage;
// ========================
// ======== Common ========
// ========================
#define Debug 1
typedef uint8_t u8;
typedef uint8_t b8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint32_t b32;
typedef uint64_t u64;
typedef int8_t i8;
typedef int32_t i32;
typedef int64_t i64;
typedef float f32;
typedef double f64;
typedef size_t sz;
// Printf format strings.
#define FORMAT_I64 PLATFORM_FORMAT_I64
#define FORMAT_U64 PLATFORM_FORMAT_U64
#define true 1
#define false 0
#define Zero {0}
#define AsciiMax 128
#define LineMax 256
#define PathMax 256
#define LabelMax 128
#define MaxU64 0xffffffffffffffff
#define Max(a, b) ((a) < (b) ? (b) : (a))
#define Min(a, b) ((a) > (b) ? (b) : (a))
#define Kilobytes(n) (1024*n)
#define Megabytes(n) Kilobytes(1024)
#define Gigabytes(n) Megabytes(1024)
// SystemV parameter passing
#define Eightbytes(n) (n*8*8)
// Next multiple of p which is greater than v, or v if it is already aligned.
#define AlignPow2(v, p) ( \
(((v) + (p) - 1) & ~((p) - 1)) \
)
#define Assert(expr) PlatformAssert(expr)
#define PrintString(...) PlatformPrintString(__VA_ARGS__)
#define InvalidCodePath Assert(!"Invalid code path.")
#define ArrayCount(arr) (sizeof((arr)) / sizeof(*(arr)))
#define ArrayErrorDefault(f, l) \
fprintf(stderr, "Array overflow in %s:%d\n", f, l); \
Assert(!"Array error.");
#define ArrayError(f, l) ArrayErrorDefault(f, l)
#define ArrayPush(arr, e) \
if (ArrayCount(arr) > n_##arr) { \
(arr)[n_##arr++] = e; \
} else { \
ArrayError(__FILE__, __LINE__); \
}
#define Break PlatformBreak
#define DevBreak(message) \
fprintf(stderr, "Compiler dev: Keep going here [%s]\n", message); \
Break;
#define NotImplemented(message) \
printf("Not Implemented! -- [%s]\n", message); \
Assert(0);
// ========================
// ======== String ========
// ========================
char* getString(char* orig);
// ==========================
// ======== Platform ========
// ==========================
#if defined(_WIN32)
#include "platform_windows.h"
#else
#include "platform_unix.h"
#endif
u64 platformFirstBitSet(u64 val);
ErrorCode platformListDirectory(char*** out_files, char* dirname, b32 (*filter)(char*));
ErrorCode platformCompileAndLinkAsmFile(char* filename_without_extension);
ErrorCode platformAssemble(char* nasm_path, char* asm_file);
ErrorCode platformLink(char* ld_path, char* filename_without_extension);
// ========================
// ======== Memory ========
// ========================
#define ARENA_DEFAULT_BLOCK_SIZE Megabytes(1)
#define AllocType(arena, type) \
allocate(arena, sizeof(type))
#define AllocArray(arena, type, count) \
allocate(arena, sizeof(type) * (count))
#define ArenaBootstrap(object, arenaName) \
{ \
size_t sz = sizeof(*object); \
u8* block = arenaBlock(&sz); \
block += sizeof(ArenaHeader); \
Arena a = { \
.used = 0, \
.size = sz, \
.block = block, \
}; \
Arena* p = allocate(&a, sizeof(Arena)); \
*p = a; \
object->arenaName = p; \
}
struct Arena {
u8* block;
size_t used;
size_t size;
struct Arena* next;
} typedef Arena;
void* allocate(Arena* a, size_t num_bytes);
void deallocate(Arena* a);
// =======================
// ======== Ctype ========
// =======================
struct AstNode;
struct RegVar;
struct Ctype {
enum {
Type_NONE = 0,
// Arithmetic types
Type_ARITH = (1<<0),
Type_PEANO = (1<<1), // NOTE: Type_INTEGER would be too easy to confuse with Type_INT
Type_REAL = (1<<2),
// Integer types
Type_CHAR = Type_ARITH | Type_PEANO | (1<<3),
Type_SHORT = Type_ARITH | Type_PEANO | (1<<4),
Type_INT = Type_ARITH | Type_PEANO | (1<<5),
Type_LONG = Type_ARITH | Type_PEANO | (1<<6),
Type_UNSIGNED = (1 << 7),
Type_UCHAR = Type_CHAR | Type_UNSIGNED,
Type_USHORT = Type_SHORT | Type_UNSIGNED,
Type_UINT = Type_INT | Type_UNSIGNED,
Type_ULONG = Type_LONG | Type_UNSIGNED,
// Real types
Type_FLOAT = Type_ARITH | Type_REAL | (1<<10),
Type_DOUBLE = Type_ARITH | Type_REAL | (1<<11),
Type_FUNC = (1<<12),
// Structs and unions
Type_AGGREGATE = (1<<13),
// Pointers
Type_POINTER = (1<<14),
Type_ARRAY = (1<<15),
Type_ENUM = (1<<16),
} type;
enum {
Qual_CONST = (1<<0),
Qual_RESTRICT = (1<<1),
Qual_VOLATILE = (1<<2),
} qualifiers;
// TODO: Move this into an associated struct.
union {
struct CtypeAggregate {
char* tag;
struct AstNode* decls;
u64 bits;
} aggr;
struct CtypeFunc {
struct Ctype* return_type;
struct Ctype* s_params;
} func;
struct CtypePointer {
struct Ctype* pointee;
} pointer;
};
} typedef Ctype;
// =======================
// ======== Lexer ========
// =======================
enum Keyword {
#define X(keyword) Keyword_ ## keyword,
#include "keywords.inl"
#undef X
} typedef Keyword;
enum TokType {
TType_NONE,
TType_PUNCTUATOR,
TType_STRING_LITERAL,
TType_NUMBER,
TType_FLOAT,
TType_DOUBLE,
TType_ID,
TType_KEYWORD = 0xF000,
} typedef TokType;
enum Punctuator {
Punctuator_BEGIN = /*...*/ 128, // ASCII codes are reserved for single-char punctuators.
#define X(op, name) name,
#include "punctuators.inl"
#undef X
Punctuator_END,
} typedef Punctuator;
struct Token {
TokType type;
union {
u64 value;
union {
char* string;
u8 character;
u16 uint16;
i32 int32;
i64 int64;
f32 real32;
f64 real64;
} cast;
};
u64 line_number;
struct Token* next;
} typedef Token;
// =====================
// ======== AST ========
// =====================
typedef enum AstType_n {
#define X(node) node,
#include "ast_nodes.inl"
#undef X
} AstType;
struct AstNode {
AstType type;
union {
// Ast_DECLARATION_SPECIFIER
struct AstNodeDeclSpec {
Ctype ctype;
} as_decl_specifier;
// Ast_DECLARATOR
struct AstNodeDeclarator {
char* id;
struct AstNode* params; // Ast_PARAMETER
u32 pointer_stars;
} as_declarator;
// Ast_NUMBER
struct {
Token* tok;
} as_number;
// Ast_ID
struct {
Token* tok;
} as_id;
struct {
Token* tok;
} as_string_literal;
// Ast_IF
struct {
struct AstNode* condition;
struct AstNode* then;
struct AstNode* else_;
} as_if /*lol*/;
// Ast_ADDRESS
// Ast_POSTFIX_INC
// Ast_POSTFIX_DEC
// Ast_RETURN
struct {
struct AstNode* expr;
} as_single_expr;
// Ast_PARAMETER
struct AstNodeParameter {
struct AstNode* decl_specifier;
struct AstNodeDeclarator* declarator;
struct AstNodeParameter* next;
} as_parameter;
// Ast_ARGUMENT_EXPR_LIST
struct AstNodeArgument {
struct AstNode* expr;
struct AstNodeArgument* next;
} as_arg_expr_list;
// Ast_FUNCDEF
struct {
char* label;
Ctype ctype; // Function type (return type & param types)
struct AstNodeDeclarator* declarator;
struct AstNode* compound_stmt;
} as_funcdef;
// Ast_ASSIGN_EXPR
struct AstNodeAssignExpr {
struct AstNode* lhs;
Token* op;
struct AstNode* rhs;
} as_assignment_expr;
// Ast_FUNCCALL
struct {
struct AstNode* expr;
struct AstNodeArgument* arg_expr_list;
} as_funccall;
// Ast_DECLARATOR_LIST
struct AstNodeDeclaratorList {
struct AstNodeDeclarator* declarator;
struct AstNodeDeclaratorList* next;
} as_declarator_list;
// Ast_DECLARATION
struct AstNodeDeclaration {
struct AstNodeDeclSpec* decl_spec;
struct AstNodeDeclaratorList* declarators;
struct AstNode* rhs;
} as_declaration;
// Ast_DECLARATION_LIST
struct AstNodeDeclarationList {
struct AstNodeDeclaration* declaration;
struct AstNodeDeclarationList* next;
} as_declaration_list;
// Ast_STRUCT_MEMBER_ACCESS
struct {
struct AstNode* primary_expr;
char* field;
} as_member_access;
// Binary expressions
struct {
struct AstNode* left;
struct AstNode* right;
} as_binary_expr;
// Ast_COMPOUND_STMT
struct AstNodeCompoundStmt {
struct AstNode* stmt;
struct AstNodeCompoundStmt* next;
} as_compound_stmt;
// Ast_ITERATION
struct {
struct AstNodeDeclaration* declaration;
struct AstNode* before_iteration;
struct AstNode* after_iteration;
struct AstNode* body;
} as_iteration;
// Ast_TRANSLATION_UNIT
struct AstNodeTU {
struct AstNode* node;
struct AstNodeTU* next;
} as_tu;
};
u64 line_number;
} typedef AstNode;
// ========================
// ======== Parser ========
// ========================
struct HMAggregateSizes;
#define HashmapName HMAggregateSizes
#define HashmapPrefix aggr
#define HashmapKey char*
#define HashmapValue u64
#include "hashmap.inl"
struct HMStaticArrays;
#define HashmapName HMStaticArrays
#define HashmapPrefix staticArr
#define HashmapKey char*
#define HashmapValue char*
#include "hashmap.inl"
struct StaticBuffer {
enum {
SBType_STRING,
SBType_ARRAY,
} type;
union {
// String
Token* tok;
// Array?
struct {
u32 size; // TODO: Does the spec specify a minimum static array size?
Ctype ctype;
};
};
} typedef StaticBuffer;
struct Parser {
Token* token; // The next token to parse.
Arena* arena;
AstNode* tree;
char* file_name;
HMAggregateSizes* hm_sizes;
HMStaticArrays* hm_static_arrays;
enum {
ParserFlag_FANSI = (1 << 0),
} flags;
} typedef Parser;
// =========================
// ======== Codegen ========
// =========================
typedef enum RegisterEnum {
Reg_RAX,
Reg_RBX,
Reg_RCX,
Reg_RDX,
Reg_RSI,
Reg_RDI,
Reg_R8,
Reg_R9,
Reg_R10,
Reg_R11,
Reg_R12,
Reg_R13,
Reg_R14,
Reg_R15,
// Floating point registers.
Reg_XMM0,
Reg_XMM1,
Reg_XMM2,
Reg_XMM3,
Reg_XMM4,
Reg_XMM5,
Reg_XMM6,
Reg_XMM7,
Reg_Count,
} RegisterEnum;
enum EmitTarget {
Target_NONE,
Target_ACCUM,
Target_STACK,
} typedef EmitTarget;
// TODO: Make Location fit in a register and use a hack to fit 64-bit values.
struct Location {
enum {
Location_INVALID,
Location_IMMEDIATE,
Location_REGISTER,
Location_STACK, // RSP relative
Location_REG_POINTER, // Pointer relative to register
} type;
union {
// REGISTER
struct {
RegisterEnum reg;
// STACK_FROM_REG
i32 reg_offset;
};
// IMMEDIATE
union {
union {
f64 real64;
i64 int64;
} cast;
u64 immediate_value; // Cast to appropriate value based on token type.
};
// STACK
struct {
i64 offset;
};
};
} typedef Location;
struct RegVar {
Ctype c;
Location location;
} typedef RegVar;
// SymTable definition
struct SymTable;
#define HashmapName SymTable
#define HashmapPrefix sym
#define HashmapKey char*
#define HashmapValue RegVar
#define HashFunction hashStrPtr
#define KeyCompareFunc compareStringKey
#include "hashmap.inl"
typedef struct StackValue_s {
unsigned int offset : 6;
enum {
Stack_OFFSET,
Stack_QWORD,
} type : 2;
} StackValue;
struct TagMember {
char* id;
Ctype ctype;
i64 offset;
} typedef TagMember;
struct Tag {
RegVar rvar;
TagMember* s_members;
} typedef Tag;
// TagTable definition
struct TagTable;
#define HashmapName TagTable
#define HashmapPrefix tag
#define HashmapKey char*
#define HashmapValue Tag
#define HashFunction hashStrPtr
#define KeyCompareFunc compareStringKey
#include "hashmap.inl"
#define SCOPE_HASH_SIZE 1024
struct Scope {
Arena* arena;
int if_count;
struct Scope* prev;
// Name spaces
//SymTable label_table;
// Structs, enums, unions
TagTable tag_table;
SymTable symbol_table;
} typedef Scope;
Tag* findTag(Scope* scope, char* name);
enum MachineConfigFlags {
Config_TARGET_MACOS = (1<<0),
Config_TARGET_LINUX = (1<<1),
Config_TARGET_WIN = (1<<2),
Config_INSTR_OUTPUT_DISABLED = (1<<3),
} typedef MachineConfigFlags;
struct Machine typedef Machine;
struct Codegen {
Arena* arena;
Scope* scope;
char* file_name;
u64 last_line_number;
AstNode* current_function;
HMStaticArrays* hm_static_arrays;
// Disable/Enable instruction output.
#define MaxInstrOutputStack 8
char instrOutputStack[MaxInstrOutputStack];
char n_instrOutputStack;
Machine* m;
// Constants
AstNode* one;
} typedef Codegen;
// =====================================
// ======== Machine abstraction ========
// =====================================
struct Machine {
u8 flags; // MachineConfigFlags
Location (*declareStringLiteral)(void* machine, char* label, char* string);
void (*stackPop)(void* machine, RegVar* et);
Location (*stackPush)(void* machine, Location location);
Location (*stackPushReg)(void* machine, RegisterEnum reg);
Location (*stackPushImm)(void* machine, i64 value);
Location (*stackPushOffset)(void* machine, u64 bytes);
void (*stackAddress)(void* machine, RegVar* entry, Location target_loc);
void (*addressOf)(void* machine, Location* loc, Location target_loc);
void (*functionPrelude)(void* machine, char* func_name);
void (*beginFuncParams ) (void* machine);
void (*pushParameter)(void* machine, Scope* scope, RegVar* rvar);
Location (*popParameter)(void* machine, Scope* scope, Ctype* ctype);
void (*endFuncParams ) (void* machine);
void (*functionEpilogue)(void* machine);
void (*mov)(void* machine, RegVar* dst, RegVar* src);
void (*add)(void* machine, RegVar* dst, RegVar* src);
void (*sub)(void* machine, RegVar* dst, RegVar* src);
void (*mul)(void* machine, RegVar* dst, RegVar* src);
void (*div)(void* machine, RegVar* dst, RegVar* src);
void (*mod)(void* machine, RegVar* dst, RegVar* src);
void (*bitAnd)(void* machine, RegVar* dst, RegVar* src);
void (*bitOr)(void* machine, RegVar* dst, RegVar* src);
void (*bitXor)(void* machine, RegVar* dst, RegVar* src);
void (*shiftLeft)(void* machine, RegVar* dst, RegVar* src);
void (*shiftRight)(void* machine, RegVar* dst, RegVar* src);
void (*cmp)(void* machine, RegVar* dst, RegVar* src);
void (*cmpSet)(void* machine, AstType type, Location dst);
void (*cmpJmp)(void* machine, AstType ast_type, char* label);
void (*cmpJmpStackTop)(void* machine, AstType ast_type, Location loc_to_compare, RegVar* type, char* then, char* els);
void (*testAndJump)(void* machine, RegisterEnum reg, u32 bits, char* then, char* els);
void (*jmp)(void* machine, char* label);
void (*label)(void* machine, char* label);
void (*call)(void* machine, char* func);
void (*finish)(void* machine);
// Registers
RegVar* (*immediateFromToken)(void* machine, Token* tok);
RegVar* (*helper)(void* machine, int type /*Ctype.type*/, u32 bits);
RegVar* (*helperC)(void* machine, Ctype c);
RegVar* (*accum)(void* machine, int type /*Ctype.type*/, u32 bits);
RegVar* (*accumC)(void* machine, Ctype c);
// Conversion. Result in stack
void (*convertFloatToInt)(void* machine, Location from, EmitTarget target);
void (*convertIntegerToFloat)(void* machine, Location from, EmitTarget target);
void (*convertDoubleToInt)(void* machine, Location from, EmitTarget target);
void (*convertIntegerToDouble)(void* machine, Location from, EmitTarget target);
void (*convertDoubleToFloat)(void* machine, Location from, EmitTarget target);
void (*convertFloatToDouble)(void* machine, Location from, EmitTarget target);
};
Machine* makeMachineX64(Arena* a, MachineConfigFlags mflags);
struct Codegen;
// ======================
// ======== User ========
// ======================
enum CompilerFlag {
CompilerFlag_TEST_ALL = (1<<0),
} typedef CompilerFlag;