aboutsummaryrefslogtreecommitdiff
path: root/src/AstGen.zig
AgeCommit message (Collapse)Author
2021-10-25stage2: fix switch on tagged union capture-by-pointerAndrew Kelley
* AstGen: always use `typeof` and never `typeof_elem` on the `switch_cond`/`switch_cond_ref` instruction because both variants return a value and not a pointer. - Delete the `typeof_elem` ZIR instruction since it is no longer needed. * Sema: validateUnionInit now recognizes a comptime mutable value and no longer emits a compile error saying "cannot evaluate constant expression" - Still to-do is detecting comptime union values in a function that is not being executed at compile-time. - This is still to-do for structs too. * Sema: when emitting a call AIR instruction, call resolveTypeLayout on all the parameter types as well as the return type. * `Type.structFieldOffset` now works for unions in addition to structs.
2021-10-25AstGen: move nodeMayEvalToError logic for builtinsAndrew Kelley
to the declarative BuiltinFn.zig file which lists info about all the builtin functions.
2021-10-23astgen.zig: emit ZIR for callconv before return type in fnDecl and fnProtoExprMatthew Borkowski
2021-10-23astgen.zig: when ret's operand ResultLoc is .ptr, load from ret_ptr before ↵Matthew Borkowski
is_non_err or err_union_code
2021-10-23astgen.zig: fix nodeMayEvalToErrorMatthew Borkowski
2021-10-22stage2: change `@bitCast` to always be by-valueAndrew Kelley
After a discussion about language specs, this seems like the best way to go, because it's simpler to reason about both for humans and compilers. The `bitcast_result_ptr` ZIR instruction is no longer needed. This commit also implements writing enums, arrays, and vectors to virtual memory at compile-time. This unlocked some more of compiler-rt being able to build, which in turn unlocks saturating arithmetic behavior tests. There was also a memory leak in the comptime closure system which is now fixed.
2021-10-20stage2: implement slicingAndrew Kelley
* New AIR instruction: slice, which constructs a slice out of a pointer and a length. * AstGen: use `coerced_ty` for start and end expressions, use `none` for the sentinel, and don't try to load the result of the slice operation because it returns a by-value result. * Sema: pointer arithmetic is extracted into analyzePointerArithmetic and it is used by the implementation of slice. - Also I implemented comptime pointer addition. * Sema: extract logic into analyzeSlicePtr, analyzeSliceLen and use them inside the slice semantic analysis. - The approach in stage2 is much cleaner than stage1 because it uses more granular analysis calls for obtaining the slice pointer, doing arithmetic on it, and checking if the length is comptime-known. * Sema: use the slice Value Tag for slices when doing coercion from pointer-to-array. * LLVM backend: detect when emitting a GEP instruction into a pointer-to-array and add the extra index that is required. * Type: ptrAlignment for c_void returns 0. * Implement Value.hash and Value.eql for slices. * Remove accidentally duplicated behavior test.
2021-10-20Sema: fix missing copy in array multiplicationAndrew Kelley
lead to a Use-After-Free in backend codgen
2021-10-20AstGen: make the index variable of `inline for` a `alloc_comptime`Andrew Kelley
Before it was being emitted as an `alloc` which caused inline for loops to not work correctly.
2021-10-19stage2: implement switching on unionsAndrew Kelley
* AstGen: Move `refToIndex` and `indexToRef` to Zir * ZIR: the switch_block_*_* instruction tags are collapsed into one switch_block tag which uses 4 bits for flags, and reduces the scalar_cases_len field from 32 to 28 bits. This freed up more ZIR tags, 2 of which are now used for `switch_cond` and `switch_cond_ref` for producing the switch condition value. For example, for union values it returns the corresponding enum value. * switching with multiple cases and ranges is not yet supported because I want to change the ZIR encoding to store index pointers into the extra array rather than storing prong indexes. This will avoid O(N^2) iteration over prongs. * AstGen now adds a `switch_cond` on the operand and then passes the result of that to the `switch_block` instruction. * Sema: partially implement `switch_capture_*` instructions. * Sema: `unionToTag` notices if the enum type has only one possible value.
2021-10-20stage2: remove AstGen none_or_refRobin Voetter
The remaining uses of this result location were causing a bunch of errors problems where the pointers returned from rvalue and lvalue expressions would be confused, allowing for extra pointers on rvalue expressions. For example: ```zig const X = struct {a: i32}; var x: X = .{.a = 1}; var ptr = &x; _ = x.a; ``` In the last line, the lookup of x with result location .none_or_ref would return a double pointer (**X). This would be dereferenced one, after which a relative pointer to `a` would be fetched and derefenced to get the final result. However, this also allows us to manually construct a double pointer, and fetch the field of the inner type of that: ```zig _ = &(&(x)).a; ``` This problem also manifests itself with element access. There are two obvious ways to fix the problem, both of which include replacing the usage of .none_or_ref for field- and element accesses with something which deterministically produce either a pointer or value: either result location .ref or .none. In the former case, this would be paired with .elem_ptr, and in the latter case with .elem_val. Note that the stage 1 compiler does not have this problem, because there is no equivalent of .elem_val and .field_val. In this way it is equivalent to using the result location .ref for field- and element accesses. In this case i have used .none, as this matches language behaviour more closely.
2021-10-19astgen.zig: fix emitting wrong error unwrapping instructions in tryExprMatthew Borkowski
2021-10-18astgen.zig: fix false positive in breakExpr's checking for store_to_block_ptrMatthew Borkowski
2021-10-12stage2: fix comptime stores and sentinel-terminated arraysAndrew Kelley
* ZIR: the `array_type_sentinel` now has a source node attached to it for proper error reporting. * Refactor: move `Module.arrayType` to `Type.array` * Value: the `bytes` and `array` tags now include the sentinel, if the type has one. This simplifies comptime evaluation logic. * Sema: fix `zirStructInitEmpty` to properly handle when the type is void or a sentinel-terminated array. This handles the syntax `void{}` and `[0:X]T{}`. * Sema: fix the logic for reporting "cannot store runtime value in compile time variable" as well as for emitting a runtime store when a pointer value is comptime known but it is a global variable. * Sema: implement elemVal for double pointer to array. This can happen with this code for example: `var a: *[1]u8 = undefined; _ = a[0];` * Sema: Rework the `storePtrVal` function to properly handle nested structs and arrays. - Also it now handles comptime stores through a bitcasted pointer. When the pointer element type and the type according to the Decl don't match, the element value is bitcasted before storage.
2021-10-10Merge pull request #9925 from mattbork/uniondecl-fixesAndrew Kelley
stage2: astgen unionDecl fixes
2021-10-10translate-c: fix logic for checking primitive namesAndrew Kelley
isZigPrimitiveType had a bug where it checked the integer names (e.g. u32) before primitives, leading it to incorrectly return `false` for `undefined` which starts with `u`. Related: #9928
2021-10-09stage2: add astgen errors for untyped union fields and union field values ↵Matthew Borkowski
without inferred tag type
2021-10-09stage2: fix astgen for anytype union fields and differentiate anytype vs ↵Matthew Borkowski
inferred void in semaUnionFields
2021-10-07stage2: fix returning structs byval from functionsAndrew Kelley
2021-10-07AstGen: make array literals work like struct literalsAndrew Kelley
Now, array literals will emit a coerce_result_ptr ZIR instruction just like struct literals do. This makes for another passing behavior test case.
2021-10-07stage2: implement array literal with explicit typeAndrew Kelley
New ZIR instruction: elem_ptr_imm This saves some memory for array literals since the element indexes are communicated as immediate values rather than as references to other ZIR instructions.
2021-10-04Merge pull request #9882 from mattbork/astgen-cursorAndrew Kelley
astgen.zig: keep source cursor increasing monotonically as much as possible
2021-10-02AstGen: fix `while` and `for` with unreachable bodiesAndrew Kelley
Companion commit to 61a53a587558ff1fe1b0ec98bb424022885edccf. This commit also moves over a bunch of behavior test cases to the passing-for-stage2 section.
2021-10-02AstGen: fix if, orelse, catch, with unreachable bodiesAndrew Kelley
Before, the system to replace a result location pointer with a traditional break instruction did not notice the case when one of the bodies was unreachable. Now, the emitted ZIR code is improved and simplified in this case, resulting in a new passing behavior test.
2021-10-02astgen.zig formattingMatthew Borkowski
2021-10-02astgen.zig: assert that advanceSourceCursor never has to rewind cursorMatthew Borkowski
2021-10-02astgen.zig: have defer scopes cache source cursor to reduce redundant ↵Matthew Borkowski
scanning during genDefers
2021-10-02astgen.zig: make switchExpr generate cases in source order to keep source ↵Matthew Borkowski
cursor increasing monotonically
2021-10-02astgen.zig: pass lbrace line and column to addFunc to keep source cursor ↵Matthew Borkowski
increasing monotonically
2021-09-29stage2: enable building compiler_rt when using LLVM backendAndrew Kelley
* AstGen: fix emitting `store_to_inferred_ptr` when it should be emitting `store` for a variable that has an explicit alignment. * Compilation: fix a couple memory leaks * Sema: implement support for locals that have specified alignment. * Sema: implement `@intCast` when it needs to emit an AIR instruction. * Sema: implement `@alignOf` * Implement debug printing for extended alloc ZIR instructions.
2021-09-28AstGen: improved logic for nodeMayNeedMemoryLocationAndrew Kelley
* `@as` and `@bitCast` no longer unconditionally return `true` from this function; they forward the question to their sub-expression. * fix `@splat` incorrectly being marked as needing a memory location (this function returns a SIMD vector; it definitely does not want a memory location). Makes AstGen generate slightly nicer ZIR, which in turn generates slightly nicer AIR, generating slightly nicer machine code in debug builds. It also means I can procrastinate implementing the bitcast_result_ptr ZIR instruction semantic analysis :^)
2021-09-28saturating arithmetic modificationsAndrew Kelley
* Remove the builtins `@addWithSaturation`, `@subWithSaturation`, `@mulWithSaturation`, and `@shlWithSaturation` now that we have first-class syntax for saturating arithmetic. * langref: Clarify the behavior of `@shlExact`. * Ast: rename `bit_shift_left` to `shl` and `bit_shift_right` to `shr` for consistency. * Air: rename to include underscore separator with consistency with the rest of the ops. * Air: add shl_exact instruction * Use non-extended tags for saturating arithmetic, to keep it simple so that all the arithmetic operations can be done the same way. - Sema: unify analyzeArithmetic with analyzeSatArithmetic - implement comptime `+|`, `-|`, and `*|` - allow float operands to saturating arithmetic * `<<|` allows any integer type for the RHS. * C backend: fix rebase conflicts * LLVM backend: reduce the amount of branching for arithmetic ops * zig.h: fix magic number not matching actual size of C integer types
2021-09-28AstGen: delete dead codeAndrew Kelley
2021-09-28sat-arithmetic: create Sema.analyzeSatArithmeticTravis Staloch
- similar to Sema.analyzeArithmetic but uses accepts Zir.Inst.Extended.InstData - missing support for Pointer types and comptime arithmetic
2021-09-28sat-arithmetic: fixups zig fmt / astcheckTravis Staloch
2021-09-28sat-arithmetic: add c backend supportTravis Staloch
- modify AstGen binOpExt()/assignBinOpExt() to accept generic extended payload T - rework Sema zirSatArithmetic() to use existing sema.analyzeArithmetic() by adding an `opt_extended` parameter. - add airSatOp() to codegen/c.zig - add saturating functions to src/link/C/zig.h
2021-09-28sat-arithmetic: add operator supportTravis Staloch
- adds initial support for the operators +|, -|, *|, <<|, +|=, -|=, *|=, <<|= - uses operators in addition to builtins in behavior test - adds binOpExt() and assignBinOpExt() to AstGen.zig. these need to be audited
2021-09-28Stage 2: Support inst.func() syntax (#9827)Martin Wickham
* Merge call zir instructions to make space for field_call * Fix bug with comptime known anytype args * Delete the param_type zir instruction * Move some passing tests to stage 2 * Implement a.b() function calls * Add field_call_bind support for call and field builtins
2021-09-24stage2: implement `@memset` and `@memcpy` builtinsAndrew Kelley
2021-09-24Spelling corrections (#9833)Josh Soref
Signed-off-by: Josh Soref <jsoref@users.noreply.github.com> Co-authored-by: Josh Soref <jsoref@users.noreply.github.com>
2021-09-23Stage2: Implement comptime closures and the This builtin (#9823)Martin Wickham
2021-09-22stage2: fix AstGen for some struct syntaxesAndrew Kelley
* AstGen: fix not emitting `struct_init_empty` when an explicit type is present in struct initialization syntax. * AstGen: these two syntaxes now lower to identical ZIR: - `var a = A{ .b = c };` - `var a = @as(A, .{ .b = c });` * Zir: clarify `auto_enum_tag` in the doc comments. * LLVM Backend: fix lowering of function return types when the type has 0 bits.
2021-09-21stage2: progress towards ability to compile compiler-rtAndrew Kelley
* prepare compiler-rt to support being compiled by stage2 - put in a few minor workarounds that will be removed later, such as using `builtin.stage2_arch` rather than `builtin.cpu.arch`. - only try to export a few symbols for now - we'll move more symbols over to the "working in stage2" section as they become functional and gain test coverage. - use `inline fn` at function declarations rather than `@call` with an always_inline modifier at the callsites, to avoid depending on the anonymous array literal syntax language feature (for now). * AIR: replace floatcast instruction with fptrunc and fpext for shortening and widening floating point values, respectively. * Introduce a new ZIR instruction, `export_value`, which implements `@export` for the case when the thing to be exported is a local comptime value that points to a function. - AstGen: fix `@export` not properly reporting ambiguous decl references. * Sema: handle ExportOptions linkage. The value is now available to all backends. - Implement setting global linkage as appropriate in the LLVM backend. I did not yet inspect the LLVM IR, so this still needs to be audited. There is already a pending task to make sure the alias stuff is working as intended, and this is related. - Sema almost handles section, just a tiny bit more code is needed in `resolveExportOptions`. * Sema: implement float widening and shortening for both `@floatCast` and float coercion. - Implement the LLVM backend code for this as well.
2021-09-20stage2: various fixes to cImport, sizeOf and types to get tests passingVeikka Tuominen
2021-09-20stage2: implement cImportVeikka Tuominen
2021-09-20Address Spaces: Yeet address space on function prototypesRobin Voetter
This is a property which solely belongs to pointers to functions, not to the functions themselves. This cannot be properly represented by stage 2 at the moment, as type with zigTypeTag() == .Fn is overloaded for for function pointers and function prototypes.
2021-09-20Address Spaces: fmt a bunch of stuffRobin Voetter
2021-09-20Address spaces: Forbid addrspace and linksection for local variablesRobin Voetter
2021-09-20Address Spaces: Sema basicsRobin Voetter
2021-09-20Address spaces: AstGenRobin Voetter
Adds AST generation for address spaces on pointers, function prototypes, function declarations and variable declarations. In the latter two cases, declaration properties were already stored more efficiently in a declaration structure. To accomodate these for address spaces, the bit indicating presence of a linksection attribute has been extended to include either linksection, address space, or both.