Commit fc6e111b76

Andrew Kelley <andrew@ziglang.org>
2022-07-21 22:07:27
Sema: improve compile error for bad function alignment
* Integrate more declaratively with src/target.zig * Only trigger the check when a function body is found, do not trigger for function types.
1 parent b946934
src/Sema.zig
@@ -18010,6 +18010,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
     const section_src: LazySrcLoc = .{ .node_offset_fn_type_section = inst_data.src_node };
     const cc_src: LazySrcLoc = .{ .node_offset_fn_type_cc = inst_data.src_node };
     const ret_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = inst_data.src_node };
+    const has_body = extra.data.body_len != 0;
 
     var extra_index: usize = extra.end;
 
@@ -18019,8 +18020,11 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
         break :blk lib_name;
     } else null;
 
-    if ((extra.data.bits.has_align_body or extra.data.bits.has_align_ref) and sema.mod.getTarget().cpu.arch.isWasm()) {
-        return sema.fail(block, align_src, "'align' is not allowed on functions in wasm", .{});
+    if (has_body and
+        (extra.data.bits.has_align_body or extra.data.bits.has_align_ref) and
+        !target_util.supportsFunctionAlignment(target))
+    {
+        return sema.fail(block, align_src, "target does not support function alignment", .{});
     }
 
     const @"align": ?u32 = if (extra.data.bits.has_align_body) blk: {
@@ -18162,7 +18166,6 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
     } else 0;
 
     var src_locs: Zir.Inst.Func.SrcLocs = undefined;
-    const has_body = extra.data.body_len != 0;
     if (has_body) {
         extra_index += extra.data.body_len;
         src_locs = sema.code.extraData(Zir.Inst.Func.SrcLocs, extra_index).data;
src/target.zig
@@ -744,6 +744,7 @@ pub fn llvmMachineAbi(target: std.Target) ?[:0]const u8 {
     }
 }
 
+/// This function returns 1 if function alignment is not observable or settable.
 pub fn defaultFunctionAlignment(target: std.Target) u32 {
     return switch (target.cpu.arch) {
         .arm, .armeb => 4,
@@ -753,3 +754,10 @@ pub fn defaultFunctionAlignment(target: std.Target) u32 {
         else => 1,
     };
 }
+
+pub fn supportsFunctionAlignment(target: std.Target) bool {
+    return switch (target.cpu.arch) {
+        .wasm32, .wasm64 => false,
+        else => true,
+    };
+}
test/cases/compile_errors/align_n_expr_function_pointers_is_a_compile_error.zig
@@ -6,4 +6,4 @@ export fn foo() align(1) void {
 // backend=stage2
 // target=wasm32-freestanding-none
 //
-// :1:23: error: 'align' is not allowed on functions in wasm
\ No newline at end of file
+// :1:23: error: target does not support function alignment