authorgravatar for timonkruiper@gmail.comTimon Kruiper <timonkruiper@gmail.com> 2020-12-24 16:47:09+01:00
committergravatar for timonkruiper@gmail.comTimon Kruiper <timonkruiper@gmail.com> 2020-12-28 21:20:49+01:00
log4a32d4f288737a0d67484c1f05817ec468ec41f1
treed41c1643aeedf082bae5eb7d8801029c99cddf52
parent09cf043efd5966e328e4454bc30bc756f439938b

stage2: refactor (simplify) code structure of `llvm_backend.zig`


1 files changed, 55 insertions(+), 59 deletions(-)

src/llvm_backend.zig+55-59
......@@ -136,8 +136,11 @@ pub fn targetTriple(allocator: *Allocator, target: std.Target) ![:0]u8 {
136136}
137137
138138pub const LLVMIRModule = struct {
139 module: *Module,
139140 llvm_module: *const llvm.ModuleRef,
140141 target_machine: *const llvm.TargetMachineRef,
142 builder: *const llvm.BuilderRef,
143
141144 output_path: []const u8,
142145
143146 gpa: *Allocator,
......@@ -192,9 +195,14 @@ pub const LLVMIRModule = struct {
192195 );
193196 errdefer target_machine.disposeTargetMachine();
194197
198 const builder = llvm.BuilderRef.createBuilder();
199 errdefer builder.disposeBuilder();
200
195201 self.* = .{
202 .module = options.module.?,
196203 .llvm_module = llvm_module,
197204 .target_machine = target_machine,
205 .builder = builder,
198206 .output_path = sub_path,
199207 .gpa = gpa,
200208 };
......@@ -202,8 +210,9 @@ pub const LLVMIRModule = struct {
202210 }
203211
204212 pub fn deinit(self: *LLVMIRModule, allocator: *Allocator) void {
205 self.llvm_module.disposeModule();
213 self.builder.disposeBuilder();
206214 self.target_machine.disposeTargetMachine();
215 self.llvm_module.disposeModule();
207216 allocator.destroy(self);
208217 }
209218
......@@ -216,6 +225,14 @@ pub const LLVMIRModule = struct {
216225 }
217226
218227 pub fn flushModule(self: *LLVMIRModule, comp: *Compilation) !void {
228 if (comp.verbose_llvm_ir) {
229 const dump = self.llvm_module.printToString();
230 defer llvm.disposeMessage(dump);
231
232 const stderr = std.io.getStdErr().outStream();
233 try stderr.writeAll(std.mem.spanZ(dump));
234 }
235
219236 {
220237 var error_message: [*:0]const u8 = undefined;
221238 // verifyModule always allocs the error_message even if there is no error
......@@ -228,14 +245,6 @@ pub const LLVMIRModule = struct {
228245 }
229246 }
230247
231 if (comp.verbose_llvm_ir) {
232 const dump = self.llvm_module.printToString();
233 defer llvm.disposeMessage(dump);
234
235 const stderr = std.io.getStdErr().outStream();
236 try stderr.writeAll(std.mem.spanZ(dump));
237 }
238
239248 const output_pathZ = try self.gpa.dupeZ(u8, self.output_path);
240249 defer self.gpa.free(output_pathZ);
241250
......@@ -258,7 +267,7 @@ pub const LLVMIRModule = struct {
258267
259268 pub fn updateDecl(self: *LLVMIRModule, module: *Module, decl: *Module.Decl) !void {
260269 const typed_value = decl.typed_value.most_recent.typed_value;
261 self.generate(module, typed_value, decl.src()) catch |err| switch (err) {
270 self.gen(module, typed_value, decl.src()) catch |err| switch (err) {
262271 error.CodegenFail => {
263272 decl.analysis = .codegen_failure;
264273 try module.failed_decls.put(module.gpa, decl, self.err_msg.?);
......@@ -268,19 +277,12 @@ pub const LLVMIRModule = struct {
268277 };
269278 }
270279
271 fn generate(self: *LLVMIRModule, module: *Module, typed_value: TypedValue, src: usize) !void {
280 fn gen(self: *LLVMIRModule, module: *Module, typed_value: TypedValue, src: usize) !void {
272281 switch (typed_value.ty.zigTypeTag()) {
273282 .Fn => {
274283 const func = typed_value.val.cast(Value.Payload.Function).?.func;
275284
276 var codegen = CodeGen{
277 .module = module,
278 .llvm_module = self.llvm_module,
279 .builder = llvm.BuilderRef.createBuilder(),
280 };
281 defer codegen.builder.disposeBuilder();
282
283 const llvm_func = try codegen.resolveLLVMFunction(func);
285 const llvm_func = try self.resolveLLVMFunction(func);
284286
285287 // We remove all the basic blocks of a function to support incremental
286288 // compilation!
......@@ -290,15 +292,15 @@ pub const LLVMIRModule = struct {
290292 }
291293
292294 const entry_block = llvm_func.appendBasicBlock("Entry");
293 codegen.builder.positionBuilderAtEnd(entry_block);
295 self.builder.positionBuilderAtEnd(entry_block);
294296
295297 const instructions = func.analysis.success.instructions;
296298 for (instructions) |inst| {
297299 switch (inst.tag) {
298 .breakpoint => try codegen.generateBreakpoint(inst.castTag(.breakpoint).?),
299 .call => try codegen.generateCall(inst.castTag(.call).?),
300 .unreach => codegen.generateUnreach(inst.castTag(.unreach).?),
301 .retvoid => codegen.generateRetVoid(inst.castTag(.retvoid).?),
300 .breakpoint => try self.genBreakpoint(inst.castTag(.breakpoint).?),
301 .call => try self.genCall(inst.castTag(.call).?),
302 .unreach => self.genUnreach(inst.castTag(.unreach).?),
303 .retvoid => self.genRetVoid(inst.castTag(.retvoid).?),
302304 .dbg_stmt => {
303305 // TODO: implement debug info
304306 },
......@@ -310,83 +312,70 @@ pub const LLVMIRModule = struct {
310312 }
311313 }
312314
313 pub fn fail(self: *LLVMIRModule, src: usize, comptime format: []const u8, args: anytype) error{ OutOfMemory, CodegenFail } {
314 @setCold(true);
315 std.debug.assert(self.err_msg == null);
316 self.err_msg = try Compilation.ErrorMsg.create(self.gpa, src, format, args);
317 return error.CodegenFail;
318 }
319};
320
321const CodeGen = struct {
322 module: *Module,
323 llvm_module: *const llvm.ModuleRef,
324 builder: *const llvm.BuilderRef,
325
326 fn generateCall(codegen: *CodeGen, inst: *Inst.Call) !void {
315 fn genCall(self: *LLVMIRModule, inst: *Inst.Call) !void {
327316 if (inst.func.cast(Inst.Constant)) |func_inst| {
328317 if (func_inst.val.cast(Value.Payload.Function)) |func_val| {
329318 const func = func_val.func;
330319 const zig_fn_type = func.owner_decl.typed_value.most_recent.typed_value.ty;
331 const llvm_fn = try codegen.resolveLLVMFunction(func);
320 const llvm_fn = try self.resolveLLVMFunction(func);
332321
333322 // TODO: handle more arguments, inst.args
334323
335324 // TODO: LLVMBuildCall2 handles opaque function pointers, according to llvm docs
336325 // Do we need that?
337 const call = codegen.builder.buildCall(llvm_fn, null, 0, "");
326 const call = self.builder.buildCall(llvm_fn, null, 0, "");
338327
339328 if (zig_fn_type.fnReturnType().zigTypeTag() == .NoReturn) {
340 _ = codegen.builder.buildUnreachable();
329 _ = self.builder.buildUnreachable();
341330 }
342331 }
343332 }
344333 }
345334
346 fn generateRetVoid(codegen: *CodeGen, inst: *Inst.NoOp) void {
347 _ = codegen.builder.buildRetVoid();
335 fn genRetVoid(self: *LLVMIRModule, inst: *Inst.NoOp) void {
336 _ = self.builder.buildRetVoid();
348337 }
349338
350 fn generateUnreach(codegen: *CodeGen, inst: *Inst.NoOp) void {
351 _ = codegen.builder.buildUnreachable();
339 fn genUnreach(self: *LLVMIRModule, inst: *Inst.NoOp) void {
340 _ = self.builder.buildUnreachable();
352341 }
353342
354 fn generateBreakpoint(codegen: *CodeGen, inst: *Inst.NoOp) !void {
343 fn genBreakpoint(self: *LLVMIRModule, inst: *Inst.NoOp) !void {
355344 // TODO: Store this function somewhere such that we dont have to add it again
356345 const fn_type = llvm.TypeRef.functionType(llvm.voidType(), null, 0, false);
357 const func = codegen.llvm_module.addFunction("llvm.debugtrap", fn_type);
346 const func = self.llvm_module.addFunction("llvm.debugtrap", fn_type);
358347 // TODO: add assertion: LLVMGetIntrinsicID
359 _ = codegen.builder.buildCall(func, null, 0, "");
348 _ = self.builder.buildCall(func, null, 0, "");
360349 }
361350
362351 /// If the llvm function does not exist, create it
363 fn resolveLLVMFunction(codegen: *CodeGen, func: *Module.Fn) !*const llvm.ValueRef {
352 fn resolveLLVMFunction(self: *LLVMIRModule, func: *Module.Fn) !*const llvm.ValueRef {
364353 // TODO: do we want to store this in our own datastructure?
365 if (codegen.llvm_module.getNamedFunction(func.owner_decl.name)) |llvm_fn| return llvm_fn;
354 if (self.llvm_module.getNamedFunction(func.owner_decl.name)) |llvm_fn| return llvm_fn;
366355
367356 const zig_fn_type = func.owner_decl.typed_value.most_recent.typed_value.ty;
368357 const return_type = zig_fn_type.fnReturnType();
369358
370359 const fn_param_len = zig_fn_type.fnParamLen();
371360
372 const fn_param_types = try codegen.module.gpa.alloc(Type, fn_param_len);
373 defer codegen.module.gpa.free(fn_param_types);
361 const fn_param_types = try self.gpa.alloc(Type, fn_param_len);
362 defer self.gpa.free(fn_param_types);
374363 zig_fn_type.fnParamTypes(fn_param_types);
375364
376 const llvm_param = try codegen.module.gpa.alloc(*const llvm.TypeRef, fn_param_len);
377 defer codegen.module.gpa.free(llvm_param);
365 const llvm_param = try self.gpa.alloc(*const llvm.TypeRef, fn_param_len);
366 defer self.gpa.free(llvm_param);
378367
379368 for (fn_param_types) |fn_param, i| {
380 llvm_param[i] = codegen.getLLVMType(fn_param);
369 llvm_param[i] = self.getLLVMType(fn_param);
381370 }
382371
383372 const fn_type = llvm.TypeRef.functionType(
384 codegen.getLLVMType(return_type),
373 self.getLLVMType(return_type),
385374 if (fn_param_len == 0) null else llvm_param.ptr,
386375 @intCast(c_uint, fn_param_len),
387376 false,
388377 );
389 const llvm_fn = codegen.llvm_module.addFunction(func.owner_decl.name, fn_type);
378 const llvm_fn = self.llvm_module.addFunction(func.owner_decl.name, fn_type);
390379
391380 if (return_type.zigTypeTag() == .NoReturn) {
392381 llvm_fn.addFnAttr("noreturn");
......@@ -395,16 +384,23 @@ const CodeGen = struct {
395384 return llvm_fn;
396385 }
397386
398 fn getLLVMType(codegen: *CodeGen, t: Type) *const llvm.TypeRef {
387 fn getLLVMType(self: *LLVMIRModule, t: Type) *const llvm.TypeRef {
399388 switch (t.zigTypeTag()) {
400389 .Void => return llvm.voidType(),
401390 .NoReturn => return llvm.voidType(),
402391 .Int => {
403 const info = t.intInfo(codegen.module.getTarget());
392 const info = t.intInfo(self.module.getTarget());
404393 return llvm.intType(info.bits);
405394 },
406395 .Bool => return llvm.intType(1),
407396 else => unreachable,
408397 }
409398 }
399
400 pub fn fail(self: *LLVMIRModule, src: usize, comptime format: []const u8, args: anytype) error{ OutOfMemory, CodegenFail } {
401 @setCold(true);
402 std.debug.assert(self.err_msg == null);
403 self.err_msg = try Compilation.ErrorMsg.create(self.gpa, src, format, args);
404 return error.CodegenFail;
405 }
410406};