LCOV - code coverage report
Current view: top level - src - codegen.cpp (source / functions) Hit Total Coverage
Test: coverage.info.cleaned Lines: 5260 6483 81.1 %
Date: 1970-01-01 00:00:01 Functions: 257 281 91.5 %
Branches: 1834 2697 68.0 %

           Branch data     Line data    Source code
       1                 :            : /*
       2                 :            :  * Copyright (c) 2015 Andrew Kelley
       3                 :            :  *
       4                 :            :  * This file is part of zig, which is MIT licensed.
       5                 :            :  * See http://opensource.org/licenses/MIT
       6                 :            :  */
       7                 :            : 
       8                 :            : #include "analyze.hpp"
       9                 :            : #include "ast_render.hpp"
      10                 :            : #include "codegen.hpp"
      11                 :            : #include "compiler.hpp"
      12                 :            : #include "config.h"
      13                 :            : #include "errmsg.hpp"
      14                 :            : #include "error.hpp"
      15                 :            : #include "hash_map.hpp"
      16                 :            : #include "ir.hpp"
      17                 :            : #include "os.hpp"
      18                 :            : #include "translate_c.hpp"
      19                 :            : #include "target.hpp"
      20                 :            : #include "util.hpp"
      21                 :            : #include "zig_llvm.h"
      22                 :            : #include "userland.h"
      23                 :            : 
      24                 :            : #include <stdio.h>
      25                 :            : #include <errno.h>
      26                 :            : 
      27                 :            : enum ResumeId {
      28                 :            :     ResumeIdManual,
      29                 :            :     ResumeIdReturn,
      30                 :            :     ResumeIdCall,
      31                 :            : };
      32                 :            : 
      33                 :          0 : static void init_darwin_native(CodeGen *g) {
      34                 :          0 :     char *osx_target = getenv("MACOSX_DEPLOYMENT_TARGET");
      35                 :          0 :     char *ios_target = getenv("IPHONEOS_DEPLOYMENT_TARGET");
      36                 :            : 
      37                 :            :     // Allow conflicts among OSX and iOS, but choose the default platform.
      38 [ #  # ][ #  # ]:          0 :     if (osx_target && ios_target) {
      39 [ #  # ][ #  # ]:          0 :         if (g->zig_target->arch == ZigLLVM_arm ||
      40         [ #  # ]:          0 :             g->zig_target->arch == ZigLLVM_aarch64 ||
      41                 :          0 :             g->zig_target->arch == ZigLLVM_thumb)
      42                 :            :         {
      43                 :          0 :             osx_target = nullptr;
      44                 :            :         } else {
      45                 :          0 :             ios_target = nullptr;
      46                 :            :         }
      47                 :            :     }
      48                 :            : 
      49         [ #  # ]:          0 :     if (osx_target) {
      50                 :          0 :         g->mmacosx_version_min = buf_create_from_str(osx_target);
      51         [ #  # ]:          0 :     } else if (ios_target) {
      52                 :          0 :         g->mios_version_min = buf_create_from_str(ios_target);
      53         [ #  # ]:          0 :     } else if (g->zig_target->os != OsIOS) {
      54                 :          0 :         g->mmacosx_version_min = buf_create_from_str("10.14");
      55                 :            :     }
      56                 :          0 : }
      57                 :            : 
      58                 :        167 : static ZigPackage *new_package(const char *root_src_dir, const char *root_src_path, const char *pkg_path) {
      59                 :        167 :     ZigPackage *entry = allocate<ZigPackage>(1);
      60                 :        167 :     entry->package_table.init(4);
      61                 :        167 :     buf_init_from_str(&entry->root_src_dir, root_src_dir);
      62                 :        167 :     buf_init_from_str(&entry->root_src_path, root_src_path);
      63                 :        167 :     buf_init_from_str(&entry->pkg_path, pkg_path);
      64                 :        167 :     return entry;
      65                 :            : }
      66                 :            : 
      67                 :          0 : ZigPackage *new_anonymous_package() {
      68                 :          0 :     return new_package("", "", "");
      69                 :            : }
      70                 :            : 
      71                 :            : static const char *symbols_that_llvm_depends_on[] = {
      72                 :            :     "memcpy",
      73                 :            :     "memset",
      74                 :            :     "sqrt",
      75                 :            :     "powi",
      76                 :            :     "sin",
      77                 :            :     "cos",
      78                 :            :     "pow",
      79                 :            :     "exp",
      80                 :            :     "exp2",
      81                 :            :     "log",
      82                 :            :     "log10",
      83                 :            :     "log2",
      84                 :            :     "fma",
      85                 :            :     "fabs",
      86                 :            :     "minnum",
      87                 :            :     "maxnum",
      88                 :            :     "copysign",
      89                 :            :     "floor",
      90                 :            :     "ceil",
      91                 :            :     "trunc",
      92                 :            :     "rint",
      93                 :            :     "nearbyint",
      94                 :            :     "round",
      95                 :            :     // TODO probably all of compiler-rt needs to go here
      96                 :            : };
      97                 :            : 
      98                 :         16 : void codegen_set_clang_argv(CodeGen *g, const char **args, size_t len) {
      99                 :         16 :     g->clang_argv = args;
     100                 :         16 :     g->clang_argv_len = len;
     101                 :         16 : }
     102                 :            : 
     103                 :          0 : void codegen_set_llvm_argv(CodeGen *g, const char **args, size_t len) {
     104                 :          0 :     g->llvm_argv = args;
     105                 :          0 :     g->llvm_argv_len = len;
     106                 :          0 : }
     107                 :            : 
     108                 :          0 : void codegen_set_test_filter(CodeGen *g, Buf *filter) {
     109                 :          0 :     g->test_filter = filter;
     110                 :          0 : }
     111                 :            : 
     112                 :         16 : void codegen_set_test_name_prefix(CodeGen *g, Buf *prefix) {
     113                 :         16 :     g->test_name_prefix = prefix;
     114                 :         16 : }
     115                 :            : 
     116                 :         21 : void codegen_set_lib_version(CodeGen *g, size_t major, size_t minor, size_t patch) {
     117                 :         21 :     g->version_major = major;
     118                 :         21 :     g->version_minor = minor;
     119                 :         21 :     g->version_patch = patch;
     120                 :         21 : }
     121                 :            : 
     122                 :         16 : void codegen_set_emit_file_type(CodeGen *g, EmitFileType emit_file_type) {
     123                 :         16 :     g->emit_file_type = emit_file_type;
     124                 :         16 : }
     125                 :            : 
     126                 :          0 : void codegen_set_each_lib_rpath(CodeGen *g, bool each_lib_rpath) {
     127                 :          0 :     g->each_lib_rpath = each_lib_rpath;
     128                 :          0 : }
     129                 :            : 
     130                 :         79 : void codegen_set_errmsg_color(CodeGen *g, ErrColor err_color) {
     131                 :         79 :     g->err_color = err_color;
     132                 :         79 : }
     133                 :            : 
     134                 :         79 : void codegen_set_strip(CodeGen *g, bool strip) {
     135                 :         79 :     g->strip_debug_symbols = strip;
     136         [ -  + ]:         79 :     if (!target_has_debug_info(g->zig_target)) {
     137                 :          0 :         g->strip_debug_symbols = true;
     138                 :            :     }
     139                 :         79 : }
     140                 :            : 
     141                 :         81 : void codegen_set_out_name(CodeGen *g, Buf *out_name) {
     142                 :         81 :     g->root_out_name = out_name;
     143                 :         81 : }
     144                 :            : 
     145                 :          0 : void codegen_add_lib_dir(CodeGen *g, const char *dir) {
     146                 :          0 :     g->lib_dirs.append(dir);
     147                 :          0 : }
     148                 :            : 
     149                 :          0 : void codegen_add_rpath(CodeGen *g, const char *name) {
     150                 :          0 :     g->rpath_list.append(buf_create_from_str(name));
     151                 :          0 : }
     152                 :            : 
     153                 :         10 : LinkLib *codegen_add_link_lib(CodeGen *g, Buf *name) {
     154                 :         10 :     return add_link_lib(g, name);
     155                 :            : }
     156                 :            : 
     157                 :          0 : void codegen_add_forbidden_lib(CodeGen *codegen, Buf *lib) {
     158                 :          0 :     codegen->forbidden_libs.append(lib);
     159                 :          0 : }
     160                 :            : 
     161                 :          0 : void codegen_add_framework(CodeGen *g, const char *framework) {
     162                 :          0 :     g->darwin_frameworks.append(buf_create_from_str(framework));
     163                 :          0 : }
     164                 :            : 
     165                 :         63 : void codegen_set_mmacosx_version_min(CodeGen *g, Buf *mmacosx_version_min) {
     166                 :         63 :     g->mmacosx_version_min = mmacosx_version_min;
     167                 :         63 : }
     168                 :            : 
     169                 :         63 : void codegen_set_mios_version_min(CodeGen *g, Buf *mios_version_min) {
     170                 :         63 :     g->mios_version_min = mios_version_min;
     171                 :         63 : }
     172                 :            : 
     173                 :         16 : void codegen_set_rdynamic(CodeGen *g, bool rdynamic) {
     174                 :         16 :     g->linker_rdynamic = rdynamic;
     175                 :         16 : }
     176                 :            : 
     177                 :         16 : void codegen_set_linker_script(CodeGen *g, const char *linker_script) {
     178                 :         16 :     g->linker_script = linker_script;
     179                 :         16 : }
     180                 :            : 
     181                 :            : 
     182                 :            : static void render_const_val(CodeGen *g, ConstExprValue *const_val, const char *name);
     183                 :            : static void render_const_val_global(CodeGen *g, ConstExprValue *const_val, const char *name);
     184                 :            : static LLVMValueRef gen_const_val(CodeGen *g, ConstExprValue *const_val, const char *name);
     185                 :            : static void generate_error_name_table(CodeGen *g);
     186                 :            : static bool value_is_all_undef(CodeGen *g, ConstExprValue *const_val);
     187                 :            : static void gen_undef_init(CodeGen *g, uint32_t ptr_align_bytes, ZigType *value_type, LLVMValueRef ptr);
     188                 :            : static LLVMValueRef build_alloca(CodeGen *g, ZigType *type_entry, const char *name, uint32_t alignment);
     189                 :            : 
     190                 :     107134 : static void addLLVMAttr(LLVMValueRef val, LLVMAttributeIndex attr_index, const char *attr_name) {
     191                 :     107134 :     unsigned kind_id = LLVMGetEnumAttributeKindForName(attr_name, strlen(attr_name));
     192                 :     107134 :     assert(kind_id != 0);
     193                 :     107134 :     LLVMAttributeRef llvm_attr = LLVMCreateEnumAttribute(LLVMGetGlobalContext(), kind_id, 0);
     194                 :     107134 :     LLVMAddAttributeAtIndex(val, attr_index, llvm_attr);
     195                 :     107134 : }
     196                 :            : 
     197                 :      24222 : static void addLLVMAttrStr(LLVMValueRef val, LLVMAttributeIndex attr_index,
     198                 :            :         const char *attr_name, const char *attr_val)
     199                 :            : {
     200                 :      24222 :     LLVMAttributeRef llvm_attr = LLVMCreateStringAttribute(LLVMGetGlobalContext(),
     201                 :      24222 :             attr_name, (unsigned)strlen(attr_name), attr_val, (unsigned)strlen(attr_val));
     202                 :      24222 :     LLVMAddAttributeAtIndex(val, attr_index, llvm_attr);
     203                 :      24222 : }
     204                 :            : 
     205                 :      17599 : static void addLLVMAttrInt(LLVMValueRef val, LLVMAttributeIndex attr_index,
     206                 :            :         const char *attr_name, uint64_t attr_val)
     207                 :            : {
     208                 :      17599 :     unsigned kind_id = LLVMGetEnumAttributeKindForName(attr_name, strlen(attr_name));
     209                 :      17599 :     assert(kind_id != 0);
     210                 :      17599 :     LLVMAttributeRef llvm_attr = LLVMCreateEnumAttribute(LLVMGetGlobalContext(), kind_id, attr_val);
     211                 :      17599 :     LLVMAddAttributeAtIndex(val, attr_index, llvm_attr);
     212                 :      17599 : }
     213                 :            : 
     214                 :      62699 : static void addLLVMFnAttr(LLVMValueRef fn_val, const char *attr_name) {
     215                 :      62699 :     return addLLVMAttr(fn_val, -1, attr_name);
     216                 :            : }
     217                 :            : 
     218                 :      24222 : static void addLLVMFnAttrStr(LLVMValueRef fn_val, const char *attr_name, const char *attr_val) {
     219                 :      24222 :     return addLLVMAttrStr(fn_val, -1, attr_name, attr_val);
     220                 :            : }
     221                 :            : 
     222                 :         10 : static void addLLVMFnAttrInt(LLVMValueRef fn_val, const char *attr_name, uint64_t attr_val) {
     223                 :         10 :     return addLLVMAttrInt(fn_val, -1, attr_name, attr_val);
     224                 :            : }
     225                 :            : 
     226                 :      43964 : static void addLLVMArgAttr(LLVMValueRef fn_val, unsigned param_index, const char *attr_name) {
     227                 :      43964 :     return addLLVMAttr(fn_val, param_index + 1, attr_name);
     228                 :            : }
     229                 :            : 
     230                 :      17589 : static void addLLVMArgAttrInt(LLVMValueRef fn_val, unsigned param_index, const char *attr_name, uint64_t attr_val) {
     231                 :      17589 :     return addLLVMAttrInt(fn_val, param_index + 1, attr_name, attr_val);
     232                 :            : }
     233                 :            : 
     234                 :      23331 : static bool is_symbol_available(CodeGen *g, Buf *name) {
     235 [ +  + ][ +  - ]:      23331 :     return g->exported_symbol_names.maybe_get(name) == nullptr && g->external_prototypes.maybe_get(name) == nullptr;
     236                 :            : }
     237                 :            : 
     238                 :      23319 : static Buf *get_mangled_name(CodeGen *g, Buf *original_name, bool external_linkage) {
     239 [ +  - ][ +  + ]:      23319 :     if (external_linkage || is_symbol_available(g, original_name)) {
                 [ +  + ]
     240                 :      23307 :         return original_name;
     241                 :            :     }
     242                 :            : 
     243                 :         12 :     int n = 0;
     244                 :          0 :     for (;; n += 1) {
     245                 :         12 :         Buf *new_name = buf_sprintf("%s.%d", buf_ptr(original_name), n);
     246         [ +  - ]:         12 :         if (is_symbol_available(g, new_name)) {
     247                 :         12 :             return new_name;
     248                 :            :         }
     249                 :          0 :     }
     250                 :            : }
     251                 :            : 
     252                 :     103868 : static LLVMCallConv get_llvm_cc(CodeGen *g, CallingConvention cc) {
     253   [ +  +  -  -  :     103868 :     switch (cc) {
                +  +  - ]
     254                 :      99217 :         case CallingConventionUnspecified: return LLVMFastCallConv;
     255                 :       4225 :         case CallingConventionC: return LLVMCCallConv;
     256                 :          0 :         case CallingConventionCold:
     257                 :            :             // cold calling convention only works on x86.
     258 [ #  # ][ #  # ]:          0 :             if (g->zig_target->arch == ZigLLVM_x86 ||
     259                 :          0 :                 g->zig_target->arch == ZigLLVM_x86_64)
     260                 :            :             {
     261                 :            :                 // cold calling convention is not supported on windows
     262         [ #  # ]:          0 :                 if (g->zig_target->os == OsWindows) {
     263                 :          0 :                     return LLVMCCallConv;
     264                 :            :                 } else {
     265                 :          0 :                     return LLVMColdCallConv;
     266                 :            :                 }
     267                 :            :             } else {
     268                 :          0 :                 return LLVMCCallConv;
     269                 :            :             }
     270                 :            :             break;
     271                 :          0 :         case CallingConventionNaked:
     272                 :          0 :             zig_unreachable();
     273                 :        146 :         case CallingConventionStdcall:
     274                 :            :             // stdcall calling convention only works on x86.
     275         [ -  + ]:        146 :             if (g->zig_target->arch == ZigLLVM_x86) {
     276                 :          0 :                 return LLVMX86StdcallCallConv;
     277                 :            :             } else {
     278                 :        146 :                 return LLVMCCallConv;
     279                 :            :             }
     280                 :        280 :         case CallingConventionAsync:
     281                 :        280 :             return LLVMFastCallConv;
     282                 :            :     }
     283                 :          0 :     zig_unreachable();
     284                 :            : }
     285                 :            : 
     286                 :      24454 : static void add_uwtable_attr(CodeGen *g, LLVMValueRef fn_val) {
     287         [ +  + ]:      24454 :     if (g->zig_target->os == OsWindows) {
     288                 :       4724 :         addLLVMFnAttr(fn_val, "uwtable");
     289                 :            :     }
     290                 :      24454 : }
     291                 :            : 
     292                 :      24420 : static LLVMLinkage to_llvm_linkage(GlobalLinkageId id) {
     293   [ +  +  +  -  :      24420 :     switch (id) {
                      - ]
     294                 :      20345 :         case GlobalLinkageIdInternal:
     295                 :      20345 :             return LLVMInternalLinkage;
     296                 :       3685 :         case GlobalLinkageIdStrong:
     297                 :       3685 :             return LLVMExternalLinkage;
     298                 :        390 :         case GlobalLinkageIdWeak:
     299                 :        390 :             return LLVMWeakODRLinkage;
     300                 :          0 :         case GlobalLinkageIdLinkOnce:
     301                 :          0 :             return LLVMLinkOnceODRLinkage;
     302                 :            :     }
     303                 :          0 :     zig_unreachable();
     304                 :            : }
     305                 :            : 
     306                 :            : // label (grep this): [fn_frame_struct_layout]
     307                 :       5296 : static uint32_t frame_index_trace_arg(CodeGen *g, ZigType *return_type) {
     308                 :            :     // [0] *ReturnType (callee's)
     309                 :            :     // [1] *ReturnType (awaiter's)
     310                 :            :     // [2] ReturnType
     311         [ +  + ]:       5296 :     uint32_t return_field_count = type_has_bits(return_type) ? 3 : 0;
     312                 :       5296 :     return frame_ret_start + return_field_count;
     313                 :            : }
     314                 :            : 
     315                 :            : // label (grep this): [fn_frame_struct_layout]
     316                 :       2128 : static uint32_t frame_index_arg(CodeGen *g, ZigType *return_type) {
     317                 :       2128 :     bool have_stack_trace = codegen_fn_has_err_ret_tracing_arg(g, return_type);
     318                 :            :     // [0] *StackTrace (callee's)
     319                 :            :     // [1] *StackTrace (awaiter's)
     320         [ +  + ]:       2128 :     uint32_t trace_field_count = have_stack_trace ? 2 : 0;
     321                 :       2128 :     return frame_index_trace_arg(g, return_type) + trace_field_count;
     322                 :            : }
     323                 :            : 
     324                 :            : // label (grep this): [fn_frame_struct_layout]
     325                 :        448 : static uint32_t frame_index_trace_stack(CodeGen *g, FnTypeId *fn_type_id) {
     326                 :        448 :     uint32_t result = frame_index_arg(g, fn_type_id->return_type);
     327         [ +  + ]:        752 :     for (size_t i = 0; i < fn_type_id->param_count; i += 1) {
     328         [ +  - ]:        304 :         if (type_has_bits(fn_type_id->param_info->type)) {
     329                 :        304 :             result += 1;
     330                 :            :         }
     331                 :            :     }
     332                 :        448 :     return result;
     333                 :            : }
     334                 :            : 
     335                 :            : 
     336                 :      47876 : static uint32_t get_err_ret_trace_arg_index(CodeGen *g, ZigFn *fn_table_entry) {
     337         [ -  + ]:      47876 :     if (!g->have_err_ret_tracing) {
     338                 :          0 :         return UINT32_MAX;
     339                 :            :     }
     340         [ +  + ]:      47876 :     if (fn_is_async(fn_table_entry)) {
     341                 :        824 :         return UINT32_MAX;
     342                 :            :     }
     343                 :      47052 :     ZigType *fn_type = fn_table_entry->type_entry;
     344         [ +  + ]:      47052 :     if (!fn_type_can_fail(&fn_type->data.fn.fn_type_id)) {
     345                 :      25350 :         return UINT32_MAX;
     346                 :            :     }
     347                 :      21702 :     ZigType *return_type = fn_type->data.fn.fn_type_id.return_type;
     348 [ +  - ][ +  + ]:      21702 :     bool first_arg_ret = type_has_bits(return_type) && handle_is_ptr(return_type);
     349         [ +  + ]:      21702 :     return first_arg_ret ? 1 : 0;
     350                 :            : }
     351                 :            : 
     352                 :      24320 : static void maybe_export_dll(CodeGen *g, LLVMValueRef global_value, GlobalLinkageId linkage) {
     353 [ +  + ][ +  + ]:      24320 :     if (linkage != GlobalLinkageIdInternal && g->zig_target->os == OsWindows && g->is_dynamic) {
                 [ -  + ]
     354                 :          0 :         LLVMSetDLLStorageClass(global_value, LLVMDLLExportStorageClass);
     355                 :            :     }
     356                 :      24320 : }
     357                 :            : 
     358                 :        100 : static void maybe_import_dll(CodeGen *g, LLVMValueRef global_value, GlobalLinkageId linkage) {
     359         [ +  - ]:        100 :     if (linkage != GlobalLinkageIdInternal && g->zig_target->os == OsWindows) {
     360                 :            :         // TODO come up with a good explanation/understanding for why we never do
     361                 :            :         // DLLImportStorageClass. Empirically it only causes problems. But let's have
     362                 :            :         // this documented and then clean up the code accordingly.
     363                 :            :         //LLVMSetDLLStorageClass(global_value, LLVMDLLImportStorageClass);
     364                 :            :     }
     365                 :        100 : }
     366                 :            : 
     367                 :       2937 : static bool cc_want_sret_attr(CallingConvention cc) {
     368   [ -  -  +  - ]:       2937 :     switch (cc) {
     369                 :          0 :         case CallingConventionNaked:
     370                 :          0 :             zig_unreachable();
     371                 :          0 :         case CallingConventionC:
     372                 :            :         case CallingConventionCold:
     373                 :            :         case CallingConventionStdcall:
     374                 :          0 :             return true;
     375                 :       2937 :         case CallingConventionAsync:
     376                 :            :         case CallingConventionUnspecified:
     377                 :       2937 :             return false;
     378                 :            :     }
     379                 :          0 :     zig_unreachable();
     380                 :            : }
     381                 :            : 
     382                 :      24481 : static bool codegen_have_frame_pointer(CodeGen *g) {
     383                 :      24481 :     return g->build_mode == BuildModeDebug;
     384                 :            : }
     385                 :            : 
     386                 :      24412 : static LLVMValueRef make_fn_llvm_value(CodeGen *g, ZigFn *fn) {
     387                 :      24412 :     Buf *unmangled_name = &fn->symbol_name;
     388                 :            :     Buf *symbol_name;
     389                 :            :     GlobalLinkageId linkage;
     390         [ +  + ]:      24412 :     if (fn->body_node == nullptr) {
     391                 :        116 :         symbol_name = unmangled_name;
     392                 :        116 :         linkage = GlobalLinkageIdStrong;
     393         [ +  + ]:      24296 :     } else if (fn->export_list.length == 0) {
     394                 :      20337 :         symbol_name = get_mangled_name(g, unmangled_name, false);
     395                 :      20337 :         linkage = GlobalLinkageIdInternal;
     396                 :            :     } else {
     397                 :       3959 :         GlobalExport *fn_export = &fn->export_list.items[0];
     398                 :       3959 :         symbol_name = &fn_export->name;
     399                 :       3959 :         linkage = fn_export->linkage;
     400                 :            :     }
     401                 :            : 
     402                 :      24412 :     bool external_linkage = linkage != GlobalLinkageIdInternal;
     403                 :      24412 :     CallingConvention cc = fn->type_entry->data.fn.fn_type_id.cc;
     404 [ +  + ][ +  + ]:      24412 :     if (cc == CallingConventionStdcall && external_linkage &&
                 [ -  + ]
     405                 :         50 :         g->zig_target->arch == ZigLLVM_x86)
     406                 :            :     {
     407                 :            :         // prevent llvm name mangling
     408                 :          0 :         symbol_name = buf_sprintf("\x01_%s", buf_ptr(symbol_name));
     409                 :            :     }
     410                 :            : 
     411                 :      24412 :     bool is_async = fn_is_async(fn);
     412                 :            : 
     413                 :            : 
     414                 :      24412 :     ZigType *fn_type = fn->type_entry;
     415                 :            :     // Make the raw_type_ref populated
     416                 :      24412 :     resolve_llvm_types_fn(g, fn);
     417                 :      24412 :     LLVMTypeRef fn_llvm_type = fn->raw_type_ref;
     418                 :      24412 :     LLVMValueRef llvm_fn = nullptr;
     419         [ +  + ]:      24412 :     if (fn->body_node == nullptr) {
     420                 :        116 :         LLVMValueRef existing_llvm_fn = LLVMGetNamedFunction(g->module, buf_ptr(symbol_name));
     421         [ +  + ]:        116 :         if (existing_llvm_fn) {
     422                 :          8 :             return LLVMConstBitCast(existing_llvm_fn, LLVMPointerType(fn_llvm_type, 0));
     423                 :            :         } else {
     424                 :        108 :             auto entry = g->exported_symbol_names.maybe_get(symbol_name);
     425         [ +  + ]:        108 :             if (entry == nullptr) {
     426                 :        100 :                 llvm_fn = LLVMAddFunction(g->module, buf_ptr(symbol_name), fn_llvm_type);
     427                 :            : 
     428         [ -  + ]:        100 :                 if (target_is_wasm(g->zig_target)) {
     429                 :          0 :                     assert(fn->proto_node->type == NodeTypeFnProto);
     430                 :          0 :                     AstNodeFnProto *fn_proto = &fn->proto_node->data.fn_proto;
     431 [ #  # ][ #  # ]:          0 :                     if (fn_proto-> is_extern && fn_proto->lib_name != nullptr ) {
     432                 :        100 :                         addLLVMFnAttrStr(llvm_fn, "wasm-import-module", buf_ptr(fn_proto->lib_name));
     433                 :            :                     }
     434                 :            :                 }
     435                 :            :             } else {
     436                 :          8 :                 assert(entry->value->id == TldIdFn);
     437                 :          8 :                 TldFn *tld_fn = reinterpret_cast<TldFn *>(entry->value);
     438                 :            :                 // Make the raw_type_ref populated
     439                 :          8 :                 resolve_llvm_types_fn(g, tld_fn->fn_entry);
     440                 :          8 :                 tld_fn->fn_entry->llvm_value = LLVMAddFunction(g->module, buf_ptr(symbol_name),
     441                 :          8 :                         tld_fn->fn_entry->raw_type_ref);
     442                 :          8 :                 llvm_fn = LLVMConstBitCast(tld_fn->fn_entry->llvm_value, LLVMPointerType(fn_llvm_type, 0));
     443                 :        108 :                 return llvm_fn;
     444                 :            :             }
     445                 :            :         }
     446                 :            :     } else {
     447         [ +  - ]:      24296 :         if (llvm_fn == nullptr) {
     448                 :      24296 :             llvm_fn = LLVMAddFunction(g->module, buf_ptr(symbol_name), fn_llvm_type);
     449                 :            :         }
     450                 :            : 
     451         [ +  + ]:      24332 :         for (size_t i = 1; i < fn->export_list.length; i += 1) {
     452                 :         36 :             GlobalExport *fn_export = &fn->export_list.items[i];
     453                 :         36 :             LLVMAddAlias(g->module, LLVMTypeOf(llvm_fn), llvm_fn, buf_ptr(&fn_export->name));
     454                 :            :         }
     455                 :            :     }
     456                 :            : 
     457   [ +  -  +  - ]:      24396 :     switch (fn->fn_inline) {
     458                 :         46 :         case FnInlineAlways:
     459                 :         46 :             addLLVMFnAttr(llvm_fn, "alwaysinline");
     460                 :         46 :             g->inline_fns.append(fn);
     461                 :         46 :             break;
     462                 :          0 :         case FnInlineNever:
     463                 :          0 :             addLLVMFnAttr(llvm_fn, "noinline");
     464                 :          0 :             break;
     465                 :      24350 :         case FnInlineAuto:
     466         [ +  + ]:      24350 :             if (fn->alignstack_value != 0) {
     467                 :         10 :                 addLLVMFnAttr(llvm_fn, "noinline");
     468                 :            :             }
     469                 :      24350 :             break;
     470                 :            :     }
     471                 :            : 
     472         [ +  + ]:      24396 :     if (cc == CallingConventionNaked) {
     473                 :         16 :         addLLVMFnAttr(llvm_fn, "naked");
     474                 :            :     } else {
     475                 :      24380 :         LLVMSetFunctionCallConv(llvm_fn, get_llvm_cc(g, fn_type->data.fn.fn_type_id.cc));
     476                 :            :     }
     477                 :            : 
     478 [ +  + ][ -  + ]:      24396 :     bool want_cold = fn->is_cold || cc == CallingConventionCold;
     479         [ +  + ]:      24396 :     if (want_cold) {
     480                 :        281 :         ZigLLVMAddFunctionAttrCold(llvm_fn);
     481                 :            :     }
     482                 :            : 
     483                 :            : 
     484                 :      24396 :     LLVMSetLinkage(llvm_fn, to_llvm_linkage(linkage));
     485                 :            : 
     486         [ +  + ]:      24396 :     if (linkage == GlobalLinkageIdInternal) {
     487                 :      20345 :         LLVMSetUnnamedAddr(llvm_fn, true);
     488                 :            :     }
     489                 :            : 
     490                 :      24396 :     ZigType *return_type = fn_type->data.fn.fn_type_id.return_type;
     491         [ +  + ]:      24396 :     if (return_type->id == ZigTypeIdUnreachable) {
     492                 :        334 :         addLLVMFnAttr(llvm_fn, "noreturn");
     493                 :            :     }
     494                 :            : 
     495         [ +  + ]:      24396 :     if (fn->body_node != nullptr) {
     496                 :      24296 :         maybe_export_dll(g, llvm_fn, linkage);
     497                 :            : 
     498         [ +  - ]:      24296 :         bool want_fn_safety = g->build_mode != BuildModeFastRelease &&
     499 [ +  + ][ +  - ]:      48592 :                               g->build_mode != BuildModeSmallRelease &&
     500                 :      24296 :                               !fn->def_scope->safety_off;
     501         [ +  + ]:      24296 :         if (want_fn_safety) {
     502         [ +  + ]:      23829 :             if (g->libc_link_lib != nullptr) {
     503                 :       8674 :                 addLLVMFnAttr(llvm_fn, "sspstrong");
     504                 :       8674 :                 addLLVMFnAttrStr(llvm_fn, "stack-protector-buffer-size", "4");
     505                 :            :             }
     506                 :            :         }
     507 [ +  + ][ +  + ]:      24296 :         if (g->have_stack_probing && !fn->def_scope->safety_off) {
     508                 :      24296 :             addLLVMFnAttrStr(llvm_fn, "probe-stack", "__zig_probe_stack");
     509                 :            :         }
     510                 :            :     } else {
     511                 :        100 :         maybe_import_dll(g, llvm_fn, linkage);
     512                 :            :     }
     513                 :            : 
     514         [ +  + ]:      24396 :     if (fn->alignstack_value != 0) {
     515                 :         10 :         addLLVMFnAttrInt(llvm_fn, "alignstack", fn->alignstack_value);
     516                 :            :     }
     517                 :            : 
     518                 :      24396 :     addLLVMFnAttr(llvm_fn, "nounwind");
     519                 :      24396 :     add_uwtable_attr(g, llvm_fn);
     520                 :      24396 :     addLLVMFnAttr(llvm_fn, "nobuiltin");
     521 [ +  + ][ +  + ]:      24396 :     if (codegen_have_frame_pointer(g) && fn->fn_inline != FnInlineAlways) {
                 [ +  - ]
     522                 :      24350 :         ZigLLVMAddFunctionAttr(llvm_fn, "no-frame-pointer-elim", "true");
     523                 :      24350 :         ZigLLVMAddFunctionAttr(llvm_fn, "no-frame-pointer-elim-non-leaf", nullptr);
     524                 :            :     }
     525         [ -  + ]:      24396 :     if (fn->section_name) {
     526                 :          0 :         LLVMSetSection(llvm_fn, buf_ptr(fn->section_name));
     527                 :            :     }
     528         [ +  + ]:      24396 :     if (fn->align_bytes > 0) {
     529                 :         24 :         LLVMSetAlignment(llvm_fn, (unsigned)fn->align_bytes);
     530                 :            :     } else {
     531                 :            :         // We'd like to set the best alignment for the function here, but on Darwin LLVM gives
     532                 :            :         // "Cannot getTypeInfo() on a type that is unsized!" assertion failure when calling
     533                 :            :         // any of the functions for getting alignment. Not specifying the alignment should
     534                 :            :         // use the ABI alignment, which is fine.
     535                 :            :     }
     536                 :            : 
     537         [ +  + ]:      24396 :     if (is_async) {
     538                 :        824 :         addLLVMArgAttr(llvm_fn, 0, "nonnull");
     539                 :            :     } else {
     540                 :      23572 :         unsigned init_gen_i = 0;
     541         [ +  + ]:      23572 :         if (!type_has_bits(return_type)) {
     542                 :            :             // nothing to do
     543         [ +  + ]:      15917 :         } else if (type_is_nonnull_ptr(return_type)) {
     544                 :        471 :             addLLVMAttr(llvm_fn, 0, "nonnull");
     545         [ +  + ]:      15446 :         } else if (want_first_arg_sret(g, &fn_type->data.fn.fn_type_id)) {
     546                 :            :             // Sret pointers must not be address 0
     547                 :       2937 :             addLLVMArgAttr(llvm_fn, 0, "nonnull");
     548                 :       2937 :             addLLVMArgAttr(llvm_fn, 0, "sret");
     549         [ -  + ]:       2937 :             if (cc_want_sret_attr(cc)) {
     550                 :          0 :                 addLLVMArgAttr(llvm_fn, 0, "noalias");
     551                 :            :             }
     552                 :       2937 :             init_gen_i = 1;
     553                 :            :         }
     554                 :            : 
     555                 :            :         // set parameter attributes
     556                 :      23572 :         FnWalk fn_walk = {};
     557                 :      23572 :         fn_walk.id = FnWalkIdAttrs;
     558                 :      23572 :         fn_walk.data.attrs.fn = fn;
     559                 :      23572 :         fn_walk.data.attrs.llvm_fn = llvm_fn;
     560                 :      23572 :         fn_walk.data.attrs.gen_i = init_gen_i;
     561                 :      23572 :         walk_function_params(g, fn_type, &fn_walk);
     562                 :            : 
     563                 :      23572 :         uint32_t err_ret_trace_arg_index = get_err_ret_trace_arg_index(g, fn);
     564         [ +  + ]:      23572 :         if (err_ret_trace_arg_index != UINT32_MAX) {
     565                 :            :             // Error return trace memory is in the stack, which is impossible to be at address 0
     566                 :            :             // on any architecture.
     567                 :      23572 :             addLLVMArgAttr(llvm_fn, (unsigned)err_ret_trace_arg_index, "nonnull");
     568                 :            :         }
     569                 :            :     }
     570                 :            : 
     571                 :      24412 :     return llvm_fn;
     572                 :            : }
     573                 :            : 
     574                 :     144668 : static LLVMValueRef fn_llvm_value(CodeGen *g, ZigFn *fn) {
     575         [ +  + ]:     144668 :     if (fn->llvm_value)
     576                 :     120256 :         return fn->llvm_value;
     577                 :            : 
     578                 :      24412 :     fn->llvm_value = make_fn_llvm_value(g, fn);
     579                 :      24412 :     fn->llvm_name = strdup(LLVMGetValueName(fn->llvm_value));
     580                 :      24412 :     return fn->llvm_value;
     581                 :            : }
     582                 :            : 
     583                 :    2378312 : static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) {
     584         [ +  + ]:    2378312 :     if (scope->di_scope)
     585                 :     679274 :         return scope->di_scope;
     586                 :            : 
     587                 :    1699038 :     ZigType *import = get_scope_import(scope);
     588   [ -  +  +  +  :    1699038 :     switch (scope->id) {
                   +  - ]
     589                 :          0 :         case ScopeIdCImport:
     590                 :          0 :             zig_unreachable();
     591                 :      24304 :         case ScopeIdFnDef:
     592                 :            :         {
     593                 :      24304 :             assert(scope->parent);
     594                 :      24304 :             ScopeFnDef *fn_scope = (ScopeFnDef *)scope;
     595                 :      24304 :             ZigFn *fn_table_entry = fn_scope->fn_entry;
     596         [ -  + ]:      24304 :             if (!fn_table_entry->proto_node)
     597                 :          0 :                 return get_di_scope(g, scope->parent);
     598         [ +  + ]:      24304 :             unsigned line_number = (unsigned)(fn_table_entry->proto_node->line == 0) ?
     599                 :      24280 :                 0 : (fn_table_entry->proto_node->line + 1);
     600                 :      24304 :             unsigned scope_line = line_number;
     601                 :      24304 :             bool is_definition = fn_table_entry->body_node != nullptr;
     602                 :      24304 :             bool is_optimized = g->build_mode != BuildModeDebug;
     603 [ +  - ][ +  + ]:      24304 :             bool is_internal_linkage = (fn_table_entry->body_node != nullptr &&
     604                 :      24304 :                     fn_table_entry->export_list.length == 0);
     605                 :      24304 :             unsigned flags = ZigLLVM_DIFlags_StaticMember;
     606                 :      24304 :             ZigLLVMDIScope *fn_di_scope = get_di_scope(g, scope->parent);
     607                 :      24304 :             assert(fn_di_scope != nullptr);
     608                 :      24304 :             assert(fn_table_entry->raw_di_type != nullptr);
     609                 :      72912 :             ZigLLVMDISubprogram *subprogram = ZigLLVMCreateFunction(g->dbuilder,
     610                 :      24304 :                 fn_di_scope, buf_ptr(&fn_table_entry->symbol_name), "",
     611                 :      24304 :                 import->data.structure.root_struct->di_file, line_number,
     612                 :            :                 fn_table_entry->raw_di_type, is_internal_linkage,
     613                 :      24304 :                 is_definition, scope_line, flags, is_optimized, nullptr);
     614                 :            : 
     615                 :      24304 :             scope->di_scope = ZigLLVMSubprogramToScope(subprogram);
     616         [ +  - ]:      24304 :             if (!g->strip_debug_symbols) {
     617                 :      24304 :                 ZigLLVMFnSetSubprogram(fn_llvm_value(g, fn_table_entry), subprogram);
     618                 :            :             }
     619                 :      24304 :             return scope->di_scope;
     620                 :            :         }
     621                 :       3227 :         case ScopeIdDecls:
     622         [ +  + ]:       3227 :             if (scope->parent) {
     623                 :       1649 :                 ScopeDecls *decls_scope = (ScopeDecls *)scope;
     624                 :       1649 :                 assert(decls_scope->container_type);
     625                 :       1649 :                 scope->di_scope = ZigLLVMTypeToScope(get_llvm_di_type(g, decls_scope->container_type));
     626                 :            :             } else {
     627                 :       1578 :                 scope->di_scope = ZigLLVMFileToScope(import->data.structure.root_struct->di_file);
     628                 :            :             }
     629                 :       3227 :             return scope->di_scope;
     630                 :      36915 :         case ScopeIdBlock:
     631                 :            :         case ScopeIdDefer:
     632                 :            :         {
     633                 :      36915 :             assert(scope->parent);
     634                 :      36915 :             ZigLLVMDILexicalBlock *di_block = ZigLLVMCreateLexicalBlock(g->dbuilder,
     635                 :            :                 get_di_scope(g, scope->parent),
     636                 :      36915 :                 import->data.structure.root_struct->di_file,
     637                 :      36915 :                 (unsigned)scope->source_node->line + 1,
     638                 :      36915 :                 (unsigned)scope->source_node->column + 1);
     639                 :      36915 :             scope->di_scope = ZigLLVMLexicalBlockToScope(di_block);
     640                 :      36915 :             return scope->di_scope;
     641                 :            :         }
     642                 :    1634592 :         case ScopeIdVarDecl:
     643                 :            :         case ScopeIdDeferExpr:
     644                 :            :         case ScopeIdLoop:
     645                 :            :         case ScopeIdSuspend:
     646                 :            :         case ScopeIdCompTime:
     647                 :            :         case ScopeIdRuntime:
     648                 :            :         case ScopeIdTypeOf:
     649                 :    1634592 :             return get_di_scope(g, scope->parent);
     650                 :            :     }
     651                 :          0 :     zig_unreachable();
     652                 :            : }
     653                 :            : 
     654                 :      42523 : static void clear_debug_source_node(CodeGen *g) {
     655                 :      42523 :     ZigLLVMClearCurrentDebugLocation(g->builder);
     656                 :      42523 : }
     657                 :            : 
     658                 :        264 : static LLVMValueRef get_arithmetic_overflow_fn(CodeGen *g, ZigType *operand_type,
     659                 :            :         const char *signed_name, const char *unsigned_name)
     660                 :            : {
     661         [ -  + ]:        264 :     ZigType *int_type = (operand_type->id == ZigTypeIdVector) ? operand_type->data.vector.elem_type : operand_type;
     662                 :            :     char fn_name[64];
     663                 :            : 
     664                 :        264 :     assert(int_type->id == ZigTypeIdInt);
     665         [ +  + ]:        264 :     const char *signed_str = int_type->data.integral.is_signed ? signed_name : unsigned_name;
     666                 :            : 
     667                 :            :     LLVMTypeRef param_types[] = {
     668                 :        264 :         get_llvm_type(g, operand_type),
     669                 :        264 :         get_llvm_type(g, operand_type),
     670                 :        528 :     };
     671                 :            : 
     672         [ -  + ]:        264 :     if (operand_type->id == ZigTypeIdVector) {
     673                 :          0 :         sprintf(fn_name, "llvm.%s.with.overflow.v%" PRIu32 "i%" PRIu32, signed_str,
     674                 :            :                 operand_type->data.vector.len, int_type->data.integral.bit_count);
     675                 :            : 
     676                 :            :         LLVMTypeRef return_elem_types[] = {
     677                 :          0 :             get_llvm_type(g, operand_type),
     678                 :          0 :             LLVMVectorType(LLVMInt1Type(), operand_type->data.vector.len),
     679                 :          0 :         };
     680                 :          0 :         LLVMTypeRef return_struct_type = LLVMStructType(return_elem_types, 2, false);
     681                 :          0 :         LLVMTypeRef fn_type = LLVMFunctionType(return_struct_type, param_types, 2, false);
     682                 :          0 :         LLVMValueRef fn_val = LLVMAddFunction(g->module, fn_name, fn_type);
     683                 :          0 :         assert(LLVMGetIntrinsicID(fn_val));
     684                 :          0 :         return fn_val;
     685                 :            :     } else {
     686                 :        264 :         sprintf(fn_name, "llvm.%s.with.overflow.i%" PRIu32, signed_str, int_type->data.integral.bit_count);
     687                 :            : 
     688                 :            :         LLVMTypeRef return_elem_types[] = {
     689                 :        264 :             get_llvm_type(g, operand_type),
     690                 :        264 :             LLVMInt1Type(),
     691                 :        528 :         };
     692                 :        264 :         LLVMTypeRef return_struct_type = LLVMStructType(return_elem_types, 2, false);
     693                 :        264 :         LLVMTypeRef fn_type = LLVMFunctionType(return_struct_type, param_types, 2, false);
     694                 :        264 :         LLVMValueRef fn_val = LLVMAddFunction(g->module, fn_name, fn_type);
     695                 :        264 :         assert(LLVMGetIntrinsicID(fn_val));
     696                 :        264 :         return fn_val;
     697                 :            :     }
     698                 :            : }
     699                 :            : 
     700                 :       6156 : static LLVMValueRef get_int_overflow_fn(CodeGen *g, ZigType *operand_type, AddSubMul add_sub_mul) {
     701         [ -  + ]:       6156 :     ZigType *int_type = (operand_type->id == ZigTypeIdVector) ? operand_type->data.vector.elem_type : operand_type;
     702                 :       6156 :     assert(int_type->id == ZigTypeIdInt);
     703                 :            : 
     704                 :       6156 :     ZigLLVMFnKey key = {};
     705                 :       6156 :     key.id = ZigLLVMFnIdOverflowArithmetic;
     706                 :       6156 :     key.data.overflow_arithmetic.is_signed = int_type->data.integral.is_signed;
     707                 :       6156 :     key.data.overflow_arithmetic.add_sub_mul = add_sub_mul;
     708                 :       6156 :     key.data.overflow_arithmetic.bit_count = (uint32_t)int_type->data.integral.bit_count;
     709         [ -  + ]:       6156 :     key.data.overflow_arithmetic.vector_len = (operand_type->id == ZigTypeIdVector) ?
     710                 :            :         operand_type->data.vector.len : 0;
     711                 :            : 
     712                 :       6156 :     auto existing_entry = g->llvm_fn_table.maybe_get(key);
     713         [ +  + ]:       6156 :     if (existing_entry)
     714                 :       5892 :         return existing_entry->value;
     715                 :            : 
     716                 :            :     LLVMValueRef fn_val;
     717   [ +  +  +  - ]:        264 :     switch (add_sub_mul) {
     718                 :        117 :         case AddSubMulAdd:
     719                 :        117 :             fn_val = get_arithmetic_overflow_fn(g, operand_type, "sadd", "uadd");
     720                 :        117 :             break;
     721                 :         96 :         case AddSubMulSub:
     722                 :         96 :             fn_val = get_arithmetic_overflow_fn(g, operand_type, "ssub", "usub");
     723                 :         96 :             break;
     724                 :         51 :         case AddSubMulMul:
     725                 :         51 :             fn_val = get_arithmetic_overflow_fn(g, operand_type, "smul", "umul");
     726                 :         51 :             break;
     727                 :            :     }
     728                 :            : 
     729                 :        264 :     g->llvm_fn_table.put(key, fn_val);
     730                 :       6156 :     return fn_val;
     731                 :            : }
     732                 :            : 
     733                 :        368 : static LLVMValueRef get_float_fn(CodeGen *g, ZigType *type_entry, ZigLLVMFnId fn_id, BuiltinFnId op) {
     734 [ -  + ][ #  # ]:        368 :     assert(type_entry->id == ZigTypeIdFloat ||
     735                 :          0 :            type_entry->id == ZigTypeIdVector);
     736                 :            : 
     737                 :        368 :     bool is_vector = (type_entry->id == ZigTypeIdVector);
     738         [ -  + ]:        368 :     ZigType *float_type = is_vector ? type_entry->data.vector.elem_type : type_entry;
     739                 :            : 
     740                 :        368 :     ZigLLVMFnKey key = {};
     741                 :        368 :     key.id = fn_id;
     742                 :        368 :     key.data.floating.bit_count = (uint32_t)float_type->data.floating.bit_count;
     743         [ -  + ]:        368 :     key.data.floating.vector_len = is_vector ? (uint32_t)type_entry->data.vector.len : 0;
     744                 :        368 :     key.data.floating.op = op;
     745                 :            : 
     746                 :        368 :     auto existing_entry = g->llvm_fn_table.maybe_get(key);
     747         [ +  + ]:        368 :     if (existing_entry)
     748                 :        128 :         return existing_entry->value;
     749                 :            : 
     750                 :            :     const char *name;
     751                 :            :     uint32_t num_args;
     752         [ +  + ]:        240 :     if (fn_id == ZigLLVMFnIdFMA) {
     753                 :         24 :         name = "fma";
     754                 :         24 :         num_args = 3;
     755         [ +  - ]:        216 :     } else if (fn_id == ZigLLVMFnIdFloatOp) {
     756                 :        216 :         name = float_op_to_name(op, true);
     757                 :        216 :         num_args = 1;
     758                 :            :     } else {
     759                 :          0 :         zig_unreachable();
     760                 :            :     }
     761                 :            : 
     762                 :            :     char fn_name[64];
     763         [ -  + ]:        240 :     if (is_vector)
     764                 :          0 :         sprintf(fn_name, "llvm.%s.v%" PRIu32 "f%" PRIu32, name, key.data.floating.vector_len, key.data.floating.bit_count);
     765                 :            :     else
     766                 :        240 :         sprintf(fn_name, "llvm.%s.f%" PRIu32, name, key.data.floating.bit_count);
     767                 :        240 :     LLVMTypeRef float_type_ref = get_llvm_type(g, type_entry);
     768                 :            :     LLVMTypeRef return_elem_types[3] = {
     769                 :            :         float_type_ref,
     770                 :            :         float_type_ref,
     771                 :            :         float_type_ref,
     772                 :        240 :     };
     773                 :        240 :     LLVMTypeRef fn_type = LLVMFunctionType(float_type_ref, return_elem_types, num_args, false);
     774                 :        240 :     LLVMValueRef fn_val = LLVMAddFunction(g->module, fn_name, fn_type);
     775                 :        240 :     assert(LLVMGetIntrinsicID(fn_val));
     776                 :            : 
     777                 :        240 :     g->llvm_fn_table.put(key, fn_val);
     778                 :        368 :     return fn_val;
     779                 :            : }
     780                 :            : 
     781                 :      69457 : static LLVMValueRef gen_store_untyped(CodeGen *g, LLVMValueRef value, LLVMValueRef ptr,
     782                 :            :         uint32_t alignment, bool is_volatile)
     783                 :            : {
     784                 :      69457 :     LLVMValueRef instruction = LLVMBuildStore(g->builder, value, ptr);
     785         [ +  + ]:      69457 :     if (is_volatile) LLVMSetVolatile(instruction, true);
     786         [ +  + ]:      69457 :     if (alignment != 0) {
     787                 :      52200 :         LLVMSetAlignment(instruction, alignment);
     788                 :            :     }
     789                 :      69457 :     return instruction;
     790                 :            : }
     791                 :            : 
     792                 :      33837 : static LLVMValueRef gen_store(CodeGen *g, LLVMValueRef value, LLVMValueRef ptr, ZigType *ptr_type) {
     793                 :      33837 :     assert(ptr_type->id == ZigTypeIdPointer);
     794                 :      33837 :     uint32_t alignment = get_ptr_align(g, ptr_type);
     795                 :      33837 :     return gen_store_untyped(g, value, ptr, alignment, ptr_type->data.pointer.is_volatile);
     796                 :            : }
     797                 :            : 
     798                 :     115215 : static LLVMValueRef gen_load_untyped(CodeGen *g, LLVMValueRef ptr, uint32_t alignment, bool is_volatile,
     799                 :            :         const char *name)
     800                 :            : {
     801                 :     115215 :     LLVMValueRef result = LLVMBuildLoad(g->builder, ptr, name);
     802         [ +  + ]:     115215 :     if (is_volatile) LLVMSetVolatile(result, true);
     803         [ +  + ]:     115215 :     if (alignment == 0) {
     804                 :      15334 :         LLVMSetAlignment(result, LLVMABIAlignmentOfType(g->target_data_ref, LLVMGetElementType(LLVMTypeOf(ptr))));
     805                 :            :     } else {
     806                 :      99881 :         LLVMSetAlignment(result, alignment);
     807                 :            :     }
     808                 :     115215 :     return result;
     809                 :            : }
     810                 :            : 
     811                 :      99873 : static LLVMValueRef gen_load(CodeGen *g, LLVMValueRef ptr, ZigType *ptr_type, const char *name) {
     812                 :      99873 :     assert(ptr_type->id == ZigTypeIdPointer);
     813                 :      99873 :     uint32_t alignment = get_ptr_align(g, ptr_type);
     814                 :      99873 :     return gen_load_untyped(g, ptr, alignment, ptr_type->data.pointer.is_volatile, name);
     815                 :            : }
     816                 :            : 
     817                 :     142819 : static LLVMValueRef get_handle_value(CodeGen *g, LLVMValueRef ptr, ZigType *type, ZigType *ptr_type) {
     818         [ +  + ]:     142819 :     if (type_has_bits(type)) {
     819         [ +  + ]:     142811 :         if (handle_is_ptr(type)) {
     820                 :      43716 :             return ptr;
     821                 :            :         } else {
     822                 :      99095 :             assert(ptr_type->id == ZigTypeIdPointer);
     823                 :      99095 :             return gen_load(g, ptr, ptr_type, "");
     824                 :            :         }
     825                 :            :     } else {
     826                 :          8 :         return nullptr;
     827                 :            :     }
     828                 :            : }
     829                 :            : 
     830                 :       4726 : static bool ir_want_fast_math(CodeGen *g, IrInstruction *instruction) {
     831                 :            :     // TODO memoize
     832                 :       4726 :     Scope *scope = instruction->scope;
     833         [ +  + ]:      69441 :     while (scope) {
     834         [ +  + ]:      64715 :         if (scope->id == ScopeIdBlock) {
     835                 :       6988 :             ScopeBlock *block_scope = (ScopeBlock *)scope;
     836         [ -  + ]:       6988 :             if (block_scope->fast_math_set_node)
     837                 :       6988 :                 return block_scope->fast_math_on;
     838         [ +  + ]:      57727 :         } else if (scope->id == ScopeIdDecls) {
     839                 :       4962 :             ScopeDecls *decls_scope = (ScopeDecls *)scope;
     840         [ -  + ]:       4962 :             if (decls_scope->fast_math_set_node)
     841                 :       4962 :                 return decls_scope->fast_math_on;
     842                 :            :         }
     843                 :      64715 :         scope = scope->parent;
     844                 :            :     }
     845                 :       4726 :     return false;
     846                 :            : }
     847                 :            : 
     848                 :      57162 : static bool ir_want_runtime_safety_scope(CodeGen *g, Scope *scope) {
     849                 :            :     // TODO memoize
     850         [ +  + ]:     831657 :     while (scope) {
     851         [ +  + ]:     784164 :         if (scope->id == ScopeIdBlock) {
     852                 :      98674 :             ScopeBlock *block_scope = (ScopeBlock *)scope;
     853         [ +  + ]:      98674 :             if (block_scope->safety_set_node)
     854                 :      98674 :                 return !block_scope->safety_off;
     855         [ +  + ]:     685490 :         } else if (scope->id == ScopeIdDecls) {
     856                 :      61977 :             ScopeDecls *decls_scope = (ScopeDecls *)scope;
     857         [ -  + ]:      61977 :             if (decls_scope->safety_set_node)
     858                 :      61977 :                 return !decls_scope->safety_off;
     859                 :            :         }
     860                 :     774495 :         scope = scope->parent;
     861                 :            :     }
     862                 :            : 
     863 [ +  - ][ +  - ]:      47493 :     return (g->build_mode != BuildModeFastRelease &&
     864                 :      47493 :             g->build_mode != BuildModeSmallRelease);
     865                 :            : }
     866                 :            : 
     867                 :      53818 : static bool ir_want_runtime_safety(CodeGen *g, IrInstruction *instruction) {
     868                 :      53818 :     return ir_want_runtime_safety_scope(g, instruction->scope);
     869                 :            : }
     870                 :            : 
     871                 :        231 : static Buf *panic_msg_buf(PanicMsgId msg_id) {
     872   [ -  +  +  +  :        231 :     switch (msg_id) {
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
                   -  - ]
     873                 :          0 :         case PanicMsgIdCount:
     874                 :          0 :             zig_unreachable();
     875                 :         11 :         case PanicMsgIdBoundsCheckFailure:
     876                 :         11 :             return buf_create_from_str("index out of bounds");
     877                 :         15 :         case PanicMsgIdCastNegativeToUnsigned:
     878                 :         15 :             return buf_create_from_str("attempt to cast negative value to unsigned integer");
     879                 :         15 :         case PanicMsgIdCastTruncatedData:
     880                 :         15 :             return buf_create_from_str("integer cast truncated bits");
     881                 :         15 :         case PanicMsgIdIntegerOverflow:
     882                 :         15 :             return buf_create_from_str("integer overflow");
     883                 :          8 :         case PanicMsgIdShlOverflowedBits:
     884                 :          8 :             return buf_create_from_str("left shift overflowed bits");
     885                 :          8 :         case PanicMsgIdShrOverflowedBits:
     886                 :          8 :             return buf_create_from_str("right shift overflowed bits");
     887                 :         11 :         case PanicMsgIdDivisionByZero:
     888                 :         11 :             return buf_create_from_str("division by zero");
     889                 :         11 :         case PanicMsgIdRemainderDivisionByZero:
     890                 :         11 :             return buf_create_from_str("remainder division by zero or negative value");
     891                 :          8 :         case PanicMsgIdExactDivisionRemainder:
     892                 :          8 :             return buf_create_from_str("exact division produced remainder");
     893                 :          9 :         case PanicMsgIdSliceWidenRemainder:
     894                 :          9 :             return buf_create_from_str("slice widening size mismatch");
     895                 :          9 :         case PanicMsgIdUnwrapOptionalFail:
     896                 :          9 :             return buf_create_from_str("attempt to unwrap null");
     897                 :         15 :         case PanicMsgIdUnreachable:
     898                 :         15 :             return buf_create_from_str("reached unreachable code");
     899                 :          9 :         case PanicMsgIdInvalidErrorCode:
     900                 :          9 :             return buf_create_from_str("invalid error code");
     901                 :          9 :         case PanicMsgIdIncorrectAlignment:
     902                 :          9 :             return buf_create_from_str("incorrect alignment");
     903                 :          8 :         case PanicMsgIdBadUnionField:
     904                 :          8 :             return buf_create_from_str("access of inactive union field");
     905                 :          9 :         case PanicMsgIdBadEnumValue:
     906                 :          9 :             return buf_create_from_str("invalid enum value");
     907                 :         10 :         case PanicMsgIdFloatToInt:
     908                 :         10 :             return buf_create_from_str("integer part of floating point value out of bounds");
     909                 :         11 :         case PanicMsgIdPtrCastNull:
     910                 :         11 :             return buf_create_from_str("cast causes pointer to be null");
     911                 :          8 :         case PanicMsgIdBadResume:
     912                 :          8 :             return buf_create_from_str("resumed an async function which already returned");
     913                 :          8 :         case PanicMsgIdBadAwait:
     914                 :          8 :             return buf_create_from_str("async function awaited twice");
     915                 :          8 :         case PanicMsgIdBadReturn:
     916                 :          8 :             return buf_create_from_str("async function returned twice");
     917                 :          8 :         case PanicMsgIdResumedAnAwaitingFn:
     918                 :          8 :             return buf_create_from_str("awaiting function resumed");
     919                 :          8 :         case PanicMsgIdFrameTooSmall:
     920                 :          8 :             return buf_create_from_str("frame too small");
     921                 :          0 :         case PanicMsgIdResumedFnPendingAwait:
     922                 :          0 :             return buf_create_from_str("resumed an async function which can only be awaited");
     923                 :            :     }
     924                 :          0 :     zig_unreachable();
     925                 :            : }
     926                 :            : 
     927                 :      21082 : static LLVMValueRef get_panic_msg_ptr_val(CodeGen *g, PanicMsgId msg_id) {
     928                 :      21082 :     ConstExprValue *val = &g->panic_msg_vals[msg_id];
     929         [ +  + ]:      21082 :     if (!val->global_refs->llvm_global) {
     930                 :            : 
     931                 :        231 :         Buf *buf_msg = panic_msg_buf(msg_id);
     932                 :        231 :         ConstExprValue *array_val = create_const_str_lit(g, buf_msg);
     933                 :        231 :         init_const_slice(g, val, array_val, 0, buf_len(buf_msg), true);
     934                 :            : 
     935                 :        231 :         render_const_val(g, val, "");
     936                 :        231 :         render_const_val_global(g, val, "");
     937                 :            : 
     938                 :        231 :         assert(val->global_refs->llvm_global);
     939                 :            :     }
     940                 :            : 
     941                 :      21082 :     ZigType *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
     942                 :      21082 :             PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0, false);
     943                 :      21082 :     ZigType *str_type = get_slice_type(g, u8_ptr_type);
     944                 :      21082 :     return LLVMConstBitCast(val->global_refs->llvm_global, LLVMPointerType(get_llvm_type(g, str_type), 0));
     945                 :            : }
     946                 :            : 
     947                 :      21170 : static ZigType *ptr_to_stack_trace_type(CodeGen *g) {
     948                 :      21170 :     return get_pointer_to_type(g, get_stack_trace_type(g), false);
     949                 :            : }
     950                 :            : 
     951                 :      21380 : static void gen_panic(CodeGen *g, LLVMValueRef msg_arg, LLVMValueRef stack_trace_arg) {
     952                 :      21380 :     assert(g->panic_fn != nullptr);
     953                 :      21380 :     LLVMValueRef fn_val = fn_llvm_value(g, g->panic_fn);
     954                 :      21380 :     LLVMCallConv llvm_cc = get_llvm_cc(g, g->panic_fn->type_entry->data.fn.fn_type_id.cc);
     955         [ +  + ]:      21380 :     if (stack_trace_arg == nullptr) {
     956                 :      21128 :         stack_trace_arg = LLVMConstNull(get_llvm_type(g, ptr_to_stack_trace_type(g)));
     957                 :            :     }
     958                 :            :     LLVMValueRef args[] = {
     959                 :            :         msg_arg,
     960                 :            :         stack_trace_arg,
     961                 :      21380 :     };
     962                 :      21380 :     LLVMValueRef call_instruction = ZigLLVMBuildCall(g->builder, fn_val, args, 2, llvm_cc, ZigLLVM_FnInlineAuto, "");
     963                 :      21380 :     LLVMSetTailCall(call_instruction, true);
     964                 :      21380 :     LLVMBuildUnreachable(g->builder);
     965                 :      21380 : }
     966                 :            : 
     967                 :            : // TODO update most callsites to call gen_assertion instead of this
     968                 :      21082 : static void gen_safety_crash(CodeGen *g, PanicMsgId msg_id) {
     969                 :      21082 :     gen_panic(g, get_panic_msg_ptr_val(g, msg_id), nullptr);
     970                 :      21082 : }
     971                 :            : 
     972                 :       3344 : static void gen_assertion_scope(CodeGen *g, PanicMsgId msg_id, Scope *source_scope) {
     973         [ +  - ]:       3344 :     if (ir_want_runtime_safety_scope(g, source_scope)) {
     974                 :       3344 :         gen_safety_crash(g, msg_id);
     975                 :            :     } else {
     976                 :          0 :         LLVMBuildUnreachable(g->builder);
     977                 :            :     }
     978                 :       3344 : }
     979                 :            : 
     980                 :       2520 : static void gen_assertion(CodeGen *g, PanicMsgId msg_id, IrInstruction *source_instruction) {
     981                 :       2520 :     return gen_assertion_scope(g, msg_id, source_instruction->scope);
     982                 :            : }
     983                 :            : 
     984                 :         16 : static LLVMValueRef get_stacksave_fn_val(CodeGen *g) {
     985         [ +  + ]:         16 :     if (g->stacksave_fn_val)
     986                 :          8 :         return g->stacksave_fn_val;
     987                 :            : 
     988                 :            :     // declare i8* @llvm.stacksave()
     989                 :            : 
     990                 :          8 :     LLVMTypeRef fn_type = LLVMFunctionType(LLVMPointerType(LLVMInt8Type(), 0), nullptr, 0, false);
     991                 :          8 :     g->stacksave_fn_val = LLVMAddFunction(g->module, "llvm.stacksave", fn_type);
     992                 :          8 :     assert(LLVMGetIntrinsicID(g->stacksave_fn_val));
     993                 :            : 
     994                 :          8 :     return g->stacksave_fn_val;
     995                 :            : }
     996                 :            : 
     997                 :         16 : static LLVMValueRef get_stackrestore_fn_val(CodeGen *g) {
     998         [ +  + ]:         16 :     if (g->stackrestore_fn_val)
     999                 :          8 :         return g->stackrestore_fn_val;
    1000                 :            : 
    1001                 :            :     // declare void @llvm.stackrestore(i8* %ptr)
    1002                 :            : 
    1003                 :          8 :     LLVMTypeRef param_type = LLVMPointerType(LLVMInt8Type(), 0);
    1004                 :          8 :     LLVMTypeRef fn_type = LLVMFunctionType(LLVMVoidType(), &param_type, 1, false);
    1005                 :          8 :     g->stackrestore_fn_val = LLVMAddFunction(g->module, "llvm.stackrestore", fn_type);
    1006                 :          8 :     assert(LLVMGetIntrinsicID(g->stackrestore_fn_val));
    1007                 :            : 
    1008                 :         16 :     return g->stackrestore_fn_val;
    1009                 :            : }
    1010                 :            : 
    1011                 :         16 : static LLVMValueRef get_write_register_fn_val(CodeGen *g) {
    1012         [ +  + ]:         16 :     if (g->write_register_fn_val)
    1013                 :          8 :         return g->write_register_fn_val;
    1014                 :            : 
    1015                 :            :     // declare void @llvm.write_register.i64(metadata, i64 @value)
    1016                 :            :     // !0 = !{!"sp\00"}
    1017                 :            : 
    1018                 :            :     LLVMTypeRef param_types[] = {
    1019                 :          8 :         LLVMMetadataTypeInContext(LLVMGetGlobalContext()),
    1020                 :          8 :         LLVMIntType(g->pointer_size_bytes * 8),
    1021                 :         16 :     };
    1022                 :            : 
    1023                 :          8 :     LLVMTypeRef fn_type = LLVMFunctionType(LLVMVoidType(), param_types, 2, false);
    1024                 :          8 :     Buf *name = buf_sprintf("llvm.write_register.i%d", g->pointer_size_bytes * 8);
    1025                 :          8 :     g->write_register_fn_val = LLVMAddFunction(g->module, buf_ptr(name), fn_type);
    1026                 :          8 :     assert(LLVMGetIntrinsicID(g->write_register_fn_val));
    1027                 :            : 
    1028                 :         16 :     return g->write_register_fn_val;
    1029                 :            : }
    1030                 :            : 
    1031                 :        135 : static LLVMValueRef get_return_address_fn_val(CodeGen *g) {
    1032         [ +  + ]:        135 :     if (g->return_address_fn_val)
    1033                 :        126 :         return g->return_address_fn_val;
    1034                 :            : 
    1035                 :          9 :     ZigType *return_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);
    1036                 :            : 
    1037                 :          9 :     LLVMTypeRef fn_type = LLVMFunctionType(get_llvm_type(g, return_type),
    1038                 :          9 :             &g->builtin_types.entry_i32->llvm_type, 1, false);
    1039                 :          9 :     g->return_address_fn_val = LLVMAddFunction(g->module, "llvm.returnaddress", fn_type);
    1040                 :          9 :     assert(LLVMGetIntrinsicID(g->return_address_fn_val));
    1041                 :            : 
    1042                 :          9 :     return g->return_address_fn_val;
    1043                 :            : }
    1044                 :            : 
    1045                 :         17 : static LLVMValueRef get_add_error_return_trace_addr_fn(CodeGen *g) {
    1046         [ +  + ]:         17 :     if (g->add_error_return_trace_addr_fn_val != nullptr)
    1047                 :          8 :         return g->add_error_return_trace_addr_fn_val;
    1048                 :            : 
    1049                 :            :     LLVMTypeRef arg_types[] = {
    1050                 :          9 :         get_llvm_type(g, ptr_to_stack_trace_type(g)),
    1051                 :          9 :         g->builtin_types.entry_usize->llvm_type,
    1052                 :         18 :     };
    1053                 :          9 :     LLVMTypeRef fn_type_ref = LLVMFunctionType(LLVMVoidType(), arg_types, 2, false);
    1054                 :            : 
    1055                 :          9 :     Buf *fn_name = get_mangled_name(g, buf_create_from_str("__zig_add_err_ret_trace_addr"), false);
    1056                 :          9 :     LLVMValueRef fn_val = LLVMAddFunction(g->module, buf_ptr(fn_name), fn_type_ref);
    1057                 :          9 :     addLLVMFnAttr(fn_val, "alwaysinline");
    1058                 :          9 :     LLVMSetLinkage(fn_val, LLVMInternalLinkage);
    1059                 :          9 :     LLVMSetFunctionCallConv(fn_val, get_llvm_cc(g, CallingConventionUnspecified));
    1060                 :          9 :     addLLVMFnAttr(fn_val, "nounwind");
    1061                 :          9 :     add_uwtable_attr(g, fn_val);
    1062                 :            :     // Error return trace memory is in the stack, which is impossible to be at address 0
    1063                 :            :     // on any architecture.
    1064                 :          9 :     addLLVMArgAttr(fn_val, (unsigned)0, "nonnull");
    1065         [ +  - ]:          9 :     if (codegen_have_frame_pointer(g)) {
    1066                 :          9 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim", "true");
    1067                 :          9 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim-non-leaf", nullptr);
    1068                 :            :     }
    1069                 :            : 
    1070                 :          9 :     LLVMBasicBlockRef entry_block = LLVMAppendBasicBlock(fn_val, "Entry");
    1071                 :          9 :     LLVMBasicBlockRef prev_block = LLVMGetInsertBlock(g->builder);
    1072                 :          9 :     LLVMValueRef prev_debug_location = LLVMGetCurrentDebugLocation(g->builder);
    1073                 :          9 :     LLVMPositionBuilderAtEnd(g->builder, entry_block);
    1074                 :          9 :     ZigLLVMClearCurrentDebugLocation(g->builder);
    1075                 :            : 
    1076                 :          9 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    1077                 :            : 
    1078                 :            :     // stack_trace.instruction_addresses[stack_trace.index & (stack_trace.instruction_addresses.len - 1)] = return_address;
    1079                 :            : 
    1080                 :          9 :     LLVMValueRef err_ret_trace_ptr = LLVMGetParam(fn_val, 0);
    1081                 :          9 :     LLVMValueRef address_value = LLVMGetParam(fn_val, 1);
    1082                 :            : 
    1083                 :          9 :     size_t index_field_index = g->stack_trace_type->data.structure.fields[0].gen_index;
    1084                 :          9 :     LLVMValueRef index_field_ptr = LLVMBuildStructGEP(g->builder, err_ret_trace_ptr, (unsigned)index_field_index, "");
    1085                 :          9 :     size_t addresses_field_index = g->stack_trace_type->data.structure.fields[1].gen_index;
    1086                 :          9 :     LLVMValueRef addresses_field_ptr = LLVMBuildStructGEP(g->builder, err_ret_trace_ptr, (unsigned)addresses_field_index, "");
    1087                 :            : 
    1088                 :          9 :     ZigType *slice_type = g->stack_trace_type->data.structure.fields[1].type_entry;
    1089                 :          9 :     size_t ptr_field_index = slice_type->data.structure.fields[slice_ptr_index].gen_index;
    1090                 :          9 :     LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, addresses_field_ptr, (unsigned)ptr_field_index, "");
    1091                 :          9 :     size_t len_field_index = slice_type->data.structure.fields[slice_len_index].gen_index;
    1092                 :          9 :     LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, addresses_field_ptr, (unsigned)len_field_index, "");
    1093                 :            : 
    1094                 :          9 :     LLVMValueRef len_value = gen_load_untyped(g, len_field_ptr, 0, false, "");
    1095                 :          9 :     LLVMValueRef index_val = gen_load_untyped(g, index_field_ptr, 0, false, "");
    1096                 :          9 :     LLVMValueRef len_val_minus_one = LLVMBuildSub(g->builder, len_value, LLVMConstInt(usize_type_ref, 1, false), "");
    1097                 :          9 :     LLVMValueRef masked_val = LLVMBuildAnd(g->builder, index_val, len_val_minus_one, "");
    1098                 :            :     LLVMValueRef address_indices[] = {
    1099                 :            :         masked_val,
    1100                 :          9 :     };
    1101                 :            : 
    1102                 :          9 :     LLVMValueRef ptr_value = gen_load_untyped(g, ptr_field_ptr, 0, false, "");
    1103                 :          9 :     LLVMValueRef address_slot = LLVMBuildInBoundsGEP(g->builder, ptr_value, address_indices, 1, "");
    1104                 :            : 
    1105                 :          9 :     gen_store_untyped(g, address_value, address_slot, 0, false);
    1106                 :            : 
    1107                 :            :     // stack_trace.index += 1;
    1108                 :          9 :     LLVMValueRef index_plus_one_val = LLVMBuildNUWAdd(g->builder, index_val, LLVMConstInt(usize_type_ref, 1, false), "");
    1109                 :          9 :     gen_store_untyped(g, index_plus_one_val, index_field_ptr, 0, false);
    1110                 :            : 
    1111                 :            :     // return;
    1112                 :          9 :     LLVMBuildRetVoid(g->builder);
    1113                 :            : 
    1114                 :          9 :     LLVMPositionBuilderAtEnd(g->builder, prev_block);
    1115         [ +  - ]:          9 :     if (!g->strip_debug_symbols) {
    1116                 :          9 :         LLVMSetCurrentDebugLocation(g->builder, prev_debug_location);
    1117                 :            :     }
    1118                 :            : 
    1119                 :          9 :     g->add_error_return_trace_addr_fn_val = fn_val;
    1120                 :         17 :     return fn_val;
    1121                 :            : }
    1122                 :            : 
    1123                 :       9986 : static LLVMValueRef get_return_err_fn(CodeGen *g) {
    1124         [ +  + ]:       9986 :     if (g->return_err_fn != nullptr)
    1125                 :       9977 :         return g->return_err_fn;
    1126                 :            : 
    1127                 :          9 :     assert(g->err_tag_type != nullptr);
    1128                 :            : 
    1129                 :            :     LLVMTypeRef arg_types[] = {
    1130                 :            :         // error return trace pointer
    1131                 :          9 :         get_llvm_type(g, ptr_to_stack_trace_type(g)),
    1132                 :          9 :     };
    1133                 :          9 :     LLVMTypeRef fn_type_ref = LLVMFunctionType(LLVMVoidType(), arg_types, 1, false);
    1134                 :            : 
    1135                 :          9 :     Buf *fn_name = get_mangled_name(g, buf_create_from_str("__zig_return_error"), false);
    1136                 :          9 :     LLVMValueRef fn_val = LLVMAddFunction(g->module, buf_ptr(fn_name), fn_type_ref);
    1137                 :          9 :     addLLVMFnAttr(fn_val, "noinline"); // so that we can look at return address
    1138                 :          9 :     addLLVMFnAttr(fn_val, "cold");
    1139                 :          9 :     LLVMSetLinkage(fn_val, LLVMInternalLinkage);
    1140                 :          9 :     LLVMSetFunctionCallConv(fn_val, get_llvm_cc(g, CallingConventionUnspecified));
    1141                 :          9 :     addLLVMFnAttr(fn_val, "nounwind");
    1142                 :          9 :     add_uwtable_attr(g, fn_val);
    1143         [ +  - ]:          9 :     if (codegen_have_frame_pointer(g)) {
    1144                 :          9 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim", "true");
    1145                 :          9 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim-non-leaf", nullptr);
    1146                 :            :     }
    1147                 :            : 
    1148                 :            :     // this is above the ZigLLVMClearCurrentDebugLocation
    1149                 :          9 :     LLVMValueRef add_error_return_trace_addr_fn_val = get_add_error_return_trace_addr_fn(g);
    1150                 :            : 
    1151                 :          9 :     LLVMBasicBlockRef entry_block = LLVMAppendBasicBlock(fn_val, "Entry");
    1152                 :          9 :     LLVMBasicBlockRef prev_block = LLVMGetInsertBlock(g->builder);
    1153                 :          9 :     LLVMValueRef prev_debug_location = LLVMGetCurrentDebugLocation(g->builder);
    1154                 :          9 :     LLVMPositionBuilderAtEnd(g->builder, entry_block);
    1155                 :          9 :     ZigLLVMClearCurrentDebugLocation(g->builder);
    1156                 :            : 
    1157                 :          9 :     LLVMValueRef err_ret_trace_ptr = LLVMGetParam(fn_val, 0);
    1158                 :            : 
    1159                 :          9 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    1160                 :          9 :     LLVMValueRef zero = LLVMConstNull(get_llvm_type(g, g->builtin_types.entry_i32));
    1161                 :          9 :     LLVMValueRef return_address_ptr = LLVMBuildCall(g->builder, get_return_address_fn_val(g), &zero, 1, "");
    1162                 :          9 :     LLVMValueRef return_address = LLVMBuildPtrToInt(g->builder, return_address_ptr, usize_type_ref, "");
    1163                 :            : 
    1164                 :          9 :     LLVMBasicBlockRef return_block = LLVMAppendBasicBlock(fn_val, "Return");
    1165                 :          9 :     LLVMBasicBlockRef dest_non_null_block = LLVMAppendBasicBlock(fn_val, "DestNonNull");
    1166                 :            : 
    1167                 :          9 :     LLVMValueRef null_dest_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, err_ret_trace_ptr,
    1168                 :          9 :             LLVMConstNull(LLVMTypeOf(err_ret_trace_ptr)), "");
    1169                 :          9 :     LLVMBuildCondBr(g->builder, null_dest_bit, return_block, dest_non_null_block);
    1170                 :            : 
    1171                 :          9 :     LLVMPositionBuilderAtEnd(g->builder, return_block);
    1172                 :          9 :     LLVMBuildRetVoid(g->builder);
    1173                 :            : 
    1174                 :          9 :     LLVMPositionBuilderAtEnd(g->builder, dest_non_null_block);
    1175                 :          9 :     LLVMValueRef args[] = { err_ret_trace_ptr, return_address };
    1176                 :          9 :     ZigLLVMBuildCall(g->builder, add_error_return_trace_addr_fn_val, args, 2, get_llvm_cc(g, CallingConventionUnspecified), ZigLLVM_FnInlineAlways, "");
    1177                 :          9 :     LLVMBuildRetVoid(g->builder);
    1178                 :            : 
    1179                 :          9 :     LLVMPositionBuilderAtEnd(g->builder, prev_block);
    1180         [ +  - ]:          9 :     if (!g->strip_debug_symbols) {
    1181                 :          9 :         LLVMSetCurrentDebugLocation(g->builder, prev_debug_location);
    1182                 :            :     }
    1183                 :            : 
    1184                 :          9 :     g->return_err_fn = fn_val;
    1185                 :       9986 :     return fn_val;
    1186                 :            : }
    1187                 :            : 
    1188                 :        696 : static LLVMValueRef get_safety_crash_err_fn(CodeGen *g) {
    1189         [ +  + ]:        696 :     if (g->safety_crash_err_fn != nullptr)
    1190                 :        687 :         return g->safety_crash_err_fn;
    1191                 :            : 
    1192                 :            :     static const char *unwrap_err_msg_text = "attempt to unwrap error: ";
    1193                 :            : 
    1194                 :          9 :     g->generate_error_name_table = true;
    1195                 :          9 :     generate_error_name_table(g);
    1196                 :          9 :     assert(g->err_name_table != nullptr);
    1197                 :            : 
    1198                 :            :     // Generate the constant part of the error message
    1199                 :          9 :     LLVMValueRef msg_prefix_init = LLVMConstString(unwrap_err_msg_text, strlen(unwrap_err_msg_text), 1);
    1200                 :          9 :     LLVMValueRef msg_prefix = LLVMAddGlobal(g->module, LLVMTypeOf(msg_prefix_init), "");
    1201                 :          9 :     LLVMSetInitializer(msg_prefix, msg_prefix_init);
    1202                 :          9 :     LLVMSetLinkage(msg_prefix, LLVMInternalLinkage);
    1203                 :          9 :     LLVMSetGlobalConstant(msg_prefix, true);
    1204                 :            : 
    1205                 :          9 :     Buf *fn_name = get_mangled_name(g, buf_create_from_str("__zig_fail_unwrap"), false);
    1206                 :            :     LLVMTypeRef fn_type_ref;
    1207         [ +  - ]:          9 :     if (g->have_err_ret_tracing) {
    1208                 :            :         LLVMTypeRef arg_types[] = {
    1209                 :          9 :             get_llvm_type(g, get_pointer_to_type(g, get_stack_trace_type(g), false)),
    1210                 :          9 :             get_llvm_type(g, g->err_tag_type),
    1211                 :         18 :         };
    1212                 :          9 :         fn_type_ref = LLVMFunctionType(LLVMVoidType(), arg_types, 2, false);
    1213                 :            :     } else {
    1214                 :            :         LLVMTypeRef arg_types[] = {
    1215                 :          0 :             get_llvm_type(g, g->err_tag_type),
    1216                 :          0 :         };
    1217                 :          0 :         fn_type_ref = LLVMFunctionType(LLVMVoidType(), arg_types, 1, false);
    1218                 :            :     }
    1219                 :          9 :     LLVMValueRef fn_val = LLVMAddFunction(g->module, buf_ptr(fn_name), fn_type_ref);
    1220                 :          9 :     addLLVMFnAttr(fn_val, "noreturn");
    1221                 :          9 :     addLLVMFnAttr(fn_val, "cold");
    1222                 :          9 :     LLVMSetLinkage(fn_val, LLVMInternalLinkage);
    1223                 :          9 :     LLVMSetFunctionCallConv(fn_val, get_llvm_cc(g, CallingConventionUnspecified));
    1224                 :          9 :     addLLVMFnAttr(fn_val, "nounwind");
    1225                 :          9 :     add_uwtable_attr(g, fn_val);
    1226         [ +  - ]:          9 :     if (codegen_have_frame_pointer(g)) {
    1227                 :          9 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim", "true");
    1228                 :          9 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim-non-leaf", nullptr);
    1229                 :            :     }
    1230                 :            :     // Not setting alignment here. See the comment above about
    1231                 :            :     // "Cannot getTypeInfo() on a type that is unsized!"
    1232                 :            :     // assertion failure on Darwin.
    1233                 :            : 
    1234                 :          9 :     LLVMBasicBlockRef entry_block = LLVMAppendBasicBlock(fn_val, "Entry");
    1235                 :          9 :     LLVMBasicBlockRef prev_block = LLVMGetInsertBlock(g->builder);
    1236                 :          9 :     LLVMValueRef prev_debug_location = LLVMGetCurrentDebugLocation(g->builder);
    1237                 :          9 :     LLVMPositionBuilderAtEnd(g->builder, entry_block);
    1238                 :          9 :     ZigLLVMClearCurrentDebugLocation(g->builder);
    1239                 :            : 
    1240                 :          9 :     ZigType *usize_ty = g->builtin_types.entry_usize;
    1241                 :          9 :     ZigType *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
    1242                 :          9 :             PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0, false);
    1243                 :          9 :     ZigType *str_type = get_slice_type(g, u8_ptr_type);
    1244                 :            : 
    1245                 :            :     // Allocate a buffer to hold the fully-formatted error message
    1246                 :          9 :     const size_t err_buf_len = strlen(unwrap_err_msg_text) + g->largest_err_name_len;
    1247                 :          9 :     LLVMValueRef max_msg_len = LLVMConstInt(usize_ty->llvm_type, err_buf_len, 0);
    1248                 :          9 :     LLVMValueRef msg_buffer = LLVMBuildArrayAlloca(g->builder, LLVMInt8Type(), max_msg_len, "msg_buffer");
    1249                 :            : 
    1250                 :            :     // Allocate a []u8 slice for the message
    1251                 :          9 :     LLVMValueRef msg_slice = build_alloca(g, str_type, "msg_slice", 0);
    1252                 :            : 
    1253                 :            :     LLVMValueRef err_ret_trace_arg;
    1254                 :            :     LLVMValueRef err_val;
    1255         [ +  - ]:          9 :     if (g->have_err_ret_tracing) {
    1256                 :          9 :         err_ret_trace_arg = LLVMGetParam(fn_val, 0);
    1257                 :          9 :         err_val = LLVMGetParam(fn_val, 1);
    1258                 :            :     } else {
    1259                 :          0 :         err_ret_trace_arg = nullptr;
    1260                 :          0 :         err_val = LLVMGetParam(fn_val, 0);
    1261                 :            :     }
    1262                 :            : 
    1263                 :            :     // Fetch the error name from the global table
    1264                 :            :     LLVMValueRef err_table_indices[] = {
    1265                 :          9 :         LLVMConstNull(usize_ty->llvm_type),
    1266                 :            :         err_val,
    1267                 :          9 :     };
    1268                 :          9 :     LLVMValueRef err_name_val = LLVMBuildInBoundsGEP(g->builder, g->err_name_table, err_table_indices, 2, "");
    1269                 :            : 
    1270                 :          9 :     LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, err_name_val, slice_ptr_index, "");
    1271                 :          9 :     LLVMValueRef err_name_ptr = gen_load_untyped(g, ptr_field_ptr, 0, false, "");
    1272                 :            : 
    1273                 :          9 :     LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, err_name_val, slice_len_index, "");
    1274                 :          9 :     LLVMValueRef err_name_len = gen_load_untyped(g, len_field_ptr, 0, false, "");
    1275                 :            : 
    1276                 :          9 :     LLVMValueRef msg_prefix_len = LLVMConstInt(usize_ty->llvm_type, strlen(unwrap_err_msg_text), false);
    1277                 :            :     // Points to the beginning of msg_buffer
    1278                 :            :     LLVMValueRef msg_buffer_ptr_indices[] = {
    1279                 :          9 :         LLVMConstNull(usize_ty->llvm_type),
    1280                 :          9 :     };
    1281                 :          9 :     LLVMValueRef msg_buffer_ptr = LLVMBuildInBoundsGEP(g->builder, msg_buffer, msg_buffer_ptr_indices, 1, "");
    1282                 :            :     // Points to the beginning of the constant prefix message
    1283                 :            :     LLVMValueRef msg_prefix_ptr_indices[] = {
    1284                 :          9 :         LLVMConstNull(usize_ty->llvm_type),
    1285                 :          9 :     };
    1286                 :          9 :     LLVMValueRef msg_prefix_ptr = LLVMConstInBoundsGEP(msg_prefix, msg_prefix_ptr_indices, 1);
    1287                 :            : 
    1288                 :            :     // Build the message using the prefix...
    1289                 :          9 :     ZigLLVMBuildMemCpy(g->builder, msg_buffer_ptr, 1, msg_prefix_ptr, 1, msg_prefix_len, false);
    1290                 :            :     // ..and append the error name
    1291                 :            :     LLVMValueRef msg_buffer_ptr_after_indices[] = {
    1292                 :            :         msg_prefix_len,
    1293                 :          9 :     };
    1294                 :          9 :     LLVMValueRef msg_buffer_ptr_after = LLVMBuildInBoundsGEP(g->builder, msg_buffer, msg_buffer_ptr_after_indices, 1, "");
    1295                 :          9 :     ZigLLVMBuildMemCpy(g->builder, msg_buffer_ptr_after, 1, err_name_ptr, 1, err_name_len, false);
    1296                 :            : 
    1297                 :            :     // Set the slice pointer
    1298                 :          9 :     LLVMValueRef msg_slice_ptr_field_ptr = LLVMBuildStructGEP(g->builder, msg_slice, slice_ptr_index, "");
    1299                 :          9 :     gen_store_untyped(g, msg_buffer_ptr, msg_slice_ptr_field_ptr, 0, false);
    1300                 :            : 
    1301                 :            :     // Set the slice length
    1302                 :          9 :     LLVMValueRef slice_len = LLVMBuildNUWAdd(g->builder, msg_prefix_len, err_name_len, "");
    1303                 :          9 :     LLVMValueRef msg_slice_len_field_ptr = LLVMBuildStructGEP(g->builder, msg_slice, slice_len_index, "");
    1304                 :          9 :     gen_store_untyped(g, slice_len, msg_slice_len_field_ptr, 0, false);
    1305                 :            : 
    1306                 :            :     // Call panic()
    1307                 :          9 :     gen_panic(g, msg_slice, err_ret_trace_arg);
    1308                 :            : 
    1309                 :          9 :     LLVMPositionBuilderAtEnd(g->builder, prev_block);
    1310         [ +  - ]:          9 :     if (!g->strip_debug_symbols) {
    1311                 :          9 :         LLVMSetCurrentDebugLocation(g->builder, prev_debug_location);
    1312                 :            :     }
    1313                 :            : 
    1314                 :          9 :     g->safety_crash_err_fn = fn_val;
    1315                 :        696 :     return fn_val;
    1316                 :            : }
    1317                 :            : 
    1318                 :      23586 : static LLVMValueRef get_cur_err_ret_trace_val(CodeGen *g, Scope *scope) {
    1319         [ -  + ]:      23586 :     if (!g->have_err_ret_tracing) {
    1320                 :          0 :         return nullptr;
    1321                 :            :     }
    1322         [ +  + ]:      23586 :     if (g->cur_err_ret_trace_val_stack != nullptr) {
    1323                 :       4627 :         return g->cur_err_ret_trace_val_stack;
    1324                 :            :     }
    1325                 :      18959 :     return g->cur_err_ret_trace_val_arg;
    1326                 :            : }
    1327                 :            : 
    1328                 :        696 : static void gen_safety_crash_for_err(CodeGen *g, LLVMValueRef err_val, Scope *scope) {
    1329                 :        696 :     LLVMValueRef safety_crash_err_fn = get_safety_crash_err_fn(g);
    1330                 :            :     LLVMValueRef call_instruction;
    1331         [ +  - ]:        696 :     if (g->have_err_ret_tracing) {
    1332                 :        696 :         LLVMValueRef err_ret_trace_val = get_cur_err_ret_trace_val(g, scope);
    1333         [ +  + ]:        696 :         if (err_ret_trace_val == nullptr) {
    1334                 :          8 :             err_ret_trace_val = LLVMConstNull(get_llvm_type(g, ptr_to_stack_trace_type(g)));
    1335                 :            :         }
    1336                 :            :         LLVMValueRef args[] = {
    1337                 :            :             err_ret_trace_val,
    1338                 :            :             err_val,
    1339                 :        696 :         };
    1340                 :        696 :         call_instruction = ZigLLVMBuildCall(g->builder, safety_crash_err_fn, args, 2,
    1341                 :        696 :                 get_llvm_cc(g, CallingConventionUnspecified), ZigLLVM_FnInlineAuto, "");
    1342                 :            :     } else {
    1343                 :            :         LLVMValueRef args[] = {
    1344                 :            :             err_val,
    1345                 :          0 :         };
    1346                 :          0 :         call_instruction = ZigLLVMBuildCall(g->builder, safety_crash_err_fn, args, 1,
    1347                 :          0 :                 get_llvm_cc(g, CallingConventionUnspecified), ZigLLVM_FnInlineAuto, "");
    1348                 :            :     }
    1349                 :        696 :     LLVMSetTailCall(call_instruction, true);
    1350                 :        696 :     LLVMBuildUnreachable(g->builder);
    1351                 :        696 : }
    1352                 :            : 
    1353                 :       6824 : static void add_bounds_check(CodeGen *g, LLVMValueRef target_val,
    1354                 :            :         LLVMIntPredicate lower_pred, LLVMValueRef lower_value,
    1355                 :            :         LLVMIntPredicate upper_pred, LLVMValueRef upper_value)
    1356                 :            : {
    1357 [ +  + ][ -  + ]:       6824 :     if (!lower_value && !upper_value) {
    1358                 :          0 :         return;
    1359                 :            :     }
    1360 [ +  - ][ +  + ]:       6824 :     if (upper_value && !lower_value) {
    1361                 :       6489 :         lower_value = upper_value;
    1362                 :       6489 :         lower_pred = upper_pred;
    1363                 :       6489 :         upper_value = nullptr;
    1364                 :            :     }
    1365                 :            : 
    1366                 :       6824 :     LLVMBasicBlockRef bounds_check_fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "BoundsCheckFail");
    1367                 :       6824 :     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "BoundsCheckOk");
    1368         [ +  + ]:       6824 :     LLVMBasicBlockRef lower_ok_block = upper_value ?
    1369                 :       7159 :         LLVMAppendBasicBlock(g->cur_fn_val, "FirstBoundsCheckOk") : ok_block;
    1370                 :            : 
    1371                 :       6824 :     LLVMValueRef lower_ok_val = LLVMBuildICmp(g->builder, lower_pred, target_val, lower_value, "");
    1372                 :       6824 :     LLVMBuildCondBr(g->builder, lower_ok_val, lower_ok_block, bounds_check_fail_block);
    1373                 :            : 
    1374                 :       6824 :     LLVMPositionBuilderAtEnd(g->builder, bounds_check_fail_block);
    1375                 :       6824 :     gen_safety_crash(g, PanicMsgIdBoundsCheckFailure);
    1376                 :            : 
    1377         [ +  + ]:       6824 :     if (upper_value) {
    1378                 :        335 :         LLVMPositionBuilderAtEnd(g->builder, lower_ok_block);
    1379                 :        335 :         LLVMValueRef upper_ok_val = LLVMBuildICmp(g->builder, upper_pred, target_val, upper_value, "");
    1380                 :        335 :         LLVMBuildCondBr(g->builder, upper_ok_val, ok_block, bounds_check_fail_block);
    1381                 :            :     }
    1382                 :            : 
    1383                 :       6824 :     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    1384                 :            : }
    1385                 :            : 
    1386                 :         32 : static LLVMValueRef gen_assert_zero(CodeGen *g, LLVMValueRef expr_val, ZigType *int_type) {
    1387                 :         32 :     LLVMValueRef zero = LLVMConstNull(get_llvm_type(g, int_type));
    1388                 :         32 :     LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, expr_val, zero, "");
    1389                 :         32 :     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "CastShortenOk");
    1390                 :         32 :     LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "CastShortenFail");
    1391                 :         32 :     LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    1392                 :            : 
    1393                 :         32 :     LLVMPositionBuilderAtEnd(g->builder, fail_block);
    1394                 :         32 :     gen_safety_crash(g, PanicMsgIdCastTruncatedData);
    1395                 :            : 
    1396                 :         32 :     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    1397                 :         32 :     return nullptr;
    1398                 :            : }
    1399                 :            : 
    1400                 :       8602 : static LLVMValueRef gen_widen_or_shorten(CodeGen *g, bool want_runtime_safety, ZigType *actual_type,
    1401                 :            :         ZigType *wanted_type, LLVMValueRef expr_val)
    1402                 :            : {
    1403                 :       8602 :     assert(actual_type->id == wanted_type->id);
    1404                 :       8602 :     assert(expr_val != nullptr);
    1405                 :            : 
    1406                 :            :     uint64_t actual_bits;
    1407                 :            :     uint64_t wanted_bits;
    1408         [ +  + ]:       8602 :     if (actual_type->id == ZigTypeIdFloat) {
    1409                 :         64 :         actual_bits = actual_type->data.floating.bit_count;
    1410                 :         64 :         wanted_bits = wanted_type->data.floating.bit_count;
    1411         [ +  - ]:       8538 :     } else if (actual_type->id == ZigTypeIdInt) {
    1412                 :       8538 :         actual_bits = actual_type->data.integral.bit_count;
    1413                 :       8538 :         wanted_bits = wanted_type->data.integral.bit_count;
    1414                 :            :     } else {
    1415                 :          0 :         zig_unreachable();
    1416                 :            :     }
    1417                 :            : 
    1418 [ +  + ][ +  + ]:       8602 :     if (actual_type->id == ZigTypeIdInt &&
    1419 [ +  + ][ +  + ]:       7729 :         !wanted_type->data.integral.is_signed && actual_type->data.integral.is_signed &&
    1420                 :            :         want_runtime_safety)
    1421                 :            :     {
    1422                 :        292 :         LLVMValueRef zero = LLVMConstNull(get_llvm_type(g, actual_type));
    1423                 :        292 :         LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntSGE, expr_val, zero, "");
    1424                 :            : 
    1425                 :        292 :         LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "SignCastOk");
    1426                 :        292 :         LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "SignCastFail");
    1427                 :        292 :         LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    1428                 :            : 
    1429                 :        292 :         LLVMPositionBuilderAtEnd(g->builder, fail_block);
    1430                 :        292 :         gen_safety_crash(g, PanicMsgIdCastNegativeToUnsigned);
    1431                 :            : 
    1432                 :        292 :         LLVMPositionBuilderAtEnd(g->builder, ok_block);
    1433                 :            :     }
    1434                 :            : 
    1435         [ +  + ]:       8602 :     if (actual_bits == wanted_bits) {
    1436                 :        846 :         return expr_val;
    1437         [ +  + ]:       7756 :     } else if (actual_bits < wanted_bits) {
    1438         [ +  + ]:       5994 :         if (actual_type->id == ZigTypeIdFloat) {
    1439                 :         56 :             return LLVMBuildFPExt(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    1440         [ +  - ]:       5938 :         } else if (actual_type->id == ZigTypeIdInt) {
    1441         [ +  + ]:       5938 :             if (actual_type->data.integral.is_signed) {
    1442                 :        239 :                 return LLVMBuildSExt(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    1443                 :            :             } else {
    1444                 :       5699 :                 return LLVMBuildZExt(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    1445                 :            :             }
    1446                 :            :         } else {
    1447                 :          0 :             zig_unreachable();
    1448                 :            :         }
    1449         [ +  - ]:       1762 :     } else if (actual_bits > wanted_bits) {
    1450         [ +  + ]:       1762 :         if (actual_type->id == ZigTypeIdFloat) {
    1451                 :          8 :             return LLVMBuildFPTrunc(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    1452         [ +  - ]:       1754 :         } else if (actual_type->id == ZigTypeIdInt) {
    1453         [ -  + ]:       1754 :             if (wanted_bits == 0) {
    1454         [ #  # ]:          0 :                 if (!want_runtime_safety)
    1455                 :          0 :                     return nullptr;
    1456                 :            : 
    1457                 :          0 :                 return gen_assert_zero(g, expr_val, actual_type);
    1458                 :            :             }
    1459                 :       1754 :             LLVMValueRef trunc_val = LLVMBuildTrunc(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    1460         [ +  + ]:       1754 :             if (!want_runtime_safety) {
    1461                 :        953 :                 return trunc_val;
    1462                 :            :             }
    1463                 :            :             LLVMValueRef orig_val;
    1464         [ +  + ]:        801 :             if (wanted_type->data.integral.is_signed) {
    1465                 :         70 :                 orig_val = LLVMBuildSExt(g->builder, trunc_val, get_llvm_type(g, actual_type), "");
    1466                 :            :             } else {
    1467                 :        731 :                 orig_val = LLVMBuildZExt(g->builder, trunc_val, get_llvm_type(g, actual_type), "");
    1468                 :            :             }
    1469                 :        801 :             LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, expr_val, orig_val, "");
    1470                 :        801 :             LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "CastShortenOk");
    1471                 :        801 :             LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "CastShortenFail");
    1472                 :        801 :             LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    1473                 :            : 
    1474                 :        801 :             LLVMPositionBuilderAtEnd(g->builder, fail_block);
    1475                 :        801 :             gen_safety_crash(g, PanicMsgIdCastTruncatedData);
    1476                 :            : 
    1477                 :        801 :             LLVMPositionBuilderAtEnd(g->builder, ok_block);
    1478                 :        801 :             return trunc_val;
    1479                 :            :         } else {
    1480                 :          0 :             zig_unreachable();
    1481                 :            :         }
    1482                 :            :     } else {
    1483                 :          0 :         zig_unreachable();
    1484                 :            :     }
    1485                 :            : }
    1486                 :            : 
    1487                 :            : typedef LLVMValueRef (*BuildBinOpFunc)(LLVMBuilderRef, LLVMValueRef, LLVMValueRef, const char *);
    1488                 :            : // These are lookup table using the AddSubMul enum as the lookup.
    1489                 :            : // If AddSubMul ever changes, then these tables will be out of
    1490                 :            : // date.
    1491                 :            : static const BuildBinOpFunc float_op[3] = { LLVMBuildFAdd, LLVMBuildFSub, LLVMBuildFMul };
    1492                 :            : static const BuildBinOpFunc wrap_op[3] = { LLVMBuildAdd, LLVMBuildSub, LLVMBuildMul };
    1493                 :            : static const BuildBinOpFunc signed_op[3] = { LLVMBuildNSWAdd, LLVMBuildNSWSub, LLVMBuildNSWMul };
    1494                 :            : static const BuildBinOpFunc unsigned_op[3] = { LLVMBuildNUWAdd, LLVMBuildNUWSub, LLVMBuildNUWMul };
    1495                 :            : 
    1496                 :       6158 : static LLVMValueRef gen_overflow_op(CodeGen *g, ZigType *operand_type, AddSubMul op,
    1497                 :            :         LLVMValueRef val1, LLVMValueRef val2)
    1498                 :            : {
    1499                 :            :     LLVMValueRef overflow_bit;
    1500                 :            :     LLVMValueRef result;
    1501                 :            : 
    1502         [ +  + ]:       6158 :     if (operand_type->id == ZigTypeIdVector) {
    1503                 :         40 :         ZigType *int_type = operand_type->data.vector.elem_type;
    1504                 :         40 :         assert(int_type->id == ZigTypeIdInt);
    1505                 :         40 :         LLVMTypeRef one_more_bit_int = LLVMIntType(int_type->data.integral.bit_count + 1);
    1506                 :         40 :         LLVMTypeRef one_more_bit_int_vector = LLVMVectorType(one_more_bit_int, operand_type->data.vector.len);
    1507         [ +  - ]:         40 :         const auto buildExtFn = int_type->data.integral.is_signed ? LLVMBuildSExt : LLVMBuildZExt;
    1508                 :         40 :         LLVMValueRef extended1 = buildExtFn(g->builder, val1, one_more_bit_int_vector, "");
    1509                 :         40 :         LLVMValueRef extended2 = buildExtFn(g->builder, val2, one_more_bit_int_vector, "");
    1510                 :         40 :         LLVMValueRef extended_result = wrap_op[op](g->builder, extended1, extended2, "");
    1511                 :         40 :         result = LLVMBuildTrunc(g->builder, extended_result, get_llvm_type(g, operand_type), "");
    1512                 :            : 
    1513                 :         40 :         LLVMValueRef re_extended_result = buildExtFn(g->builder, result, one_more_bit_int_vector, "");
    1514                 :         40 :         LLVMValueRef overflow_vector = LLVMBuildICmp(g->builder, LLVMIntNE, extended_result, re_extended_result, "");
    1515                 :         40 :         LLVMTypeRef bitcast_int_type = LLVMIntType(operand_type->data.vector.len);
    1516                 :         40 :         LLVMValueRef bitcasted_overflow = LLVMBuildBitCast(g->builder, overflow_vector, bitcast_int_type, "");
    1517                 :         40 :         LLVMValueRef zero = LLVMConstNull(bitcast_int_type);
    1518                 :         40 :         overflow_bit = LLVMBuildICmp(g->builder, LLVMIntNE, bitcasted_overflow, zero, "");
    1519                 :            :     } else {
    1520                 :       6118 :         LLVMValueRef fn_val = get_int_overflow_fn(g, operand_type, op);
    1521                 :            :         LLVMValueRef params[] = {
    1522                 :            :             val1,
    1523                 :            :             val2,
    1524                 :       6118 :         };
    1525                 :       6118 :         LLVMValueRef result_struct = LLVMBuildCall(g->builder, fn_val, params, 2, "");
    1526                 :       6118 :         result = LLVMBuildExtractValue(g->builder, result_struct, 0, "");
    1527                 :       6118 :         overflow_bit = LLVMBuildExtractValue(g->builder, result_struct, 1, "");
    1528                 :            :     }
    1529                 :            : 
    1530                 :       6158 :     LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "OverflowFail");
    1531                 :       6158 :     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "OverflowOk");
    1532                 :       6158 :     LLVMBuildCondBr(g->builder, overflow_bit, fail_block, ok_block);
    1533                 :            : 
    1534                 :       6158 :     LLVMPositionBuilderAtEnd(g->builder, fail_block);
    1535                 :       6158 :     gen_safety_crash(g, PanicMsgIdIntegerOverflow);
    1536                 :            : 
    1537                 :       6158 :     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    1538                 :       6158 :     return result;
    1539                 :            : }
    1540                 :            : 
    1541                 :      13948 : static LLVMIntPredicate cmp_op_to_int_predicate(IrBinOp cmp_op, bool is_signed) {
    1542   [ +  +  +  +  :      13948 :     switch (cmp_op) {
                +  +  - ]
    1543                 :       8473 :         case IrBinOpCmpEq:
    1544                 :       8473 :             return LLVMIntEQ;
    1545                 :       1277 :         case IrBinOpCmpNotEq:
    1546                 :       1277 :             return LLVMIntNE;
    1547                 :       1752 :         case IrBinOpCmpLessThan:
    1548         [ +  + ]:       1752 :             return is_signed ? LLVMIntSLT : LLVMIntULT;
    1549                 :       1023 :         case IrBinOpCmpGreaterThan:
    1550         [ +  + ]:       1023 :             return is_signed ? LLVMIntSGT : LLVMIntUGT;
    1551                 :        349 :         case IrBinOpCmpLessOrEq:
    1552         [ +  + ]:        349 :             return is_signed ? LLVMIntSLE : LLVMIntULE;
    1553                 :       1074 :         case IrBinOpCmpGreaterOrEq:
    1554         [ +  + ]:       1074 :             return is_signed ? LLVMIntSGE : LLVMIntUGE;
    1555                 :          0 :         default:
    1556                 :          0 :             zig_unreachable();
    1557                 :            :     }
    1558                 :            : }
    1559                 :            : 
    1560                 :       1192 : static LLVMRealPredicate cmp_op_to_real_predicate(IrBinOp cmp_op) {
    1561   [ +  +  +  +  :       1192 :     switch (cmp_op) {
                +  +  - ]
    1562                 :        690 :         case IrBinOpCmpEq:
    1563                 :        690 :             return LLVMRealOEQ;
    1564                 :        108 :         case IrBinOpCmpNotEq:
    1565                 :        108 :             return LLVMRealUNE;
    1566                 :        138 :         case IrBinOpCmpLessThan:
    1567                 :        138 :             return LLVMRealOLT;
    1568                 :        132 :         case IrBinOpCmpGreaterThan:
    1569                 :        132 :             return LLVMRealOGT;
    1570                 :         40 :         case IrBinOpCmpLessOrEq:
    1571                 :         40 :             return LLVMRealOLE;
    1572                 :         84 :         case IrBinOpCmpGreaterOrEq:
    1573                 :         84 :             return LLVMRealOGE;
    1574                 :          0 :         default:
    1575                 :          0 :             zig_unreachable();
    1576                 :            :     }
    1577                 :            : }
    1578                 :            : 
    1579                 :      38886 : static void gen_assign_raw(CodeGen *g, LLVMValueRef ptr, ZigType *ptr_type,
    1580                 :            :         LLVMValueRef value)
    1581                 :            : {
    1582                 :      38886 :     assert(ptr_type->id == ZigTypeIdPointer);
    1583                 :      38886 :     ZigType *child_type = ptr_type->data.pointer.child_type;
    1584                 :            : 
    1585         [ -  + ]:      38886 :     if (!type_has_bits(child_type))
    1586                 :          0 :         return;
    1587                 :            : 
    1588         [ +  + ]:      38886 :     if (handle_is_ptr(child_type)) {
    1589                 :       6936 :         assert(LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMPointerTypeKind);
    1590                 :       6936 :         assert(LLVMGetTypeKind(LLVMTypeOf(ptr)) == LLVMPointerTypeKind);
    1591                 :            : 
    1592                 :       6936 :         LLVMTypeRef ptr_u8 = LLVMPointerType(LLVMInt8Type(), 0);
    1593                 :            : 
    1594                 :       6936 :         LLVMValueRef src_ptr = LLVMBuildBitCast(g->builder, value, ptr_u8, "");
    1595                 :       6936 :         LLVMValueRef dest_ptr = LLVMBuildBitCast(g->builder, ptr, ptr_u8, "");
    1596                 :            : 
    1597                 :       6936 :         ZigType *usize = g->builtin_types.entry_usize;
    1598                 :       6936 :         uint64_t size_bytes = LLVMStoreSizeOfType(g->target_data_ref, get_llvm_type(g, child_type));
    1599                 :       6936 :         uint64_t align_bytes = get_ptr_align(g, ptr_type);
    1600                 :       6936 :         assert(size_bytes > 0);
    1601                 :       6936 :         assert(align_bytes > 0);
    1602                 :            : 
    1603                 :       6936 :         ZigLLVMBuildMemCpy(g->builder, dest_ptr, align_bytes, src_ptr, align_bytes,
    1604                 :            :                 LLVMConstInt(usize->llvm_type, size_bytes, false),
    1605                 :       6936 :                 ptr_type->data.pointer.is_volatile);
    1606                 :       6936 :         return;
    1607                 :            :     }
    1608                 :            : 
    1609                 :      31950 :     uint32_t host_int_bytes = ptr_type->data.pointer.host_int_bytes;
    1610         [ +  + ]:      31950 :     if (host_int_bytes == 0) {
    1611                 :      31774 :         gen_store(g, value, ptr, ptr_type);
    1612                 :      31774 :         return;
    1613                 :            :     }
    1614                 :            : 
    1615                 :        176 :     bool big_endian = g->is_big_endian;
    1616                 :            : 
    1617                 :        176 :     LLVMValueRef containing_int = gen_load(g, ptr, ptr_type, "");
    1618                 :        176 :     uint32_t host_bit_count = LLVMGetIntTypeWidth(LLVMTypeOf(containing_int));
    1619                 :        176 :     assert(host_bit_count == host_int_bytes * 8);
    1620                 :        176 :     uint32_t size_in_bits = type_size_bits(g, child_type);
    1621                 :            : 
    1622                 :        176 :     uint32_t bit_offset = ptr_type->data.pointer.bit_offset_in_host;
    1623         [ -  + ]:        176 :     uint32_t shift_amt = big_endian ? host_bit_count - bit_offset - size_in_bits : bit_offset;
    1624                 :        176 :     LLVMValueRef shift_amt_val = LLVMConstInt(LLVMTypeOf(containing_int), shift_amt, false);
    1625                 :            : 
    1626                 :            :     // Convert to equally-sized integer type in order to perform the bit
    1627                 :            :     // operations on the value to store
    1628                 :        176 :     LLVMTypeRef value_bits_type = LLVMIntType(size_in_bits);
    1629                 :        176 :     LLVMValueRef value_bits = LLVMBuildBitCast(g->builder, value, value_bits_type, "");
    1630                 :            : 
    1631                 :        176 :     LLVMValueRef mask_val = LLVMConstAllOnes(value_bits_type);
    1632                 :        176 :     mask_val = LLVMConstZExt(mask_val, LLVMTypeOf(containing_int));
    1633                 :        176 :     mask_val = LLVMConstShl(mask_val, shift_amt_val);
    1634                 :        176 :     mask_val = LLVMConstNot(mask_val);
    1635                 :            : 
    1636                 :        176 :     LLVMValueRef anded_containing_int = LLVMBuildAnd(g->builder, containing_int, mask_val, "");
    1637                 :        176 :     LLVMValueRef extended_value = LLVMBuildZExt(g->builder, value_bits, LLVMTypeOf(containing_int), "");
    1638                 :        176 :     LLVMValueRef shifted_value = LLVMBuildShl(g->builder, extended_value, shift_amt_val, "");
    1639                 :        176 :     LLVMValueRef ored_value = LLVMBuildOr(g->builder, shifted_value, anded_containing_int, "");
    1640                 :            : 
    1641                 :        176 :     gen_store(g, ored_value, ptr, ptr_type);
    1642                 :        176 :     return;
    1643                 :            : }
    1644                 :            : 
    1645                 :      51981 : static void gen_var_debug_decl(CodeGen *g, ZigVar *var) {
    1646         [ -  + ]:      51981 :     if (g->strip_debug_symbols) return;
    1647                 :      51981 :     assert(var->di_loc_var != nullptr);
    1648                 :      51981 :     AstNode *source_node = var->decl_node;
    1649                 :      51981 :     ZigLLVMDILocation *debug_loc = ZigLLVMGetDebugLoc((unsigned)source_node->line + 1,
    1650                 :      51981 :             (unsigned)source_node->column + 1, get_di_scope(g, var->parent_scope));
    1651                 :      51981 :     ZigLLVMInsertDeclareAtEnd(g->dbuilder, var->value_ref, var->di_loc_var, debug_loc,
    1652                 :            :             LLVMGetInsertBlock(g->builder));
    1653                 :            : }
    1654                 :            : 
    1655                 :     553202 : static LLVMValueRef ir_llvm_value(CodeGen *g, IrInstruction *instruction) {
    1656         [ +  + ]:     553202 :     if (!type_has_bits(instruction->value.type))
    1657                 :       7975 :         return nullptr;
    1658         [ +  + ]:     545227 :     if (!instruction->llvm_value) {
    1659                 :      83535 :         src_assert(instruction->value.special != ConstValSpecialRuntime, instruction->source_node);
    1660                 :      83535 :         assert(instruction->value.type);
    1661                 :      83535 :         render_const_val(g, &instruction->value, "");
    1662                 :            :         // we might have to do some pointer casting here due to the way union
    1663                 :            :         // values are rendered with a type other than the one we expect
    1664         [ +  + ]:      83535 :         if (handle_is_ptr(instruction->value.type)) {
    1665                 :      11170 :             render_const_val_global(g, &instruction->value, "");
    1666                 :      11170 :             ZigType *ptr_type = get_pointer_to_type(g, instruction->value.type, true);
    1667                 :      11170 :             instruction->llvm_value = LLVMBuildBitCast(g->builder, instruction->value.global_refs->llvm_global, get_llvm_type(g, ptr_type), "");
    1668                 :            :         } else {
    1669                 :      72365 :             instruction->llvm_value = LLVMBuildBitCast(g->builder, instruction->value.global_refs->llvm_value,
    1670                 :            :                     get_llvm_type(g, instruction->value.type), "");
    1671                 :            :         }
    1672                 :      83535 :         assert(instruction->llvm_value);
    1673                 :            :     }
    1674                 :     545227 :     return instruction->llvm_value;
    1675                 :            : }
    1676                 :            : 
    1677                 :            : ATTRIBUTE_NORETURN
    1678                 :          0 : static void report_errors_and_exit(CodeGen *g) {
    1679                 :          0 :     assert(g->errors.length != 0);
    1680         [ #  # ]:          0 :     for (size_t i = 0; i < g->errors.length; i += 1) {
    1681                 :          0 :         ErrorMsg *err = g->errors.at(i);
    1682                 :          0 :         print_err_msg(err, g->err_color);
    1683                 :            :     }
    1684                 :          0 :     exit(1);
    1685                 :            : }
    1686                 :            : 
    1687                 :         68 : static void report_errors_and_maybe_exit(CodeGen *g) {
    1688         [ -  + ]:         68 :     if (g->errors.length != 0) {
    1689                 :          0 :         report_errors_and_exit(g);
    1690                 :            :     }
    1691                 :         68 : }
    1692                 :            : 
    1693                 :            : ATTRIBUTE_NORETURN
    1694                 :          0 : static void give_up_with_c_abi_error(CodeGen *g, AstNode *source_node) {
    1695                 :          0 :     ErrorMsg *msg = add_node_error(g, source_node,
    1696                 :          0 :             buf_sprintf("TODO: support C ABI for more targets. https://github.com/ziglang/zig/issues/1481"));
    1697                 :          0 :     add_error_note(g, msg, source_node,
    1698                 :            :         buf_sprintf("pointers, integers, floats, bools, and enums work on all targets"));
    1699                 :          0 :     report_errors_and_exit(g);
    1700                 :            : }
    1701                 :            : 
    1702                 :      50722 : static LLVMValueRef build_alloca(CodeGen *g, ZigType *type_entry, const char *name, uint32_t alignment) {
    1703                 :      50722 :     LLVMValueRef result = LLVMBuildAlloca(g->builder, get_llvm_type(g, type_entry), name);
    1704         [ +  + ]:      50722 :     LLVMSetAlignment(result, (alignment == 0) ? get_abi_alignment(g, type_entry) : alignment);
    1705                 :      50722 :     return result;
    1706                 :            : }
    1707                 :            : 
    1708                 :      12183 : static bool iter_function_params_c_abi(CodeGen *g, ZigType *fn_type, FnWalk *fn_walk, size_t src_i) {
    1709                 :            :     // Initialized from the type for some walks, but because of C var args,
    1710                 :            :     // initialized based on callsite instructions for that one.
    1711                 :      12183 :     FnTypeParamInfo *param_info = nullptr;
    1712                 :            :     ZigType *ty;
    1713                 :      12183 :     ZigType *dest_ty = nullptr;
    1714                 :      12183 :     AstNode *source_node = nullptr;
    1715                 :            :     LLVMValueRef val;
    1716                 :            :     LLVMValueRef llvm_fn;
    1717                 :            :     unsigned di_arg_index;
    1718                 :            :     ZigVar *var;
    1719   [ +  +  +  +  :      12183 :     switch (fn_walk->id) {
                   +  - ]
    1720                 :       4940 :         case FnWalkIdAttrs:
    1721         [ +  + ]:       4940 :             if (src_i >= fn_type->data.fn.fn_type_id.param_count)
    1722                 :       4031 :                 return false;
    1723                 :        909 :             param_info = &fn_type->data.fn.fn_type_id.param_info[src_i];
    1724                 :        909 :             ty = param_info->type;
    1725                 :        909 :             source_node = fn_walk->data.attrs.fn->proto_node;
    1726                 :        909 :             llvm_fn = fn_walk->data.attrs.llvm_fn;
    1727                 :        909 :             break;
    1728                 :        544 :         case FnWalkIdCall: {
    1729         [ +  + ]:        544 :             if (src_i >= fn_walk->data.call.inst->arg_count)
    1730                 :        194 :                 return false;
    1731                 :        350 :             IrInstruction *arg = fn_walk->data.call.inst->args[src_i];
    1732                 :        350 :             ty = arg->value.type;
    1733                 :        350 :             source_node = arg->source_node;
    1734                 :        350 :             val = ir_llvm_value(g, arg);
    1735                 :        350 :             break;
    1736                 :            :         }
    1737                 :       1072 :         case FnWalkIdTypes:
    1738         [ +  + ]:       1072 :             if (src_i >= fn_type->data.fn.fn_type_id.param_count)
    1739                 :        423 :                 return false;
    1740                 :        649 :             param_info = &fn_type->data.fn.fn_type_id.param_info[src_i];
    1741                 :        649 :             ty = param_info->type;
    1742                 :        649 :             break;
    1743                 :        819 :         case FnWalkIdVars:
    1744                 :        819 :             assert(src_i < fn_type->data.fn.fn_type_id.param_count);
    1745                 :        819 :             param_info = &fn_type->data.fn.fn_type_id.param_info[src_i];
    1746                 :        819 :             ty = param_info->type;
    1747                 :        819 :             var = fn_walk->data.vars.var;
    1748                 :        819 :             source_node = var->decl_node;
    1749                 :        819 :             llvm_fn = fn_walk->data.vars.llvm_fn;
    1750                 :        819 :             break;
    1751                 :       4808 :         case FnWalkIdInits:
    1752         [ +  + ]:       4808 :             if (src_i >= fn_type->data.fn.fn_type_id.param_count)
    1753                 :       3989 :                 return false;
    1754                 :        819 :             param_info = &fn_type->data.fn.fn_type_id.param_info[src_i];
    1755                 :        819 :             ty = param_info->type;
    1756                 :        819 :             var = fn_walk->data.inits.fn->variable_list.at(src_i);
    1757                 :        819 :             source_node = fn_walk->data.inits.fn->proto_node;
    1758                 :        819 :             llvm_fn = fn_walk->data.inits.llvm_fn;
    1759                 :        819 :             break;
    1760                 :            :     }
    1761                 :            : 
    1762 [ +  + ][ +  - ]:       3546 :     if (type_is_c_abi_int(g, ty) || ty->id == ZigTypeIdFloat || ty->id == ZigTypeIdVector ||
         [ -  + ][ #  # ]
                 [ +  - ]
    1763                 :          0 :         ty->id == ZigTypeIdInt // TODO investigate if we need to change this
    1764                 :            :     ) {
    1765   [ +  +  +  +  :       3546 :         switch (fn_walk->id) {
                   +  - ]
    1766                 :        909 :             case FnWalkIdAttrs: {
    1767                 :        909 :                 ZigType *ptr_type = get_codegen_ptr_type(ty);
    1768         [ +  + ]:        909 :                 if (ptr_type != nullptr) {
    1769         [ +  + ]:        128 :                     if (type_is_nonnull_ptr(ty)) {
    1770                 :         93 :                         addLLVMArgAttr(llvm_fn, fn_walk->data.attrs.gen_i, "nonnull");
    1771                 :            :                     }
    1772         [ +  + ]:        128 :                     if (ptr_type->data.pointer.is_const) {
    1773                 :         48 :                         addLLVMArgAttr(llvm_fn, fn_walk->data.attrs.gen_i, "readonly");
    1774                 :            :                     }
    1775         [ +  + ]:        128 :                     if (param_info->is_noalias) {
    1776                 :          8 :                         addLLVMArgAttr(llvm_fn, fn_walk->data.attrs.gen_i, "noalias");
    1777                 :            :                     }
    1778                 :            :                 }
    1779                 :        909 :                 fn_walk->data.attrs.gen_i += 1;
    1780                 :        909 :                 break;
    1781                 :            :             }
    1782                 :        350 :             case FnWalkIdCall:
    1783                 :        350 :                 fn_walk->data.call.gen_param_values->append(val);
    1784                 :        350 :                 break;
    1785                 :        649 :             case FnWalkIdTypes:
    1786                 :        649 :                 fn_walk->data.types.gen_param_types->append(get_llvm_type(g, ty));
    1787                 :        649 :                 fn_walk->data.types.param_di_types->append(get_llvm_di_type(g, ty));
    1788                 :        649 :                 break;
    1789                 :        819 :             case FnWalkIdVars: {
    1790                 :        819 :                 var->value_ref = build_alloca(g, ty, buf_ptr(&var->name), var->align_bytes);
    1791                 :        819 :                 di_arg_index = fn_walk->data.vars.gen_i;
    1792                 :        819 :                 fn_walk->data.vars.gen_i += 1;
    1793                 :        819 :                 dest_ty = ty;
    1794                 :        819 :                 goto var_ok;
    1795                 :            :             }
    1796                 :        819 :             case FnWalkIdInits:
    1797                 :        819 :                 clear_debug_source_node(g);
    1798                 :        819 :                 gen_store_untyped(g, LLVMGetParam(llvm_fn, fn_walk->data.inits.gen_i), var->value_ref, var->align_bytes, false);
    1799         [ +  - ]:        819 :                 if (var->decl_node) {
    1800                 :        819 :                     gen_var_debug_decl(g, var);
    1801                 :            :                 }
    1802                 :        819 :                 fn_walk->data.inits.gen_i += 1;
    1803                 :        819 :                 break;
    1804                 :            :         }
    1805                 :       2727 :         return true;
    1806                 :            :     }
    1807                 :            : 
    1808                 :            :     // Arrays are just pointers
    1809         [ #  # ]:          0 :     if (ty->id == ZigTypeIdArray) {
    1810                 :          0 :         assert(handle_is_ptr(ty));
    1811   [ #  #  #  #  :          0 :         switch (fn_walk->id) {
                   #  # ]
    1812                 :          0 :             case FnWalkIdAttrs:
    1813                 :            :                 // arrays passed to C ABI functions may not be at address 0
    1814                 :          0 :                 addLLVMArgAttr(llvm_fn, fn_walk->data.attrs.gen_i, "nonnull");
    1815                 :          0 :                 addLLVMArgAttrInt(llvm_fn, fn_walk->data.attrs.gen_i, "align", get_abi_alignment(g, ty));
    1816                 :          0 :                 fn_walk->data.attrs.gen_i += 1;
    1817                 :          0 :                 break;
    1818                 :          0 :             case FnWalkIdCall:
    1819                 :          0 :                 fn_walk->data.call.gen_param_values->append(val);
    1820                 :          0 :                 break;
    1821                 :          0 :             case FnWalkIdTypes: {
    1822                 :          0 :                 ZigType *gen_type = get_pointer_to_type(g, ty, true);
    1823                 :          0 :                 fn_walk->data.types.gen_param_types->append(get_llvm_type(g, gen_type));
    1824                 :          0 :                 fn_walk->data.types.param_di_types->append(get_llvm_di_type(g, gen_type));
    1825                 :          0 :                 break;
    1826                 :            :             }
    1827                 :          0 :             case FnWalkIdVars: {
    1828                 :          0 :                 var->value_ref = LLVMGetParam(llvm_fn,  fn_walk->data.vars.gen_i);
    1829                 :          0 :                 di_arg_index = fn_walk->data.vars.gen_i;
    1830                 :          0 :                 dest_ty = get_pointer_to_type(g, ty, false);
    1831                 :          0 :                 fn_walk->data.vars.gen_i += 1;
    1832                 :          0 :                 goto var_ok;
    1833                 :            :             }
    1834                 :          0 :             case FnWalkIdInits:
    1835         [ #  # ]:          0 :                 if (var->decl_node) {
    1836                 :          0 :                     gen_var_debug_decl(g, var);
    1837                 :            :                 }
    1838                 :          0 :                 fn_walk->data.inits.gen_i += 1;
    1839                 :          0 :                 break;
    1840                 :            :         }
    1841                 :          0 :         return true;
    1842                 :            :     }
    1843                 :            : 
    1844         [ #  # ]:          0 :     if (g->zig_target->arch == ZigLLVM_x86_64) {
    1845                 :          0 :         X64CABIClass abi_class = type_c_abi_x86_64_class(g, ty);
    1846                 :          0 :         size_t ty_size = type_size(g, ty);
    1847         [ #  # ]:          0 :         if (abi_class == X64CABIClass_MEMORY) {
    1848                 :          0 :             assert(handle_is_ptr(ty));
    1849   [ #  #  #  #  :          0 :             switch (fn_walk->id) {
                   #  # ]
    1850                 :          0 :                 case FnWalkIdAttrs:
    1851                 :          0 :                     addLLVMArgAttr(llvm_fn, fn_walk->data.attrs.gen_i, "byval");
    1852                 :          0 :                     addLLVMArgAttrInt(llvm_fn, fn_walk->data.attrs.gen_i, "align", get_abi_alignment(g, ty));
    1853                 :            :                     // Byvalue parameters must not have address 0
    1854                 :          0 :                     addLLVMArgAttr(llvm_fn, fn_walk->data.attrs.gen_i, "nonnull");
    1855                 :          0 :                     fn_walk->data.attrs.gen_i += 1;
    1856                 :          0 :                     break;
    1857                 :          0 :                 case FnWalkIdCall:
    1858                 :          0 :                     fn_walk->data.call.gen_param_values->append(val);
    1859                 :          0 :                     break;
    1860                 :          0 :                 case FnWalkIdTypes: {
    1861                 :          0 :                     ZigType *gen_type = get_pointer_to_type(g, ty, true);
    1862                 :          0 :                     fn_walk->data.types.gen_param_types->append(get_llvm_type(g, gen_type));
    1863                 :          0 :                     fn_walk->data.types.param_di_types->append(get_llvm_di_type(g, gen_type));
    1864                 :          0 :                     break;
    1865                 :            :                 }
    1866                 :          0 :                 case FnWalkIdVars: {
    1867                 :          0 :                     di_arg_index = fn_walk->data.vars.gen_i;
    1868                 :          0 :                     var->value_ref = LLVMGetParam(llvm_fn,  fn_walk->data.vars.gen_i);
    1869                 :          0 :                     dest_ty = get_pointer_to_type(g, ty, false);
    1870                 :          0 :                     fn_walk->data.vars.gen_i += 1;
    1871                 :          0 :                     goto var_ok;
    1872                 :            :                 }
    1873                 :          0 :                 case FnWalkIdInits:
    1874         [ #  # ]:          0 :                     if (var->decl_node) {
    1875                 :          0 :                         gen_var_debug_decl(g, var);
    1876                 :            :                     }
    1877                 :          0 :                     fn_walk->data.inits.gen_i += 1;
    1878                 :          0 :                     break;
    1879                 :            :             }
    1880                 :          0 :             return true;
    1881         [ #  # ]:          0 :         } else if (abi_class == X64CABIClass_INTEGER) {
    1882   [ #  #  #  #  :          0 :             switch (fn_walk->id) {
                   #  # ]
    1883                 :          0 :                 case FnWalkIdAttrs:
    1884                 :          0 :                     fn_walk->data.attrs.gen_i += 1;
    1885                 :          0 :                     break;
    1886                 :          0 :                 case FnWalkIdCall: {
    1887                 :          0 :                     LLVMTypeRef ptr_to_int_type_ref = LLVMPointerType(LLVMIntType((unsigned)ty_size * 8), 0);
    1888                 :          0 :                     LLVMValueRef bitcasted = LLVMBuildBitCast(g->builder, val, ptr_to_int_type_ref, "");
    1889                 :          0 :                     LLVMValueRef loaded = LLVMBuildLoad(g->builder, bitcasted, "");
    1890                 :          0 :                     fn_walk->data.call.gen_param_values->append(loaded);
    1891                 :          0 :                     break;
    1892                 :            :                 }
    1893                 :          0 :                 case FnWalkIdTypes: {
    1894                 :          0 :                     ZigType *gen_type = get_int_type(g, false, ty_size * 8);
    1895                 :          0 :                     fn_walk->data.types.gen_param_types->append(get_llvm_type(g, gen_type));
    1896                 :          0 :                     fn_walk->data.types.param_di_types->append(get_llvm_di_type(g, gen_type));
    1897                 :          0 :                     break;
    1898                 :            :                 }
    1899                 :          0 :                 case FnWalkIdVars: {
    1900                 :          0 :                     di_arg_index = fn_walk->data.vars.gen_i;
    1901                 :          0 :                     var->value_ref = build_alloca(g, ty, buf_ptr(&var->name), var->align_bytes);
    1902                 :          0 :                     fn_walk->data.vars.gen_i += 1;
    1903                 :          0 :                     dest_ty = ty;
    1904                 :          0 :                     goto var_ok;
    1905                 :            :                 }
    1906                 :          0 :                 case FnWalkIdInits: {
    1907                 :          0 :                     clear_debug_source_node(g);
    1908         [ #  # ]:          0 :                     if (!fn_is_async(fn_walk->data.inits.fn)) {
    1909                 :          0 :                         LLVMValueRef arg = LLVMGetParam(llvm_fn, fn_walk->data.inits.gen_i);
    1910                 :          0 :                         LLVMTypeRef ptr_to_int_type_ref = LLVMPointerType(LLVMIntType((unsigned)ty_size * 8), 0);
    1911                 :          0 :                         LLVMValueRef bitcasted = LLVMBuildBitCast(g->builder, var->value_ref, ptr_to_int_type_ref, "");
    1912                 :          0 :                         gen_store_untyped(g, arg, bitcasted, var->align_bytes, false);
    1913                 :            :                     }
    1914         [ #  # ]:          0 :                     if (var->decl_node) {
    1915                 :          0 :                         gen_var_debug_decl(g, var);
    1916                 :            :                     }
    1917                 :          0 :                     fn_walk->data.inits.gen_i += 1;
    1918                 :          0 :                     break;
    1919                 :            :                 }
    1920                 :            :             }
    1921                 :          0 :             return true;
    1922                 :            :         }
    1923                 :            :     }
    1924         [ #  # ]:          0 :     if (source_node != nullptr) {
    1925                 :          0 :         give_up_with_c_abi_error(g, source_node);
    1926                 :            :     }
    1927                 :            :     // otherwise allow codegen code to report a compile error
    1928                 :          0 :     return false;
    1929                 :            : 
    1930                 :        819 : var_ok:
    1931 [ +  - ][ +  - ]:        819 :     if (dest_ty != nullptr && var->decl_node) {
    1932                 :            :         // arg index + 1 because the 0 index is return value
    1933                 :       1638 :         var->di_loc_var = ZigLLVMCreateParameterVariable(g->dbuilder, get_di_scope(g, var->parent_scope),
    1934                 :        819 :                 buf_ptr(&var->name), fn_walk->data.vars.import->data.structure.root_struct->di_file,
    1935                 :        819 :                 (unsigned)(var->decl_node->line + 1),
    1936                 :        819 :                 get_llvm_di_type(g, dest_ty), !g->strip_debug_symbols, 0, di_arg_index + 1);
    1937                 :            :     }
    1938                 :        819 :     return true;
    1939                 :            : }
    1940                 :            : 
    1941                 :      93190 : void walk_function_params(CodeGen *g, ZigType *fn_type, FnWalk *fn_walk) {
    1942                 :      93190 :     CallingConvention cc = fn_type->data.fn.fn_type_id.cc;
    1943         [ +  + ]:      93190 :     if (cc == CallingConventionC) {
    1944                 :       8637 :         size_t src_i = 0;
    1945                 :            :         for (;;) {
    1946         [ +  + ]:      11364 :             if (!iter_function_params_c_abi(g, fn_type, fn_walk, src_i))
    1947                 :       8637 :                 break;
    1948                 :       2727 :             src_i += 1;
    1949                 :            :         }
    1950                 :       8637 :         return;
    1951                 :            :     }
    1952         [ +  + ]:      84553 :     if (fn_walk->id == FnWalkIdCall) {
    1953                 :      45521 :         IrInstructionCallGen *instruction = fn_walk->data.call.inst;
    1954                 :      45521 :         bool is_var_args = fn_walk->data.call.is_var_args;
    1955         [ +  + ]:     117795 :         for (size_t call_i = 0; call_i < instruction->arg_count; call_i += 1) {
    1956                 :      72274 :             IrInstruction *param_instruction = instruction->args[call_i];
    1957                 :      72274 :             ZigType *param_type = param_instruction->value.type;
    1958 [ +  - ][ +  + ]:      72274 :             if (is_var_args || type_has_bits(param_type)) {
                 [ +  + ]
    1959                 :      72066 :                 LLVMValueRef param_value = ir_llvm_value(g, param_instruction);
    1960                 :      72066 :                 assert(param_value);
    1961                 :      72066 :                 fn_walk->data.call.gen_param_values->append(param_value);
    1962                 :      72066 :                 fn_walk->data.call.gen_param_types->append(param_type);
    1963                 :            :             }
    1964                 :            :         }
    1965                 :      45521 :         return;
    1966                 :            :     }
    1967                 :      39032 :     size_t next_var_i = 0;
    1968         [ +  + ]:      91049 :     for (size_t param_i = 0; param_i < fn_type->data.fn.fn_type_id.param_count; param_i += 1) {
    1969                 :      52017 :         FnGenParamInfo *gen_info = &fn_type->data.fn.gen_param_info[param_i];
    1970                 :      52017 :         size_t gen_index = gen_info->gen_index;
    1971                 :            : 
    1972         [ +  + ]:      52017 :         if (gen_index == SIZE_MAX) {
    1973                 :        352 :             continue;
    1974                 :            :         }
    1975                 :            : 
    1976   [ +  +  -  -  :      51665 :         switch (fn_walk->id) {
                   -  - ]
    1977                 :      25902 :             case FnWalkIdAttrs: {
    1978                 :      25902 :                 LLVMValueRef llvm_fn = fn_walk->data.attrs.llvm_fn;
    1979                 :      25902 :                 bool is_byval = gen_info->is_byval;
    1980                 :      25902 :                 FnTypeParamInfo *param_info = &fn_type->data.fn.fn_type_id.param_info[param_i];
    1981                 :            : 
    1982                 :      25902 :                 ZigType *param_type = gen_info->type;
    1983         [ +  + ]:      25902 :                 if (param_info->is_noalias) {
    1984                 :          8 :                     addLLVMArgAttr(llvm_fn, (unsigned)gen_index, "noalias");
    1985                 :            :                 }
    1986 [ +  + ][ +  + ]:      25902 :                 if ((param_type->id == ZigTypeIdPointer && param_type->data.pointer.is_const) || is_byval) {
                 [ -  + ]
    1987                 :       8942 :                     addLLVMArgAttr(llvm_fn, (unsigned)gen_index, "readonly");
    1988                 :            :                 }
    1989         [ +  + ]:      25902 :                 if (get_codegen_ptr_type(param_type) != nullptr) {
    1990                 :      17589 :                     addLLVMArgAttrInt(llvm_fn, (unsigned)gen_index, "align", get_ptr_align(g, param_type));
    1991                 :            :                 }
    1992         [ +  + ]:      25902 :                 if (type_is_nonnull_ptr(param_type)) {
    1993                 :      17275 :                     addLLVMArgAttr(llvm_fn, (unsigned)gen_index, "nonnull");
    1994                 :            :                 }
    1995                 :      25902 :                 break;
    1996                 :            :             }
    1997                 :      25763 :             case FnWalkIdInits: {
    1998                 :      25763 :                 ZigFn *fn_table_entry = fn_walk->data.inits.fn;
    1999                 :      25763 :                 LLVMValueRef llvm_fn = fn_table_entry->llvm_value;
    2000                 :      25763 :                 ZigVar *variable = fn_table_entry->variable_list.at(next_var_i);
    2001                 :      25763 :                 assert(variable->src_arg_index != SIZE_MAX);
    2002                 :      25763 :                 next_var_i += 1;
    2003                 :            : 
    2004                 :      25763 :                 assert(variable);
    2005                 :      25763 :                 assert(variable->value_ref);
    2006                 :            : 
    2007 [ +  - ][ +  + ]:      25763 :                 if (!handle_is_ptr(variable->var_type) && !fn_is_async(fn_walk->data.inits.fn)) {
                 [ +  + ]
    2008                 :      17400 :                     clear_debug_source_node(g);
    2009                 :      17400 :                     ZigType *fn_type = fn_table_entry->type_entry;
    2010                 :      17400 :                     unsigned gen_arg_index = fn_type->data.fn.gen_param_info[variable->src_arg_index].gen_index;
    2011                 :      17400 :                     gen_store_untyped(g, LLVMGetParam(llvm_fn, gen_arg_index),
    2012                 :            :                             variable->value_ref, variable->align_bytes, false);
    2013                 :            :                 }
    2014                 :            : 
    2015         [ +  - ]:      25763 :                 if (variable->decl_node) {
    2016                 :      25763 :                     gen_var_debug_decl(g, variable);
    2017                 :            :                 }
    2018                 :      25763 :                 break;
    2019                 :            :             }
    2020                 :          0 :             case FnWalkIdCall:
    2021                 :            :                 // handled before for loop
    2022                 :          0 :                 zig_unreachable();
    2023                 :          0 :             case FnWalkIdTypes:
    2024                 :            :                 // Not called for non-c-abi
    2025                 :          0 :                 zig_unreachable();
    2026                 :          0 :             case FnWalkIdVars:
    2027                 :            :                 // iter_function_params_c_abi is called directly for this one
    2028                 :          0 :                 zig_unreachable();
    2029                 :            :         }
    2030                 :            :     }
    2031                 :            : }
    2032                 :            : 
    2033                 :       1600 : static LLVMValueRef get_merge_err_ret_traces_fn_val(CodeGen *g) {
    2034         [ +  + ]:       1600 :     if (g->merge_err_ret_traces_fn_val)
    2035                 :       1592 :         return g->merge_err_ret_traces_fn_val;
    2036                 :            : 
    2037                 :          8 :     assert(g->stack_trace_type != nullptr);
    2038                 :            : 
    2039                 :            :     LLVMTypeRef param_types[] = {
    2040                 :          8 :         get_llvm_type(g, ptr_to_stack_trace_type(g)),
    2041                 :          8 :         get_llvm_type(g, ptr_to_stack_trace_type(g)),
    2042                 :         16 :     };
    2043                 :          8 :     LLVMTypeRef fn_type_ref = LLVMFunctionType(LLVMVoidType(), param_types, 2, false);
    2044                 :            : 
    2045                 :          8 :     Buf *fn_name = get_mangled_name(g, buf_create_from_str("__zig_merge_error_return_traces"), false);
    2046                 :          8 :     LLVMValueRef fn_val = LLVMAddFunction(g->module, buf_ptr(fn_name), fn_type_ref);
    2047                 :          8 :     LLVMSetLinkage(fn_val, LLVMInternalLinkage);
    2048                 :          8 :     LLVMSetFunctionCallConv(fn_val, get_llvm_cc(g, CallingConventionUnspecified));
    2049                 :          8 :     addLLVMFnAttr(fn_val, "nounwind");
    2050                 :          8 :     add_uwtable_attr(g, fn_val);
    2051                 :          8 :     addLLVMArgAttr(fn_val, (unsigned)0, "noalias");
    2052                 :          8 :     addLLVMArgAttr(fn_val, (unsigned)0, "writeonly");
    2053                 :            : 
    2054                 :          8 :     addLLVMArgAttr(fn_val, (unsigned)1, "noalias");
    2055                 :          8 :     addLLVMArgAttr(fn_val, (unsigned)1, "readonly");
    2056         [ +  - ]:          8 :     if (g->build_mode == BuildModeDebug) {
    2057                 :          8 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim", "true");
    2058                 :          8 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim-non-leaf", nullptr);
    2059                 :            :     }
    2060                 :            : 
    2061                 :            :     // this is above the ZigLLVMClearCurrentDebugLocation
    2062                 :          8 :     LLVMValueRef add_error_return_trace_addr_fn_val = get_add_error_return_trace_addr_fn(g);
    2063                 :            : 
    2064                 :          8 :     LLVMBasicBlockRef entry_block = LLVMAppendBasicBlock(fn_val, "Entry");
    2065                 :          8 :     LLVMBasicBlockRef prev_block = LLVMGetInsertBlock(g->builder);
    2066                 :          8 :     LLVMValueRef prev_debug_location = LLVMGetCurrentDebugLocation(g->builder);
    2067                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, entry_block);
    2068                 :          8 :     ZigLLVMClearCurrentDebugLocation(g->builder);
    2069                 :            : 
    2070                 :            :     // if (dest_stack_trace == null or src_stack_trace == null) return;
    2071                 :            :     // var frame_index: usize = undefined;
    2072                 :            :     // var frames_left: usize = undefined;
    2073                 :            :     // if (src_stack_trace.index < src_stack_trace.instruction_addresses.len) {
    2074                 :            :     //     frame_index = 0;
    2075                 :            :     //     frames_left = src_stack_trace.index;
    2076                 :            :     //     if (frames_left == 0) return;
    2077                 :            :     // } else {
    2078                 :            :     //     frame_index = (src_stack_trace.index + 1) % src_stack_trace.instruction_addresses.len;
    2079                 :            :     //     frames_left = src_stack_trace.instruction_addresses.len;
    2080                 :            :     // }
    2081                 :            :     // while (true) {
    2082                 :            :     //     __zig_add_err_ret_trace_addr(dest_stack_trace, src_stack_trace.instruction_addresses[frame_index]);
    2083                 :            :     //     frames_left -= 1;
    2084                 :            :     //     if (frames_left == 0) return;
    2085                 :            :     //     frame_index = (frame_index + 1) % src_stack_trace.instruction_addresses.len;
    2086                 :            :     // }
    2087                 :          8 :     LLVMBasicBlockRef return_block = LLVMAppendBasicBlock(fn_val, "Return");
    2088                 :          8 :     LLVMBasicBlockRef non_null_block = LLVMAppendBasicBlock(fn_val, "NonNull");
    2089                 :            : 
    2090                 :          8 :     LLVMValueRef frame_index_ptr = LLVMBuildAlloca(g->builder, g->builtin_types.entry_usize->llvm_type, "frame_index");
    2091                 :          8 :     LLVMValueRef frames_left_ptr = LLVMBuildAlloca(g->builder, g->builtin_types.entry_usize->llvm_type, "frames_left");
    2092                 :            : 
    2093                 :          8 :     LLVMValueRef dest_stack_trace_ptr = LLVMGetParam(fn_val, 0);
    2094                 :          8 :     LLVMValueRef src_stack_trace_ptr = LLVMGetParam(fn_val, 1);
    2095                 :            : 
    2096                 :          8 :     LLVMValueRef null_dest_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, dest_stack_trace_ptr,
    2097                 :          8 :             LLVMConstNull(LLVMTypeOf(dest_stack_trace_ptr)), "");
    2098                 :          8 :     LLVMValueRef null_src_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, src_stack_trace_ptr,
    2099                 :          8 :             LLVMConstNull(LLVMTypeOf(src_stack_trace_ptr)), "");
    2100                 :          8 :     LLVMValueRef null_bit = LLVMBuildOr(g->builder, null_dest_bit, null_src_bit, "");
    2101                 :          8 :     LLVMBuildCondBr(g->builder, null_bit, return_block, non_null_block);
    2102                 :            : 
    2103                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, non_null_block);
    2104                 :          8 :     size_t src_index_field_index = g->stack_trace_type->data.structure.fields[0].gen_index;
    2105                 :          8 :     size_t src_addresses_field_index = g->stack_trace_type->data.structure.fields[1].gen_index;
    2106                 :          8 :     LLVMValueRef src_index_field_ptr = LLVMBuildStructGEP(g->builder, src_stack_trace_ptr,
    2107                 :          8 :             (unsigned)src_index_field_index, "");
    2108                 :          8 :     LLVMValueRef src_addresses_field_ptr = LLVMBuildStructGEP(g->builder, src_stack_trace_ptr,
    2109                 :          8 :             (unsigned)src_addresses_field_index, "");
    2110                 :          8 :     ZigType *slice_type = g->stack_trace_type->data.structure.fields[1].type_entry;
    2111                 :          8 :     size_t ptr_field_index = slice_type->data.structure.fields[slice_ptr_index].gen_index;
    2112                 :          8 :     LLVMValueRef src_ptr_field_ptr = LLVMBuildStructGEP(g->builder, src_addresses_field_ptr, (unsigned)ptr_field_index, "");
    2113                 :          8 :     size_t len_field_index = slice_type->data.structure.fields[slice_len_index].gen_index;
    2114                 :          8 :     LLVMValueRef src_len_field_ptr = LLVMBuildStructGEP(g->builder, src_addresses_field_ptr, (unsigned)len_field_index, "");
    2115                 :          8 :     LLVMValueRef src_index_val = LLVMBuildLoad(g->builder, src_index_field_ptr, "");
    2116                 :          8 :     LLVMValueRef src_ptr_val = LLVMBuildLoad(g->builder, src_ptr_field_ptr, "");
    2117                 :          8 :     LLVMValueRef src_len_val = LLVMBuildLoad(g->builder, src_len_field_ptr, "");
    2118                 :          8 :     LLVMValueRef no_wrap_bit = LLVMBuildICmp(g->builder, LLVMIntULT, src_index_val, src_len_val, "");
    2119                 :          8 :     LLVMBasicBlockRef no_wrap_block = LLVMAppendBasicBlock(fn_val, "NoWrap");
    2120                 :          8 :     LLVMBasicBlockRef yes_wrap_block = LLVMAppendBasicBlock(fn_val, "YesWrap");
    2121                 :          8 :     LLVMBasicBlockRef loop_block = LLVMAppendBasicBlock(fn_val, "Loop");
    2122                 :          8 :     LLVMBuildCondBr(g->builder, no_wrap_bit, no_wrap_block, yes_wrap_block);
    2123                 :            : 
    2124                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, no_wrap_block);
    2125                 :          8 :     LLVMValueRef usize_zero = LLVMConstNull(g->builtin_types.entry_usize->llvm_type);
    2126                 :          8 :     LLVMBuildStore(g->builder, usize_zero, frame_index_ptr);
    2127                 :          8 :     LLVMBuildStore(g->builder, src_index_val, frames_left_ptr);
    2128                 :          8 :     LLVMValueRef frames_left_eq_zero_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, src_index_val, usize_zero, "");
    2129                 :          8 :     LLVMBuildCondBr(g->builder, frames_left_eq_zero_bit, return_block, loop_block);
    2130                 :            : 
    2131                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, yes_wrap_block);
    2132                 :          8 :     LLVMValueRef usize_one = LLVMConstInt(g->builtin_types.entry_usize->llvm_type, 1, false);
    2133                 :          8 :     LLVMValueRef plus_one = LLVMBuildNUWAdd(g->builder, src_index_val, usize_one, "");
    2134                 :          8 :     LLVMValueRef mod_len = LLVMBuildURem(g->builder, plus_one, src_len_val, "");
    2135                 :          8 :     LLVMBuildStore(g->builder, mod_len, frame_index_ptr);
    2136                 :          8 :     LLVMBuildStore(g->builder, src_len_val, frames_left_ptr);
    2137                 :          8 :     LLVMBuildBr(g->builder, loop_block);
    2138                 :            : 
    2139                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, loop_block);
    2140                 :          8 :     LLVMValueRef ptr_index = LLVMBuildLoad(g->builder, frame_index_ptr, "");
    2141                 :          8 :     LLVMValueRef addr_ptr = LLVMBuildInBoundsGEP(g->builder, src_ptr_val, &ptr_index, 1, "");
    2142                 :          8 :     LLVMValueRef this_addr_val = LLVMBuildLoad(g->builder, addr_ptr, "");
    2143                 :          8 :     LLVMValueRef args[] = {dest_stack_trace_ptr, this_addr_val};
    2144                 :          8 :     ZigLLVMBuildCall(g->builder, add_error_return_trace_addr_fn_val, args, 2, get_llvm_cc(g, CallingConventionUnspecified), ZigLLVM_FnInlineAlways, "");
    2145                 :          8 :     LLVMValueRef prev_frames_left = LLVMBuildLoad(g->builder, frames_left_ptr, "");
    2146                 :          8 :     LLVMValueRef new_frames_left = LLVMBuildNUWSub(g->builder, prev_frames_left, usize_one, "");
    2147                 :          8 :     LLVMValueRef done_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, new_frames_left, usize_zero, "");
    2148                 :          8 :     LLVMBasicBlockRef continue_block = LLVMAppendBasicBlock(fn_val, "Continue");
    2149                 :          8 :     LLVMBuildCondBr(g->builder, done_bit, return_block, continue_block);
    2150                 :            : 
    2151                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, return_block);
    2152                 :          8 :     LLVMBuildRetVoid(g->builder);
    2153                 :            : 
    2154                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, continue_block);
    2155                 :          8 :     LLVMBuildStore(g->builder, new_frames_left, frames_left_ptr);
    2156                 :          8 :     LLVMValueRef prev_index = LLVMBuildLoad(g->builder, frame_index_ptr, "");
    2157                 :          8 :     LLVMValueRef index_plus_one = LLVMBuildNUWAdd(g->builder, prev_index, usize_one, "");
    2158                 :          8 :     LLVMValueRef index_mod_len = LLVMBuildURem(g->builder, index_plus_one, src_len_val, "");
    2159                 :          8 :     LLVMBuildStore(g->builder, index_mod_len, frame_index_ptr);
    2160                 :          8 :     LLVMBuildBr(g->builder, loop_block);
    2161                 :            : 
    2162                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, prev_block);
    2163         [ +  - ]:          8 :     if (!g->strip_debug_symbols) {
    2164                 :          8 :         LLVMSetCurrentDebugLocation(g->builder, prev_debug_location);
    2165                 :            :     }
    2166                 :            : 
    2167                 :          8 :     g->merge_err_ret_traces_fn_val = fn_val;
    2168                 :       1600 :     return fn_val;
    2169                 :            : 
    2170                 :            : }
    2171                 :       9986 : static LLVMValueRef ir_render_save_err_ret_addr(CodeGen *g, IrExecutable *executable,
    2172                 :            :         IrInstructionSaveErrRetAddr *save_err_ret_addr_instruction)
    2173                 :            : {
    2174                 :       9986 :     assert(g->have_err_ret_tracing);
    2175                 :            : 
    2176                 :       9986 :     LLVMValueRef return_err_fn = get_return_err_fn(g);
    2177                 :       9986 :     LLVMValueRef my_err_trace_val = get_cur_err_ret_trace_val(g, save_err_ret_addr_instruction->base.scope);
    2178                 :       9986 :     ZigLLVMBuildCall(g->builder, return_err_fn, &my_err_trace_val, 1,
    2179                 :       9986 :             get_llvm_cc(g, CallingConventionUnspecified), ZigLLVM_FnInlineAuto, "");
    2180                 :            : 
    2181                 :       9986 :     ZigType *ret_type = g->cur_fn->type_entry->data.fn.fn_type_id.return_type;
    2182 [ +  - ][ +  + ]:       9986 :     if (fn_is_async(g->cur_fn) && codegen_fn_has_err_ret_tracing_arg(g, ret_type)) {
                 [ +  + ]
    2183                 :        504 :         LLVMValueRef trace_ptr_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr,
    2184                 :        504 :                 frame_index_trace_arg(g, ret_type), "");
    2185                 :        504 :         LLVMBuildStore(g->builder, my_err_trace_val, trace_ptr_ptr);
    2186                 :            :     }
    2187                 :            : 
    2188                 :       9986 :     return nullptr;
    2189                 :            : }
    2190                 :            : 
    2191                 :        752 : static void gen_assert_resume_id(CodeGen *g, IrInstruction *source_instr, ResumeId resume_id, PanicMsgId msg_id,
    2192                 :            :         LLVMBasicBlockRef end_bb)
    2193                 :            : {
    2194                 :        752 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    2195                 :        752 :     LLVMBasicBlockRef bad_resume_block = LLVMAppendBasicBlock(g->cur_fn_val, "BadResume");
    2196         [ +  - ]:        752 :     if (end_bb == nullptr) end_bb = LLVMAppendBasicBlock(g->cur_fn_val, "OkResume");
    2197                 :        752 :     LLVMValueRef expected_value = LLVMConstSub(LLVMConstAllOnes(usize_type_ref),
    2198                 :        752 :             LLVMConstInt(usize_type_ref, resume_id, false));
    2199                 :        752 :     LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, LLVMGetParam(g->cur_fn_val, 1), expected_value, "");
    2200                 :        752 :     LLVMBuildCondBr(g->builder, ok_bit, end_bb, bad_resume_block);
    2201                 :            : 
    2202                 :        752 :     LLVMPositionBuilderAtEnd(g->builder, bad_resume_block);
    2203                 :        752 :     gen_assertion(g, msg_id, source_instr);
    2204                 :            : 
    2205                 :        752 :     LLVMPositionBuilderAtEnd(g->builder, end_bb);
    2206                 :        752 : }
    2207                 :            : 
    2208                 :       2496 : static LLVMValueRef gen_resume(CodeGen *g, LLVMValueRef fn_val, LLVMValueRef target_frame_ptr, ResumeId resume_id) {
    2209                 :       2496 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    2210         [ +  + ]:       2496 :     if (fn_val == nullptr) {
    2211                 :       1640 :         LLVMValueRef fn_ptr_ptr = LLVMBuildStructGEP(g->builder, target_frame_ptr, frame_fn_ptr_index, "");
    2212                 :       1640 :         fn_val = LLVMBuildLoad(g->builder, fn_ptr_ptr, "");
    2213                 :            :     }
    2214                 :       2496 :     LLVMValueRef arg_val = LLVMConstSub(LLVMConstAllOnes(usize_type_ref),
    2215                 :       2496 :             LLVMConstInt(usize_type_ref, resume_id, false));
    2216                 :       2496 :     LLVMValueRef args[] = {target_frame_ptr, arg_val};
    2217                 :       2496 :     return ZigLLVMBuildCall(g->builder, fn_val, args, 2, LLVMFastCallConv, ZigLLVM_FnInlineAuto, "");
    2218                 :            : }
    2219                 :            : 
    2220                 :       1192 : static LLVMBasicBlockRef gen_suspend_begin(CodeGen *g, const char *name_hint) {
    2221                 :       1192 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    2222                 :       1192 :     LLVMBasicBlockRef resume_bb = LLVMAppendBasicBlock(g->cur_fn_val, name_hint);
    2223                 :       1192 :     size_t new_block_index = g->cur_resume_block_count;
    2224                 :       1192 :     g->cur_resume_block_count += 1;
    2225                 :       1192 :     LLVMValueRef new_block_index_val = LLVMConstInt(usize_type_ref, new_block_index, false);
    2226                 :       1192 :     LLVMAddCase(g->cur_async_switch_instr, new_block_index_val, resume_bb);
    2227                 :       1192 :     LLVMBuildStore(g->builder, new_block_index_val, g->cur_async_resume_index_ptr);
    2228                 :       1192 :     return resume_bb;
    2229                 :            : }
    2230                 :            : 
    2231                 :       1408 : static void set_tail_call_if_appropriate(CodeGen *g, LLVMValueRef call_inst) {
    2232                 :       1408 :     LLVMSetTailCall(call_inst, true);
    2233                 :       1408 : }
    2234                 :            : 
    2235                 :       1760 : static LLVMValueRef gen_maybe_atomic_op(CodeGen *g, LLVMAtomicRMWBinOp op, LLVMValueRef ptr, LLVMValueRef val,
    2236                 :            :         LLVMAtomicOrdering order)
    2237                 :            : {
    2238         [ +  + ]:       1760 :     if (g->is_single_threaded) {
    2239                 :        880 :         LLVMValueRef loaded = LLVMBuildLoad(g->builder, ptr, "");
    2240                 :            :         LLVMValueRef modified;
    2241      [ +  +  - ]:        880 :         switch (op) {
    2242                 :        276 :             case LLVMAtomicRMWBinOpXchg:
    2243                 :        276 :                 modified = val;
    2244                 :        276 :                 break;
    2245                 :        604 :             case LLVMAtomicRMWBinOpXor:
    2246                 :        604 :                 modified = LLVMBuildXor(g->builder, loaded, val, "");
    2247                 :        604 :                 break;
    2248                 :          0 :             default:
    2249                 :          0 :                 zig_unreachable();
    2250                 :            :         }
    2251                 :        880 :         LLVMBuildStore(g->builder, modified, ptr);
    2252                 :        880 :         return loaded;
    2253                 :            :     } else {
    2254                 :        880 :         return LLVMBuildAtomicRMW(g->builder, op, ptr, val, order, false);
    2255                 :            :     }
    2256                 :            : }
    2257                 :            : 
    2258                 :       1208 : static void gen_async_return(CodeGen *g, IrInstructionReturn *instruction) {
    2259                 :       1208 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    2260                 :            : 
    2261         [ +  + ]:       1208 :     ZigType *operand_type = (instruction->operand != nullptr) ? instruction->operand->value.type : nullptr;
    2262 [ +  + ][ +  + ]:       1208 :     bool operand_has_bits = (operand_type != nullptr) && type_has_bits(operand_type);
    2263                 :       1208 :     ZigType *ret_type = g->cur_fn->type_entry->data.fn.fn_type_id.return_type;
    2264                 :       1208 :     bool ret_type_has_bits = type_has_bits(ret_type);
    2265                 :            : 
    2266 [ +  - ][ +  + ]:       1208 :     if (operand_has_bits && instruction->operand != nullptr) {
    2267 [ +  + ][ +  - ]:        520 :         bool need_store = instruction->operand->value.special != ConstValSpecialRuntime || !handle_is_ptr(ret_type);
    2268         [ +  - ]:        520 :         if (need_store) {
    2269                 :            :             // It didn't get written to the result ptr. We do that now.
    2270                 :        520 :             ZigType *ret_ptr_type = get_pointer_to_type(g, ret_type, true);
    2271                 :        520 :             gen_assign_raw(g, g->cur_ret_ptr, ret_ptr_type, ir_llvm_value(g, instruction->operand));
    2272                 :            :         }
    2273                 :            :     }
    2274                 :            : 
    2275                 :            :     // Whether we tail resume the awaiter, or do an early return, we are done and will not be resumed.
    2276         [ +  - ]:       1208 :     if (ir_want_runtime_safety(g, &instruction->base)) {
    2277                 :       1208 :         LLVMValueRef new_resume_index = LLVMConstAllOnes(usize_type_ref);
    2278                 :       1208 :         LLVMBuildStore(g->builder, new_resume_index, g->cur_async_resume_index_ptr);
    2279                 :            :     }
    2280                 :            : 
    2281                 :       1208 :     LLVMValueRef zero = LLVMConstNull(usize_type_ref);
    2282                 :       1208 :     LLVMValueRef all_ones = LLVMConstAllOnes(usize_type_ref);
    2283                 :            : 
    2284                 :       1208 :     LLVMValueRef prev_val = gen_maybe_atomic_op(g, LLVMAtomicRMWBinOpXor, g->cur_async_awaiter_ptr,
    2285                 :       1208 :             all_ones, LLVMAtomicOrderingAcquire);
    2286                 :            : 
    2287                 :       1208 :     LLVMBasicBlockRef bad_return_block = LLVMAppendBasicBlock(g->cur_fn_val, "BadReturn");
    2288                 :       1208 :     LLVMBasicBlockRef early_return_block = LLVMAppendBasicBlock(g->cur_fn_val, "EarlyReturn");
    2289                 :       1208 :     LLVMBasicBlockRef resume_them_block = LLVMAppendBasicBlock(g->cur_fn_val, "ResumeThem");
    2290                 :            : 
    2291                 :       1208 :     LLVMValueRef switch_instr = LLVMBuildSwitch(g->builder, prev_val, resume_them_block, 2);
    2292                 :            : 
    2293                 :       1208 :     LLVMAddCase(switch_instr, zero, early_return_block);
    2294                 :       1208 :     LLVMAddCase(switch_instr, all_ones, bad_return_block);
    2295                 :            : 
    2296                 :            :     // Something has gone horribly wrong, and this is an invalid second return.
    2297                 :       1208 :     LLVMPositionBuilderAtEnd(g->builder, bad_return_block);
    2298                 :       1208 :     gen_assertion(g, PanicMsgIdBadReturn, &instruction->base);
    2299                 :            : 
    2300                 :            :     // There is no awaiter yet, but we're completely done.
    2301                 :       1208 :     LLVMPositionBuilderAtEnd(g->builder, early_return_block);
    2302                 :       1208 :     LLVMBuildRetVoid(g->builder);
    2303                 :            : 
    2304                 :            :     // We need to resume the caller by tail calling them,
    2305                 :            :     // but first write through the result pointer and possibly
    2306                 :            :     // error return trace pointer.
    2307                 :       1208 :     LLVMPositionBuilderAtEnd(g->builder, resume_them_block);
    2308                 :            : 
    2309         [ +  + ]:       1208 :     if (ret_type_has_bits) {
    2310                 :            :         // If the awaiter result pointer is non-null, we need to copy the result to there.
    2311                 :        824 :         LLVMBasicBlockRef copy_block = LLVMAppendBasicBlock(g->cur_fn_val, "CopyResult");
    2312                 :        824 :         LLVMBasicBlockRef copy_end_block = LLVMAppendBasicBlock(g->cur_fn_val, "CopyResultEnd");
    2313                 :        824 :         LLVMValueRef awaiter_ret_ptr_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr, frame_ret_start + 1, "");
    2314                 :        824 :         LLVMValueRef awaiter_ret_ptr = LLVMBuildLoad(g->builder, awaiter_ret_ptr_ptr, "");
    2315                 :        824 :         LLVMValueRef zero_ptr = LLVMConstNull(LLVMTypeOf(awaiter_ret_ptr));
    2316                 :        824 :         LLVMValueRef need_copy_bit = LLVMBuildICmp(g->builder, LLVMIntNE, awaiter_ret_ptr, zero_ptr, "");
    2317                 :        824 :         LLVMBuildCondBr(g->builder, need_copy_bit, copy_block, copy_end_block);
    2318                 :            : 
    2319                 :        824 :         LLVMPositionBuilderAtEnd(g->builder, copy_block);
    2320                 :        824 :         LLVMTypeRef ptr_u8 = LLVMPointerType(LLVMInt8Type(), 0);
    2321                 :        824 :         LLVMValueRef dest_ptr_casted = LLVMBuildBitCast(g->builder, awaiter_ret_ptr, ptr_u8, "");
    2322                 :        824 :         LLVMValueRef src_ptr_casted = LLVMBuildBitCast(g->builder, g->cur_ret_ptr, ptr_u8, "");
    2323                 :        824 :         bool is_volatile = false;
    2324                 :        824 :         uint32_t abi_align = get_abi_alignment(g, ret_type);
    2325                 :        824 :         LLVMValueRef byte_count_val = LLVMConstInt(usize_type_ref, type_size(g, ret_type), false);
    2326                 :        824 :         ZigLLVMBuildMemCpy(g->builder,
    2327                 :            :                 dest_ptr_casted, abi_align,
    2328                 :            :                 src_ptr_casted, abi_align, byte_count_val, is_volatile);
    2329                 :        824 :         LLVMBuildBr(g->builder, copy_end_block);
    2330                 :            : 
    2331                 :        824 :         LLVMPositionBuilderAtEnd(g->builder, copy_end_block);
    2332         [ +  + ]:        824 :         if (codegen_fn_has_err_ret_tracing_arg(g, ret_type)) {
    2333                 :        696 :             LLVMValueRef awaiter_trace_ptr_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr,
    2334                 :        696 :                     frame_index_trace_arg(g, ret_type) + 1, "");
    2335                 :        696 :             LLVMValueRef dest_trace_ptr = LLVMBuildLoad(g->builder, awaiter_trace_ptr_ptr, "");
    2336                 :        696 :             LLVMValueRef my_err_trace_val = get_cur_err_ret_trace_val(g, instruction->base.scope);
    2337                 :        696 :             LLVMValueRef args[] = { dest_trace_ptr, my_err_trace_val };
    2338                 :        824 :             ZigLLVMBuildCall(g->builder, get_merge_err_ret_traces_fn_val(g), args, 2,
    2339                 :        696 :                     get_llvm_cc(g, CallingConventionUnspecified), ZigLLVM_FnInlineAuto, "");
    2340                 :            :         }
    2341                 :            :     }
    2342                 :            : 
    2343                 :            :     // Resume the caller by tail calling them.
    2344                 :       1208 :     ZigType *any_frame_type = get_any_frame_type(g, ret_type);
    2345                 :       1208 :     LLVMValueRef their_frame_ptr = LLVMBuildIntToPtr(g->builder, prev_val, get_llvm_type(g, any_frame_type), "");
    2346                 :       1208 :     LLVMValueRef call_inst = gen_resume(g, nullptr, their_frame_ptr, ResumeIdReturn);
    2347                 :       1208 :     set_tail_call_if_appropriate(g, call_inst);
    2348                 :       1208 :     LLVMBuildRetVoid(g->builder);
    2349                 :       1208 : }
    2350                 :            : 
    2351                 :      34141 : static LLVMValueRef ir_render_return(CodeGen *g, IrExecutable *executable, IrInstructionReturn *instruction) {
    2352         [ +  + ]:      34141 :     if (fn_is_async(g->cur_fn)) {
    2353                 :       1208 :         gen_async_return(g, instruction);
    2354                 :       1208 :         return nullptr;
    2355                 :            :     }
    2356                 :            : 
    2357         [ +  + ]:      32933 :     if (want_first_arg_sret(g, &g->cur_fn->type_entry->data.fn.fn_type_id)) {
    2358         [ +  + ]:       6752 :         if (instruction->operand == nullptr) {
    2359                 :       4969 :             LLVMBuildRetVoid(g->builder);
    2360                 :       4969 :             return nullptr;
    2361                 :            :         }
    2362                 :       1783 :         assert(g->cur_ret_ptr);
    2363                 :       1783 :         src_assert(instruction->operand->value.special != ConstValSpecialRuntime,
    2364                 :            :                 instruction->base.source_node);
    2365                 :       1783 :         LLVMValueRef value = ir_llvm_value(g, instruction->operand);
    2366                 :       1783 :         ZigType *return_type = instruction->operand->value.type;
    2367                 :       1783 :         gen_assign_raw(g, g->cur_ret_ptr, get_pointer_to_type(g, return_type, false), value);
    2368                 :       1783 :         LLVMBuildRetVoid(g->builder);
    2369   [ +  -  +  + ]:      52362 :     } else if (g->cur_fn->type_entry->data.fn.fn_type_id.cc != CallingConventionAsync &&
                 [ +  + ]
    2370                 :      26181 :             handle_is_ptr(g->cur_fn->type_entry->data.fn.fn_type_id.return_type))
    2371                 :            :     {
    2372         [ +  - ]:          8 :         if (instruction->operand == nullptr) {
    2373                 :          8 :             LLVMValueRef by_val_value = gen_load_untyped(g, g->cur_ret_ptr, 0, false, "");
    2374                 :          8 :             LLVMBuildRet(g->builder, by_val_value);
    2375                 :            :         } else {
    2376                 :          0 :             LLVMValueRef value = ir_llvm_value(g, instruction->operand);
    2377                 :          0 :             LLVMValueRef by_val_value = gen_load_untyped(g, value, 0, false, "");
    2378                 :          8 :             LLVMBuildRet(g->builder, by_val_value);
    2379                 :            :         }
    2380         [ -  + ]:      26173 :     } else if (instruction->operand == nullptr) {
    2381                 :          0 :         LLVMBuildRetVoid(g->builder);
    2382                 :            :     } else {
    2383                 :      26173 :         LLVMValueRef value = ir_llvm_value(g, instruction->operand);
    2384                 :      26173 :         LLVMBuildRet(g->builder, value);
    2385                 :            :     }
    2386                 :      27964 :     return nullptr;
    2387                 :            : }
    2388                 :            : 
    2389                 :          8 : static LLVMValueRef gen_overflow_shl_op(CodeGen *g, ZigType *type_entry,
    2390                 :            :         LLVMValueRef val1, LLVMValueRef val2)
    2391                 :            : {
    2392                 :            :     // for unsigned left shifting, we do the lossy shift, then logically shift
    2393                 :            :     // right the same number of bits
    2394                 :            :     // if the values don't match, we have an overflow
    2395                 :            :     // for signed left shifting we do the same except arithmetic shift right
    2396                 :            : 
    2397                 :          8 :     assert(type_entry->id == ZigTypeIdInt);
    2398                 :            : 
    2399                 :          8 :     LLVMValueRef result = LLVMBuildShl(g->builder, val1, val2, "");
    2400                 :            :     LLVMValueRef orig_val;
    2401         [ -  + ]:          8 :     if (type_entry->data.integral.is_signed) {
    2402                 :          0 :         orig_val = LLVMBuildAShr(g->builder, result, val2, "");
    2403                 :            :     } else {
    2404                 :          8 :         orig_val = LLVMBuildLShr(g->builder, result, val2, "");
    2405                 :            :     }
    2406                 :          8 :     LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, val1, orig_val, "");
    2407                 :            : 
    2408                 :          8 :     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "OverflowOk");
    2409                 :          8 :     LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "OverflowFail");
    2410                 :          8 :     LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    2411                 :            : 
    2412                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, fail_block);
    2413                 :          8 :     gen_safety_crash(g, PanicMsgIdShlOverflowedBits);
    2414                 :            : 
    2415                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    2416                 :          8 :     return result;
    2417                 :            : }
    2418                 :            : 
    2419                 :          8 : static LLVMValueRef gen_overflow_shr_op(CodeGen *g, ZigType *type_entry,
    2420                 :            :         LLVMValueRef val1, LLVMValueRef val2)
    2421                 :            : {
    2422                 :          8 :     assert(type_entry->id == ZigTypeIdInt);
    2423                 :            : 
    2424                 :            :     LLVMValueRef result;
    2425         [ -  + ]:          8 :     if (type_entry->data.integral.is_signed) {
    2426                 :          0 :         result = LLVMBuildAShr(g->builder, val1, val2, "");
    2427                 :            :     } else {
    2428                 :          8 :         result = LLVMBuildLShr(g->builder, val1, val2, "");
    2429                 :            :     }
    2430                 :          8 :     LLVMValueRef orig_val = LLVMBuildShl(g->builder, result, val2, "");
    2431                 :          8 :     LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, val1, orig_val, "");
    2432                 :            : 
    2433                 :          8 :     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "OverflowOk");
    2434                 :          8 :     LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "OverflowFail");
    2435                 :          8 :     LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    2436                 :            : 
    2437                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, fail_block);
    2438                 :          8 :     gen_safety_crash(g, PanicMsgIdShrOverflowedBits);
    2439                 :            : 
    2440                 :          8 :     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    2441                 :          8 :     return result;
    2442                 :            : }
    2443                 :            : 
    2444                 :         80 : static LLVMValueRef gen_float_op(CodeGen *g, LLVMValueRef val, ZigType *type_entry, BuiltinFnId op) {
    2445 [ +  + ][ +  - ]:         80 :     if ((op == BuiltinFnIdCeil ||
    2446         [ -  + ]:         80 :          op == BuiltinFnIdFloor) &&
    2447                 :         80 :         type_entry->id == ZigTypeIdInt)
    2448                 :          0 :         return val;
    2449                 :         80 :     assert(type_entry->id == ZigTypeIdFloat);
    2450                 :            : 
    2451                 :         80 :     LLVMValueRef floor_fn = get_float_fn(g, type_entry, ZigLLVMFnIdFloatOp, op);
    2452                 :         80 :     return LLVMBuildCall(g->builder, floor_fn, &val, 1, "");
    2453                 :            : }
    2454                 :            : 
    2455                 :            : enum DivKind {
    2456                 :            :     DivKindFloat,
    2457                 :            :     DivKindTrunc,
    2458                 :            :     DivKindFloor,
    2459                 :            :     DivKindExact,
    2460                 :            : };
    2461                 :            : 
    2462                 :     842331 : static LLVMValueRef bigint_to_llvm_const(LLVMTypeRef type_ref, BigInt *bigint) {
    2463         [ +  + ]:     842331 :     if (bigint->digit_count == 0) {
    2464                 :      13500 :         return LLVMConstNull(type_ref);
    2465                 :            :     }
    2466                 :            :     LLVMValueRef unsigned_val;
    2467         [ +  + ]:     828831 :     if (bigint->digit_count == 1) {
    2468                 :     828223 :         unsigned_val = LLVMConstInt(type_ref, bigint_ptr(bigint)[0], false);
    2469                 :            :     } else {
    2470                 :        608 :         unsigned_val = LLVMConstIntOfArbitraryPrecision(type_ref, bigint->digit_count, bigint_ptr(bigint));
    2471                 :            :     }
    2472         [ +  + ]:     828831 :     if (bigint->is_negative) {
    2473                 :       2678 :         return LLVMConstNeg(unsigned_val);
    2474                 :            :     } else {
    2475                 :     826153 :         return unsigned_val;
    2476                 :            :     }
    2477                 :            : }
    2478                 :            : 
    2479                 :        779 : static LLVMValueRef gen_div(CodeGen *g, bool want_runtime_safety, bool want_fast_math,
    2480                 :            :         LLVMValueRef val1, LLVMValueRef val2,
    2481                 :            :         ZigType *type_entry, DivKind div_kind)
    2482                 :            : {
    2483                 :        779 :     ZigLLVMSetFastMath(g->builder, want_fast_math);
    2484                 :            : 
    2485                 :        779 :     LLVMValueRef zero = LLVMConstNull(get_llvm_type(g, type_entry));
    2486 [ +  - ][ +  + ]:        779 :     if (want_runtime_safety && (want_fast_math || type_entry->id != ZigTypeIdFloat)) {
                 [ +  + ]
    2487                 :            :         LLVMValueRef is_zero_bit;
    2488         [ +  - ]:        507 :         if (type_entry->id == ZigTypeIdInt) {
    2489                 :        507 :             is_zero_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, val2, zero, "");
    2490         [ #  # ]:          0 :         } else if (type_entry->id == ZigTypeIdFloat) {
    2491                 :          0 :             is_zero_bit = LLVMBuildFCmp(g->builder, LLVMRealOEQ, val2, zero, "");
    2492                 :            :         } else {
    2493                 :          0 :             zig_unreachable();
    2494                 :            :         }
    2495                 :        507 :         LLVMBasicBlockRef div_zero_fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivZeroFail");
    2496                 :        507 :         LLVMBasicBlockRef div_zero_ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivZeroOk");
    2497                 :        507 :         LLVMBuildCondBr(g->builder, is_zero_bit, div_zero_fail_block, div_zero_ok_block);
    2498                 :            : 
    2499                 :        507 :         LLVMPositionBuilderAtEnd(g->builder, div_zero_fail_block);
    2500                 :        507 :         gen_safety_crash(g, PanicMsgIdDivisionByZero);
    2501                 :            : 
    2502                 :        507 :         LLVMPositionBuilderAtEnd(g->builder, div_zero_ok_block);
    2503                 :            : 
    2504 [ +  + ][ +  - ]:        507 :         if (type_entry->id == ZigTypeIdInt && type_entry->data.integral.is_signed) {
    2505                 :         26 :             LLVMValueRef neg_1_value = LLVMConstInt(get_llvm_type(g, type_entry), -1, true);
    2506                 :         26 :             BigInt int_min_bi = {0};
    2507                 :         26 :             eval_min_max_value_int(g, type_entry, &int_min_bi, false);
    2508                 :         26 :             LLVMValueRef int_min_value = bigint_to_llvm_const(get_llvm_type(g, type_entry), &int_min_bi);
    2509                 :         26 :             LLVMBasicBlockRef overflow_fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivOverflowFail");
    2510                 :         26 :             LLVMBasicBlockRef overflow_ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivOverflowOk");
    2511                 :         26 :             LLVMValueRef num_is_int_min = LLVMBuildICmp(g->builder, LLVMIntEQ, val1, int_min_value, "");
    2512                 :         26 :             LLVMValueRef den_is_neg_1 = LLVMBuildICmp(g->builder, LLVMIntEQ, val2, neg_1_value, "");
    2513                 :         26 :             LLVMValueRef overflow_fail_bit = LLVMBuildAnd(g->builder, num_is_int_min, den_is_neg_1, "");
    2514                 :         26 :             LLVMBuildCondBr(g->builder, overflow_fail_bit, overflow_fail_block, overflow_ok_block);
    2515                 :            : 
    2516                 :         26 :             LLVMPositionBuilderAtEnd(g->builder, overflow_fail_block);
    2517                 :         26 :             gen_safety_crash(g, PanicMsgIdIntegerOverflow);
    2518                 :            : 
    2519                 :         26 :             LLVMPositionBuilderAtEnd(g->builder, overflow_ok_block);
    2520                 :            :         }
    2521                 :            :     }
    2522                 :            : 
    2523         [ +  + ]:        779 :     if (type_entry->id == ZigTypeIdFloat) {
    2524                 :        228 :         LLVMValueRef result = LLVMBuildFDiv(g->builder, val1, val2, "");
    2525   [ +  +  +  +  :        228 :         switch (div_kind) {
                      - ]
    2526                 :        172 :             case DivKindFloat:
    2527                 :        172 :                 return result;
    2528                 :         16 :             case DivKindExact:
    2529         [ +  - ]:         16 :                 if (want_runtime_safety) {
    2530                 :         16 :                     LLVMValueRef floored = gen_float_op(g, result, type_entry, BuiltinFnIdFloor);
    2531                 :         16 :                     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivExactOk");
    2532                 :         16 :                     LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivExactFail");
    2533                 :         16 :                     LLVMValueRef ok_bit = LLVMBuildFCmp(g->builder, LLVMRealOEQ, floored, result, "");
    2534                 :            : 
    2535                 :         16 :                     LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    2536                 :            : 
    2537                 :         16 :                     LLVMPositionBuilderAtEnd(g->builder, fail_block);
    2538                 :         16 :                     gen_safety_crash(g, PanicMsgIdExactDivisionRemainder);
    2539                 :            : 
    2540                 :         16 :                     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    2541                 :            :                 }
    2542                 :         16 :                 return result;
    2543                 :         24 :             case DivKindTrunc:
    2544                 :            :                 {
    2545                 :         24 :                     LLVMBasicBlockRef ltz_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivTruncLTZero");
    2546                 :         24 :                     LLVMBasicBlockRef gez_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivTruncGEZero");
    2547                 :         24 :                     LLVMBasicBlockRef end_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivTruncEnd");
    2548                 :         24 :                     LLVMValueRef ltz = LLVMBuildFCmp(g->builder, LLVMRealOLT, val1, zero, "");
    2549                 :         24 :                     LLVMBuildCondBr(g->builder, ltz, ltz_block, gez_block);
    2550                 :            : 
    2551                 :         24 :                     LLVMPositionBuilderAtEnd(g->builder, ltz_block);
    2552                 :         24 :                     LLVMValueRef ceiled = gen_float_op(g, result, type_entry, BuiltinFnIdCeil);
    2553                 :         24 :                     LLVMBasicBlockRef ceiled_end_block = LLVMGetInsertBlock(g->builder);
    2554                 :         24 :                     LLVMBuildBr(g->builder, end_block);
    2555                 :            : 
    2556                 :         24 :                     LLVMPositionBuilderAtEnd(g->builder, gez_block);
    2557                 :         24 :                     LLVMValueRef floored = gen_float_op(g, result, type_entry, BuiltinFnIdFloor);
    2558                 :         24 :                     LLVMBasicBlockRef floored_end_block = LLVMGetInsertBlock(g->builder);
    2559                 :         24 :                     LLVMBuildBr(g->builder, end_block);
    2560                 :            : 
    2561                 :         24 :                     LLVMPositionBuilderAtEnd(g->builder, end_block);
    2562                 :         24 :                     LLVMValueRef phi = LLVMBuildPhi(g->builder, get_llvm_type(g, type_entry), "");
    2563                 :         24 :                     LLVMValueRef incoming_values[] = { ceiled, floored };
    2564                 :         24 :                     LLVMBasicBlockRef incoming_blocks[] = { ceiled_end_block, floored_end_block };
    2565                 :         24 :                     LLVMAddIncoming(phi, incoming_values, incoming_blocks, 2);
    2566                 :         24 :                     return phi;
    2567                 :            :                 }
    2568                 :         16 :             case DivKindFloor:
    2569                 :         16 :                 return gen_float_op(g, result, type_entry, BuiltinFnIdFloor);
    2570                 :            :         }
    2571                 :          0 :         zig_unreachable();
    2572                 :            :     }
    2573                 :            : 
    2574                 :        551 :     assert(type_entry->id == ZigTypeIdInt);
    2575                 :            : 
    2576   [ -  +  +  +  :        551 :     switch (div_kind) {
                      - ]
    2577                 :          0 :         case DivKindFloat:
    2578                 :          0 :             zig_unreachable();
    2579                 :        525 :         case DivKindTrunc:
    2580         [ +  + ]:        525 :             if (type_entry->data.integral.is_signed) {
    2581                 :         24 :                 return LLVMBuildSDiv(g->builder, val1, val2, "");
    2582                 :            :             } else {
    2583                 :        501 :                 return LLVMBuildUDiv(g->builder, val1, val2, "");
    2584                 :            :             }
    2585                 :         16 :         case DivKindExact:
    2586         [ +  - ]:         16 :             if (want_runtime_safety) {
    2587                 :            :                 LLVMValueRef remainder_val;
    2588         [ +  + ]:         16 :                 if (type_entry->data.integral.is_signed) {
    2589                 :          8 :                     remainder_val = LLVMBuildSRem(g->builder, val1, val2, "");
    2590                 :            :                 } else {
    2591                 :          8 :                     remainder_val = LLVMBuildURem(g->builder, val1, val2, "");
    2592                 :            :                 }
    2593                 :         16 :                 LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, remainder_val, zero, "");
    2594                 :            : 
    2595                 :         16 :                 LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivExactOk");
    2596                 :         16 :                 LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "DivExactFail");
    2597                 :         16 :                 LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    2598                 :            : 
    2599                 :         16 :                 LLVMPositionBuilderAtEnd(g->builder, fail_block);
    2600                 :         16 :                 gen_safety_crash(g, PanicMsgIdExactDivisionRemainder);
    2601                 :            : 
    2602                 :         16 :                 LLVMPositionBuilderAtEnd(g->builder, ok_block);
    2603                 :            :             }
    2604         [ +  + ]:         16 :             if (type_entry->data.integral.is_signed) {
    2605                 :          8 :                 return LLVMBuildExactSDiv(g->builder, val1, val2, "");
    2606                 :            :             } else {
    2607                 :          8 :                 return LLVMBuildExactUDiv(g->builder, val1, val2, "");
    2608                 :            :             }
    2609                 :         10 :         case DivKindFloor:
    2610                 :            :             {
    2611         [ -  + ]:         10 :                 if (!type_entry->data.integral.is_signed) {
    2612                 :          0 :                     return LLVMBuildUDiv(g->builder, val1, val2, "");
    2613                 :            :                 }
    2614                 :            :                 // const d = @divTrunc(a, b);
    2615                 :            :                 // const r = @rem(a, b);
    2616                 :            :                 // return if (r == 0) d else d - ((a < 0) ^ (b < 0));
    2617                 :            : 
    2618                 :         10 :                 LLVMValueRef div_trunc = LLVMBuildSDiv(g->builder, val1, val2, "");
    2619                 :         10 :                 LLVMValueRef rem = LLVMBuildSRem(g->builder, val1, val2, "");
    2620                 :         10 :                 LLVMValueRef rem_eq_0 = LLVMBuildICmp(g->builder, LLVMIntEQ, rem, zero, "");
    2621                 :         10 :                 LLVMValueRef a_lt_0 = LLVMBuildICmp(g->builder, LLVMIntSLT, val1, zero, "");
    2622                 :         10 :                 LLVMValueRef b_lt_0 = LLVMBuildICmp(g->builder, LLVMIntSLT, val2, zero, "");
    2623                 :         10 :                 LLVMValueRef a_b_xor = LLVMBuildXor(g->builder, a_lt_0, b_lt_0, "");
    2624                 :         10 :                 LLVMValueRef a_b_xor_ext = LLVMBuildZExt(g->builder, a_b_xor, LLVMTypeOf(div_trunc), "");
    2625                 :         10 :                 LLVMValueRef d_sub_xor = LLVMBuildSub(g->builder, div_trunc, a_b_xor_ext, "");
    2626                 :         10 :                 return LLVMBuildSelect(g->builder, rem_eq_0, div_trunc, d_sub_xor, "");
    2627                 :            :             }
    2628                 :            :     }
    2629                 :          0 :     zig_unreachable();
    2630                 :            : }
    2631                 :            : 
    2632                 :            : enum RemKind {
    2633                 :            :     RemKindRem,
    2634                 :            :     RemKindMod,
    2635                 :            : };
    2636                 :            : 
    2637                 :        425 : static LLVMValueRef gen_rem(CodeGen *g, bool want_runtime_safety, bool want_fast_math,
    2638                 :            :         LLVMValueRef val1, LLVMValueRef val2,
    2639                 :            :         ZigType *type_entry, RemKind rem_kind)
    2640                 :            : {
    2641                 :        425 :     ZigLLVMSetFastMath(g->builder, want_fast_math);
    2642                 :            : 
    2643                 :        425 :     LLVMValueRef zero = LLVMConstNull(get_llvm_type(g, type_entry));
    2644         [ +  + ]:        425 :     if (want_runtime_safety) {
    2645                 :            :         LLVMValueRef is_zero_bit;
    2646         [ +  - ]:        401 :         if (type_entry->id == ZigTypeIdInt) {
    2647         [ +  + ]:        401 :             LLVMIntPredicate pred = type_entry->data.integral.is_signed ? LLVMIntSLE : LLVMIntEQ;
    2648                 :        401 :             is_zero_bit = LLVMBuildICmp(g->builder, pred, val2, zero, "");
    2649         [ #  # ]:          0 :         } else if (type_entry->id == ZigTypeIdFloat) {
    2650                 :          0 :             is_zero_bit = LLVMBuildFCmp(g->builder, LLVMRealOEQ, val2, zero, "");
    2651                 :            :         } else {
    2652                 :          0 :             zig_unreachable();
    2653                 :            :         }
    2654                 :        401 :         LLVMBasicBlockRef rem_zero_ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "RemZeroOk");
    2655                 :        401 :         LLVMBasicBlockRef rem_zero_fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "RemZeroFail");
    2656                 :        401 :         LLVMBuildCondBr(g->builder, is_zero_bit, rem_zero_fail_block, rem_zero_ok_block);
    2657                 :            : 
    2658                 :        401 :         LLVMPositionBuilderAtEnd(g->builder, rem_zero_fail_block);
    2659                 :        401 :         gen_safety_crash(g, PanicMsgIdRemainderDivisionByZero);
    2660                 :            : 
    2661                 :        401 :         LLVMPositionBuilderAtEnd(g->builder, rem_zero_ok_block);
    2662                 :            :     }
    2663                 :            : 
    2664         [ -  + ]:        425 :     if (type_entry->id == ZigTypeIdFloat) {
    2665         [ #  # ]:          0 :         if (rem_kind == RemKindRem) {
    2666                 :          0 :             return LLVMBuildFRem(g->builder, val1, val2, "");
    2667                 :            :         } else {
    2668                 :          0 :             LLVMValueRef a = LLVMBuildFRem(g->builder, val1, val2, "");
    2669                 :          0 :             LLVMValueRef b = LLVMBuildFAdd(g->builder, a, val2, "");
    2670                 :          0 :             LLVMValueRef c = LLVMBuildFRem(g->builder, b, val2, "");
    2671                 :          0 :             LLVMValueRef ltz = LLVMBuildFCmp(g->builder, LLVMRealOLT, val1, zero, "");
    2672                 :          0 :             return LLVMBuildSelect(g->builder, ltz, c, a, "");
    2673                 :            :         }
    2674                 :            :     } else {
    2675                 :        425 :         assert(type_entry->id == ZigTypeIdInt);
    2676         [ +  + ]:        425 :         if (type_entry->data.integral.is_signed) {
    2677         [ -  + ]:         10 :             if (rem_kind == RemKindRem) {
    2678                 :          0 :                 return LLVMBuildSRem(g->builder, val1, val2, "");
    2679                 :            :             } else {
    2680                 :         10 :                 LLVMValueRef a = LLVMBuildSRem(g->builder, val1, val2, "");
    2681                 :         10 :                 LLVMValueRef b = LLVMBuildNSWAdd(g->builder, a, val2, "");
    2682                 :         10 :                 LLVMValueRef c = LLVMBuildSRem(g->builder, b, val2, "");
    2683                 :         10 :                 LLVMValueRef ltz = LLVMBuildICmp(g->builder, LLVMIntSLT, val1, zero, "");
    2684                 :         10 :                 return LLVMBuildSelect(g->builder, ltz, c, a, "");
    2685                 :            :             }
    2686                 :            :         } else {
    2687                 :        415 :             return LLVMBuildURem(g->builder, val1, val2, "");
    2688                 :            :         }
    2689                 :            :     }
    2690                 :            : 
    2691                 :            : }
    2692                 :            : 
    2693                 :      34164 : static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutable *executable,
    2694                 :            :         IrInstructionBinOp *bin_op_instruction)
    2695                 :            : {
    2696                 :      34164 :     IrBinOp op_id = bin_op_instruction->op_id;
    2697                 :      34164 :     IrInstruction *op1 = bin_op_instruction->op1;
    2698                 :      34164 :     IrInstruction *op2 = bin_op_instruction->op2;
    2699                 :            : 
    2700 [ +  + ][ +  + ]:      37546 :     assert(op1->value.type == op2->value.type || op_id == IrBinOpBitShiftLeftLossy ||
    2701 [ +  + ][ +  + ]:       1897 :         op_id == IrBinOpBitShiftLeftExact || op_id == IrBinOpBitShiftRightLossy ||
    2702         [ +  + ]:        411 :         op_id == IrBinOpBitShiftRightExact ||
    2703 [ +  + ][ -  + ]:      37811 :         (op1->value.type->id == ZigTypeIdErrorSet && op2->value.type->id == ZigTypeIdErrorSet) ||
                 [ +  - ]
    2704         [ +  + ]:        265 :         (op1->value.type->id == ZigTypeIdPointer &&
    2705 [ +  - ][ +  - ]:        265 :             (op_id == IrBinOpAdd || op_id == IrBinOpSub) &&
    2706                 :        265 :             op1->value.type->data.pointer.ptr_len != PtrLenSingle)
    2707                 :            :     );
    2708                 :      34164 :     ZigType *operand_type = op1->value.type;
    2709         [ +  + ]:      34164 :     ZigType *scalar_type = (operand_type->id == ZigTypeIdVector) ? operand_type->data.vector.elem_type : operand_type;
    2710                 :            : 
    2711   [ +  +  +  + ]:      66829 :     bool want_runtime_safety = bin_op_instruction->safety_check_on &&
    2712                 :      32665 :         ir_want_runtime_safety(g, &bin_op_instruction->base);
    2713                 :            : 
    2714                 :      34164 :     LLVMValueRef op1_value = ir_llvm_value(g, op1);
    2715                 :      34164 :     LLVMValueRef op2_value = ir_llvm_value(g, op2);
    2716                 :            : 
    2717                 :            : 
    2718   [ -  +  +  +  :      34164 :     switch (op_id) {
          +  +  +  +  +  
          +  +  +  +  +  
                +  +  - ]
    2719                 :          0 :         case IrBinOpInvalid:
    2720                 :            :         case IrBinOpArrayCat:
    2721                 :            :         case IrBinOpArrayMult:
    2722                 :            :         case IrBinOpRemUnspecified:
    2723                 :            :         case IrBinOpMergeErrorSets:
    2724                 :          0 :             zig_unreachable();
    2725                 :         24 :         case IrBinOpBoolOr:
    2726                 :         24 :             return LLVMBuildOr(g->builder, op1_value, op2_value, "");
    2727                 :         84 :         case IrBinOpBoolAnd:
    2728                 :         84 :             return LLVMBuildAnd(g->builder, op1_value, op2_value, "");
    2729                 :      15140 :         case IrBinOpCmpEq:
    2730                 :            :         case IrBinOpCmpNotEq:
    2731                 :            :         case IrBinOpCmpLessThan:
    2732                 :            :         case IrBinOpCmpGreaterThan:
    2733                 :            :         case IrBinOpCmpLessOrEq:
    2734                 :            :         case IrBinOpCmpGreaterOrEq:
    2735         [ +  + ]:      15140 :             if (scalar_type->id == ZigTypeIdFloat) {
    2736                 :       1192 :                 ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &bin_op_instruction->base));
    2737                 :       1192 :                 LLVMRealPredicate pred = cmp_op_to_real_predicate(op_id);
    2738                 :       1192 :                 return LLVMBuildFCmp(g->builder, pred, op1_value, op2_value, "");
    2739         [ +  + ]:      13948 :             } else if (scalar_type->id == ZigTypeIdInt) {
    2740                 :      12944 :                 LLVMIntPredicate pred = cmp_op_to_int_predicate(op_id, scalar_type->data.integral.is_signed);
    2741                 :      12944 :                 return LLVMBuildICmp(g->builder, pred, op1_value, op2_value, "");
    2742 [ +  + ][ +  - ]:       1756 :             } else if (scalar_type->id == ZigTypeIdEnum ||
    2743         [ +  + ]:        566 :                     scalar_type->id == ZigTypeIdErrorSet ||
    2744   [ +  +  +  - ]:       1756 :                     scalar_type->id == ZigTypeIdBool ||
    2745                 :        436 :                     get_codegen_ptr_type(scalar_type) != nullptr)
    2746                 :            :             {
    2747                 :       1004 :                 LLVMIntPredicate pred = cmp_op_to_int_predicate(op_id, false);
    2748                 :       1004 :                 return LLVMBuildICmp(g->builder, pred, op1_value, op2_value, "");
    2749                 :            :             } else {
    2750                 :          0 :                 zig_unreachable();
    2751                 :            :             }
    2752                 :      11210 :         case IrBinOpMult:
    2753                 :            :         case IrBinOpMultWrap:
    2754                 :            :         case IrBinOpAdd:
    2755                 :            :         case IrBinOpAddWrap:
    2756                 :            :         case IrBinOpSub:
    2757                 :            :         case IrBinOpSubWrap: {
    2758 [ +  + ][ +  + ]:      11210 :             bool is_wrapping = (op_id == IrBinOpSubWrap || op_id == IrBinOpAddWrap || op_id == IrBinOpMultWrap);
                 [ +  + ]
    2759                 :      11210 :             AddSubMul add_sub_mul =
    2760 [ +  + ][ +  + ]:      16045 :                 op_id == IrBinOpAdd || op_id == IrBinOpAddWrap ? AddSubMulAdd :
    2761 [ +  + ][ +  + ]:       4835 :                 op_id == IrBinOpSub || op_id == IrBinOpSubWrap ? AddSubMulSub :
    2762                 :            :                 AddSubMulMul;
    2763                 :            : 
    2764         [ +  + ]:      11210 :             if (scalar_type->id == ZigTypeIdPointer) {
    2765                 :        265 :                 assert(scalar_type->data.pointer.ptr_len != PtrLenSingle);
    2766                 :            :                 LLVMValueRef subscript_value;
    2767         [ -  + ]:        265 :                 if (operand_type->id == ZigTypeIdVector)
    2768                 :          0 :                     zig_panic("TODO: Implement vector operations on pointers.");
    2769                 :            : 
    2770   [ +  +  -  - ]:        265 :                 switch (add_sub_mul) {
    2771                 :        216 :                     case AddSubMulAdd:
    2772                 :        216 :                         subscript_value = op2_value;
    2773                 :        216 :                         break;
    2774                 :         49 :                     case AddSubMulSub:
    2775                 :         49 :                         subscript_value = LLVMBuildNeg(g->builder, op2_value, "");
    2776                 :         49 :                         break;
    2777                 :          0 :                     case AddSubMulMul:
    2778                 :          0 :                         zig_unreachable();
    2779                 :            :                 }
    2780                 :            : 
    2781                 :            :                 // TODO runtime safety
    2782                 :        265 :                 return LLVMBuildInBoundsGEP(g->builder, op1_value, &subscript_value, 1, "");
    2783         [ +  + ]:      10945 :             } else if (scalar_type->id == ZigTypeIdFloat) {
    2784                 :       2146 :                 ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &bin_op_instruction->base));
    2785                 :       2146 :                 return float_op[add_sub_mul](g->builder, op1_value, op2_value, "");
    2786         [ +  - ]:       8799 :             } else if (scalar_type->id == ZigTypeIdInt) {
    2787         [ +  + ]:       8799 :                 if (is_wrapping) {
    2788                 :       1047 :                     return wrap_op[add_sub_mul](g->builder, op1_value, op2_value, "");
    2789         [ +  + ]:       7752 :                 } else if (want_runtime_safety) {
    2790                 :       6104 :                     return gen_overflow_op(g, operand_type, add_sub_mul, op1_value, op2_value);
    2791         [ +  + ]:       1648 :                 } else if (scalar_type->data.integral.is_signed) {
    2792                 :        416 :                     return signed_op[add_sub_mul](g->builder, op1_value, op2_value, "");
    2793                 :            :                 } else {
    2794                 :       1232 :                     return unsigned_op[add_sub_mul](g->builder, op1_value, op2_value, "");
    2795                 :            :                 }
    2796                 :            :             } else {
    2797                 :          0 :                 zig_unreachable();
    2798                 :            :             }
    2799                 :            :         }
    2800                 :       1369 :         case IrBinOpBinOr:
    2801                 :       1369 :             return LLVMBuildOr(g->builder, op1_value, op2_value, "");
    2802                 :        486 :         case IrBinOpBinXor:
    2803                 :        486 :             return LLVMBuildXor(g->builder, op1_value, op2_value, "");
    2804                 :       1676 :         case IrBinOpBinAnd:
    2805                 :       1676 :             return LLVMBuildAnd(g->builder, op1_value, op2_value, "");
    2806                 :       1485 :         case IrBinOpBitShiftLeftLossy:
    2807                 :            :         case IrBinOpBitShiftLeftExact:
    2808                 :            :             {
    2809                 :       1485 :                 assert(scalar_type->id == ZigTypeIdInt);
    2810                 :       1485 :                 LLVMValueRef op2_casted = gen_widen_or_shorten(g, false, op2->value.type, scalar_type, op2_value);
    2811                 :       1485 :                 bool is_sloppy = (op_id == IrBinOpBitShiftLeftLossy);
    2812         [ +  + ]:       1485 :                 if (is_sloppy) {
    2813                 :       1477 :                     return LLVMBuildShl(g->builder, op1_value, op2_casted, "");
    2814         [ +  - ]:          8 :                 } else if (want_runtime_safety) {
    2815                 :          8 :                     return gen_overflow_shl_op(g, scalar_type, op1_value, op2_casted);
    2816         [ #  # ]:          0 :                 } else if (scalar_type->data.integral.is_signed) {
    2817                 :          0 :                     return ZigLLVMBuildNSWShl(g->builder, op1_value, op2_casted, "");
    2818                 :            :                 } else {
    2819                 :          0 :                     return ZigLLVMBuildNUWShl(g->builder, op1_value, op2_casted, "");
    2820                 :            :                 }
    2821                 :            :             }
    2822                 :       1486 :         case IrBinOpBitShiftRightLossy:
    2823                 :            :         case IrBinOpBitShiftRightExact:
    2824                 :            :             {
    2825                 :       1486 :                 assert(scalar_type->id == ZigTypeIdInt);
    2826                 :       1486 :                 LLVMValueRef op2_casted = gen_widen_or_shorten(g, false, op2->value.type, scalar_type, op2_value);
    2827                 :       1486 :                 bool is_sloppy = (op_id == IrBinOpBitShiftRightLossy);
    2828         [ +  + ]:       1486 :                 if (is_sloppy) {
    2829         [ +  + ]:       1478 :                     if (scalar_type->data.integral.is_signed) {
    2830                 :        170 :                         return LLVMBuildAShr(g->builder, op1_value, op2_casted, "");
    2831                 :            :                     } else {
    2832                 :       1308 :                         return LLVMBuildLShr(g->builder, op1_value, op2_casted, "");
    2833                 :            :                     }
    2834         [ +  - ]:          8 :                 } else if (want_runtime_safety) {
    2835                 :          8 :                     return gen_overflow_shr_op(g, scalar_type, op1_value, op2_casted);
    2836         [ #  # ]:          0 :                 } else if (scalar_type->data.integral.is_signed) {
    2837                 :          0 :                     return ZigLLVMBuildAShrExact(g->builder, op1_value, op2_casted, "");
    2838                 :            :                 } else {
    2839                 :          0 :                     return ZigLLVMBuildLShrExact(g->builder, op1_value, op2_casted, "");
    2840                 :            :                 }
    2841                 :            :             }
    2842                 :        172 :         case IrBinOpDivUnspecified:
    2843                 :        172 :             return gen_div(g, want_runtime_safety, ir_want_fast_math(g, &bin_op_instruction->base),
    2844                 :        172 :                     op1_value, op2_value, scalar_type, DivKindFloat);
    2845                 :         32 :         case IrBinOpDivExact:
    2846                 :         32 :             return gen_div(g, want_runtime_safety, ir_want_fast_math(g, &bin_op_instruction->base),
    2847                 :         32 :                     op1_value, op2_value, scalar_type, DivKindExact);
    2848                 :        549 :         case IrBinOpDivTrunc:
    2849                 :        549 :             return gen_div(g, want_runtime_safety, ir_want_fast_math(g, &bin_op_instruction->base),
    2850                 :        549 :                     op1_value, op2_value, scalar_type, DivKindTrunc);
    2851                 :         26 :         case IrBinOpDivFloor:
    2852                 :         26 :             return gen_div(g, want_runtime_safety, ir_want_fast_math(g, &bin_op_instruction->base),
    2853                 :         26 :                     op1_value, op2_value, scalar_type, DivKindFloor);
    2854                 :        407 :         case IrBinOpRemRem:
    2855                 :        407 :             return gen_rem(g, want_runtime_safety, ir_want_fast_math(g, &bin_op_instruction->base),
    2856                 :        407 :                     op1_value, op2_value, scalar_type, RemKindRem);
    2857                 :         18 :         case IrBinOpRemMod:
    2858                 :         18 :             return gen_rem(g, want_runtime_safety, ir_want_fast_math(g, &bin_op_instruction->base),
    2859                 :         18 :                     op1_value, op2_value, scalar_type, RemKindMod);
    2860                 :            :     }
    2861                 :          0 :     zig_unreachable();
    2862                 :            : }
    2863                 :            : 
    2864                 :         26 : static void add_error_range_check(CodeGen *g, ZigType *err_set_type, ZigType *int_type, LLVMValueRef target_val) {
    2865                 :         26 :     assert(err_set_type->id == ZigTypeIdErrorSet);
    2866                 :            : 
    2867         [ +  + ]:         26 :     if (type_is_global_error_set(err_set_type)) {
    2868                 :          9 :         LLVMValueRef zero = LLVMConstNull(get_llvm_type(g, int_type));
    2869                 :          9 :         LLVMValueRef neq_zero_bit = LLVMBuildICmp(g->builder, LLVMIntNE, target_val, zero, "");
    2870                 :            :         LLVMValueRef ok_bit;
    2871                 :            : 
    2872                 :          9 :         BigInt biggest_possible_err_val = {0};
    2873                 :          9 :         eval_min_max_value_int(g, int_type, &biggest_possible_err_val, true);
    2874                 :            : 
    2875         [ -  + ]:         18 :         if (bigint_fits_in_bits(&biggest_possible_err_val, 64, false) &&
           [ +  -  -  + ]
    2876                 :          9 :             bigint_as_usize(&biggest_possible_err_val) < g->errors_by_index.length)
    2877                 :            :         {
    2878                 :          0 :             ok_bit = neq_zero_bit;
    2879                 :            :         } else {
    2880                 :          9 :             LLVMValueRef error_value_count = LLVMConstInt(get_llvm_type(g, int_type), g->errors_by_index.length, false);
    2881                 :          9 :             LLVMValueRef in_bounds_bit = LLVMBuildICmp(g->builder, LLVMIntULT, target_val, error_value_count, "");
    2882                 :          9 :             ok_bit = LLVMBuildAnd(g->builder, neq_zero_bit, in_bounds_bit, "");
    2883                 :            :         }
    2884                 :            : 
    2885                 :          9 :         LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "IntToErrOk");
    2886                 :          9 :         LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "IntToErrFail");
    2887                 :            : 
    2888                 :          9 :         LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    2889                 :            : 
    2890                 :          9 :         LLVMPositionBuilderAtEnd(g->builder, fail_block);
    2891                 :          9 :         gen_safety_crash(g, PanicMsgIdInvalidErrorCode);
    2892                 :            : 
    2893                 :          9 :         LLVMPositionBuilderAtEnd(g->builder, ok_block);
    2894                 :            :     } else {
    2895                 :         17 :         LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "IntToErrOk");
    2896                 :         17 :         LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "IntToErrFail");
    2897                 :            : 
    2898                 :         17 :         uint32_t err_count = err_set_type->data.error_set.err_count;
    2899                 :         17 :         LLVMValueRef switch_instr = LLVMBuildSwitch(g->builder, target_val, fail_block, err_count);
    2900         [ +  + ]:         67 :         for (uint32_t i = 0; i < err_count; i += 1) {
    2901                 :         50 :             LLVMValueRef case_value = LLVMConstInt(get_llvm_type(g, g->err_tag_type),
    2902                 :         50 :                     err_set_type->data.error_set.errors[i]->value, false);
    2903                 :         50 :             LLVMAddCase(switch_instr, case_value, ok_block);
    2904                 :            :         }
    2905                 :            : 
    2906                 :         17 :         LLVMPositionBuilderAtEnd(g->builder, fail_block);
    2907                 :         17 :         gen_safety_crash(g, PanicMsgIdInvalidErrorCode);
    2908                 :            : 
    2909                 :         17 :         LLVMPositionBuilderAtEnd(g->builder, ok_block);
    2910                 :            :     }
    2911                 :         26 : }
    2912                 :            : 
    2913                 :        406 : static LLVMValueRef ir_render_resize_slice(CodeGen *g, IrExecutable *executable,
    2914                 :            :         IrInstructionResizeSlice *instruction)
    2915                 :            : {
    2916                 :        406 :     ZigType *actual_type = instruction->operand->value.type;
    2917                 :        406 :     ZigType *wanted_type = instruction->base.value.type;
    2918                 :        406 :     LLVMValueRef expr_val = ir_llvm_value(g, instruction->operand);
    2919                 :        406 :     assert(expr_val);
    2920                 :            : 
    2921                 :        406 :     LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    2922                 :        406 :     assert(wanted_type->id == ZigTypeIdStruct);
    2923                 :        406 :     assert(wanted_type->data.structure.is_slice);
    2924                 :        406 :     assert(actual_type->id == ZigTypeIdStruct);
    2925                 :        406 :     assert(actual_type->data.structure.is_slice);
    2926                 :            : 
    2927                 :        406 :     ZigType *actual_pointer_type = actual_type->data.structure.fields[0].type_entry;
    2928                 :        406 :     ZigType *actual_child_type = actual_pointer_type->data.pointer.child_type;
    2929                 :        406 :     ZigType *wanted_pointer_type = wanted_type->data.structure.fields[0].type_entry;
    2930                 :        406 :     ZigType *wanted_child_type = wanted_pointer_type->data.pointer.child_type;
    2931                 :            : 
    2932                 :            : 
    2933                 :        406 :     size_t actual_ptr_index = actual_type->data.structure.fields[slice_ptr_index].gen_index;
    2934                 :        406 :     size_t actual_len_index = actual_type->data.structure.fields[slice_len_index].gen_index;
    2935                 :        406 :     size_t wanted_ptr_index = wanted_type->data.structure.fields[slice_ptr_index].gen_index;
    2936                 :        406 :     size_t wanted_len_index = wanted_type->data.structure.fields[slice_len_index].gen_index;
    2937                 :            : 
    2938                 :        406 :     LLVMValueRef src_ptr_ptr = LLVMBuildStructGEP(g->builder, expr_val, (unsigned)actual_ptr_index, "");
    2939                 :        406 :     LLVMValueRef src_ptr = gen_load_untyped(g, src_ptr_ptr, 0, false, "");
    2940                 :        406 :     LLVMValueRef src_ptr_casted = LLVMBuildBitCast(g->builder, src_ptr,
    2941                 :        406 :             get_llvm_type(g, wanted_type->data.structure.fields[0].type_entry), "");
    2942                 :        406 :     LLVMValueRef dest_ptr_ptr = LLVMBuildStructGEP(g->builder, result_loc,
    2943                 :        406 :             (unsigned)wanted_ptr_index, "");
    2944                 :        406 :     gen_store_untyped(g, src_ptr_casted, dest_ptr_ptr, 0, false);
    2945                 :            : 
    2946                 :        406 :     LLVMValueRef src_len_ptr = LLVMBuildStructGEP(g->builder, expr_val, (unsigned)actual_len_index, "");
    2947                 :        406 :     LLVMValueRef src_len = gen_load_untyped(g, src_len_ptr, 0, false, "");
    2948                 :        406 :     uint64_t src_size = type_size(g, actual_child_type);
    2949                 :        406 :     uint64_t dest_size = type_size(g, wanted_child_type);
    2950                 :            : 
    2951                 :            :     LLVMValueRef new_len;
    2952         [ +  + ]:        406 :     if (dest_size == 1) {
    2953                 :        270 :         LLVMValueRef src_size_val = LLVMConstInt(g->builtin_types.entry_usize->llvm_type, src_size, false);
    2954                 :        270 :         new_len = LLVMBuildMul(g->builder, src_len, src_size_val, "");
    2955         [ +  - ]:        136 :     } else if (src_size == 1) {
    2956                 :        136 :         LLVMValueRef dest_size_val = LLVMConstInt(g->builtin_types.entry_usize->llvm_type, dest_size, false);
    2957         [ +  - ]:        136 :         if (ir_want_runtime_safety(g, &instruction->base)) {
    2958                 :        136 :             LLVMValueRef remainder_val = LLVMBuildURem(g->builder, src_len, dest_size_val, "");
    2959                 :        136 :             LLVMValueRef zero = LLVMConstNull(g->builtin_types.entry_usize->llvm_type);
    2960                 :        136 :             LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, remainder_val, zero, "");
    2961                 :        136 :             LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "SliceWidenOk");
    2962                 :        136 :             LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "SliceWidenFail");
    2963                 :        136 :             LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    2964                 :            : 
    2965                 :        136 :             LLVMPositionBuilderAtEnd(g->builder, fail_block);
    2966                 :        136 :             gen_safety_crash(g, PanicMsgIdSliceWidenRemainder);
    2967                 :            : 
    2968                 :        136 :             LLVMPositionBuilderAtEnd(g->builder, ok_block);
    2969                 :            :         }
    2970                 :        136 :         new_len = LLVMBuildExactUDiv(g->builder, src_len, dest_size_val, "");
    2971                 :            :     } else {
    2972                 :          0 :         zig_unreachable();
    2973                 :            :     }
    2974                 :            : 
    2975                 :        406 :     LLVMValueRef dest_len_ptr = LLVMBuildStructGEP(g->builder, result_loc, (unsigned)wanted_len_index, "");
    2976                 :        406 :     gen_store_untyped(g, new_len, dest_len_ptr, 0, false);
    2977                 :            : 
    2978                 :        406 :     return result_loc;
    2979                 :            : }
    2980                 :            : 
    2981                 :       6343 : static LLVMValueRef ir_render_cast(CodeGen *g, IrExecutable *executable,
    2982                 :            :         IrInstructionCast *cast_instruction)
    2983                 :            : {
    2984                 :       6343 :     ZigType *actual_type = cast_instruction->value->value.type;
    2985                 :       6343 :     ZigType *wanted_type = cast_instruction->base.value.type;
    2986                 :       6343 :     LLVMValueRef expr_val = ir_llvm_value(g, cast_instruction->value);
    2987                 :       6343 :     assert(expr_val);
    2988                 :            : 
    2989   [ -  +  +  +  :       6343 :     switch (cast_instruction->cast_op) {
             +  +  +  - ]
    2990                 :          0 :         case CastOpNoCast:
    2991                 :            :         case CastOpNumLitToConcrete:
    2992                 :          0 :             zig_unreachable();
    2993                 :       4382 :         case CastOpNoop:
    2994                 :       4382 :             return expr_val;
    2995                 :        116 :         case CastOpIntToFloat:
    2996                 :        116 :             assert(actual_type->id == ZigTypeIdInt);
    2997         [ +  + ]:        116 :             if (actual_type->data.integral.is_signed) {
    2998                 :         68 :                 return LLVMBuildSIToFP(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    2999                 :            :             } else {
    3000                 :         48 :                 return LLVMBuildUIToFP(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    3001                 :            :             }
    3002                 :        124 :         case CastOpFloatToInt: {
    3003                 :        124 :             assert(wanted_type->id == ZigTypeIdInt);
    3004                 :        124 :             ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &cast_instruction->base));
    3005                 :            : 
    3006                 :        124 :             bool want_safety = ir_want_runtime_safety(g, &cast_instruction->base);
    3007                 :            : 
    3008                 :            :             LLVMValueRef result;
    3009         [ +  + ]:        124 :             if (wanted_type->data.integral.is_signed) {
    3010                 :         68 :                 result = LLVMBuildFPToSI(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    3011                 :            :             } else {
    3012                 :         56 :                 result = LLVMBuildFPToUI(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    3013                 :            :             }
    3014                 :            : 
    3015         [ +  - ]:        124 :             if (want_safety) {
    3016                 :            :                 LLVMValueRef back_to_float;
    3017         [ +  + ]:        124 :                 if (wanted_type->data.integral.is_signed) {
    3018                 :         68 :                     back_to_float = LLVMBuildSIToFP(g->builder, result, LLVMTypeOf(expr_val), "");
    3019                 :            :                 } else {
    3020                 :         56 :                     back_to_float = LLVMBuildUIToFP(g->builder, result, LLVMTypeOf(expr_val), "");
    3021                 :            :                 }
    3022                 :        124 :                 LLVMValueRef difference = LLVMBuildFSub(g->builder, expr_val, back_to_float, "");
    3023                 :        124 :                 LLVMValueRef one_pos = LLVMConstReal(LLVMTypeOf(expr_val), 1.0f);
    3024                 :        124 :                 LLVMValueRef one_neg = LLVMConstReal(LLVMTypeOf(expr_val), -1.0f);
    3025                 :        124 :                 LLVMValueRef ok_bit_pos = LLVMBuildFCmp(g->builder, LLVMRealOLT, difference, one_pos, "");
    3026                 :        124 :                 LLVMValueRef ok_bit_neg = LLVMBuildFCmp(g->builder, LLVMRealOGT, difference, one_neg, "");
    3027                 :        124 :                 LLVMValueRef ok_bit = LLVMBuildAnd(g->builder, ok_bit_pos, ok_bit_neg, "");
    3028                 :        124 :                 LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "FloatCheckOk");
    3029                 :        124 :                 LLVMBasicBlockRef bad_block = LLVMAppendBasicBlock(g->cur_fn_val, "FloatCheckFail");
    3030                 :        124 :                 LLVMBuildCondBr(g->builder, ok_bit, ok_block, bad_block);
    3031                 :        124 :                 LLVMPositionBuilderAtEnd(g->builder, bad_block);
    3032                 :        124 :                 gen_safety_crash(g, PanicMsgIdFloatToInt);
    3033                 :        124 :                 LLVMPositionBuilderAtEnd(g->builder, ok_block);
    3034                 :            :             }
    3035                 :        124 :             return result;
    3036                 :            :         }
    3037                 :        127 :         case CastOpBoolToInt:
    3038                 :        127 :             assert(wanted_type->id == ZigTypeIdInt);
    3039                 :        127 :             assert(actual_type->id == ZigTypeIdBool);
    3040                 :        127 :             return LLVMBuildZExt(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    3041                 :         17 :         case CastOpErrSet:
    3042         [ +  - ]:         17 :             if (ir_want_runtime_safety(g, &cast_instruction->base)) {
    3043                 :         17 :                 add_error_range_check(g, wanted_type, g->err_tag_type, expr_val);
    3044                 :            :             }
    3045                 :         17 :             return expr_val;
    3046                 :       1577 :         case CastOpBitCast:
    3047                 :       1577 :             return LLVMBuildBitCast(g->builder, expr_val, get_llvm_type(g, wanted_type), "");
    3048                 :            :     }
    3049                 :          0 :     zig_unreachable();
    3050                 :            : }
    3051                 :            : 
    3052                 :        142 : static LLVMValueRef ir_render_ptr_of_array_to_slice(CodeGen *g, IrExecutable *executable,
    3053                 :            :         IrInstructionPtrOfArrayToSlice *instruction)
    3054                 :            : {
    3055                 :        142 :     ZigType *actual_type = instruction->operand->value.type;
    3056                 :        142 :     ZigType *slice_type = instruction->base.value.type;
    3057                 :        142 :     ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index].type_entry;
    3058                 :        142 :     size_t ptr_index = slice_type->data.structure.fields[slice_ptr_index].gen_index;
    3059                 :        142 :     size_t len_index = slice_type->data.structure.fields[slice_len_index].gen_index;
    3060                 :            : 
    3061                 :        142 :     LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    3062                 :            : 
    3063                 :        142 :     assert(actual_type->id == ZigTypeIdPointer);
    3064                 :        142 :     ZigType *array_type = actual_type->data.pointer.child_type;
    3065                 :        142 :     assert(array_type->id == ZigTypeIdArray);
    3066                 :            : 
    3067         [ +  + ]:        142 :     if (type_has_bits(actual_type)) {
    3068                 :        126 :         LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, result_loc, ptr_index, "");
    3069                 :            :         LLVMValueRef indices[] = {
    3070                 :        126 :             LLVMConstNull(g->builtin_types.entry_usize->llvm_type),
    3071                 :        126 :             LLVMConstInt(g->builtin_types.entry_usize->llvm_type, 0, false),
    3072                 :        252 :         };
    3073                 :        126 :         LLVMValueRef expr_val = ir_llvm_value(g, instruction->operand);
    3074                 :        126 :         LLVMValueRef slice_start_ptr = LLVMBuildInBoundsGEP(g->builder, expr_val, indices, 2, "");
    3075                 :        126 :         gen_store_untyped(g, slice_start_ptr, ptr_field_ptr, 0, false);
    3076         [ +  - ]:         16 :     } else if (ir_want_runtime_safety(g, &instruction->base)) {
    3077                 :         16 :         LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, result_loc, ptr_index, "");
    3078                 :         16 :         gen_undef_init(g, slice_ptr_type->abi_align, slice_ptr_type, ptr_field_ptr);
    3079                 :            :     }
    3080                 :            : 
    3081                 :        142 :     LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, result_loc, len_index, "");
    3082                 :        142 :     LLVMValueRef len_value = LLVMConstInt(g->builtin_types.entry_usize->llvm_type,
    3083                 :        142 :             array_type->data.array.len, false);
    3084                 :        142 :     gen_store_untyped(g, len_value, len_field_ptr, 0, false);
    3085                 :            : 
    3086                 :        142 :     return result_loc;
    3087                 :            : }
    3088                 :            : 
    3089                 :        984 : static LLVMValueRef ir_render_ptr_cast(CodeGen *g, IrExecutable *executable,
    3090                 :            :         IrInstructionPtrCastGen *instruction)
    3091                 :            : {
    3092                 :        984 :     ZigType *wanted_type = instruction->base.value.type;
    3093         [ -  + ]:        984 :     if (!type_has_bits(wanted_type)) {
    3094                 :          0 :         return nullptr;
    3095                 :            :     }
    3096                 :        984 :     LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
    3097                 :        984 :     LLVMValueRef result_ptr = LLVMBuildBitCast(g->builder, ptr, get_llvm_type(g, wanted_type), "");
    3098 [ +  + ][ +  + ]:        984 :     bool want_safety_check = instruction->safety_check_on && ir_want_runtime_safety(g, &instruction->base);
    3099 [ +  + ][ +  + ]:        984 :     if (!want_safety_check || ptr_allows_addr_zero(wanted_type))
                 [ +  + ]
    3100                 :        605 :         return result_ptr;
    3101                 :            : 
    3102                 :        379 :     LLVMValueRef zero = LLVMConstNull(LLVMTypeOf(result_ptr));
    3103                 :        379 :     LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntNE, result_ptr, zero, "");
    3104                 :        379 :     LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "PtrCastFail");
    3105                 :        379 :     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "PtrCastOk");
    3106                 :        379 :     LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    3107                 :            : 
    3108                 :        379 :     LLVMPositionBuilderAtEnd(g->builder, fail_block);
    3109                 :        379 :     gen_safety_crash(g, PanicMsgIdPtrCastNull);
    3110                 :            : 
    3111                 :        379 :     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    3112                 :        379 :     return result_ptr;
    3113                 :            : }
    3114                 :            : 
    3115                 :       1345 : static LLVMValueRef ir_render_bit_cast(CodeGen *g, IrExecutable *executable,
    3116                 :            :         IrInstructionBitCastGen *instruction)
    3117                 :            : {
    3118                 :       1345 :     ZigType *wanted_type = instruction->base.value.type;
    3119                 :       1345 :     ZigType *actual_type = instruction->operand->value.type;
    3120                 :       1345 :     LLVMValueRef value = ir_llvm_value(g, instruction->operand);
    3121                 :            : 
    3122                 :       1345 :     bool wanted_is_ptr = handle_is_ptr(wanted_type);
    3123                 :       1345 :     bool actual_is_ptr = handle_is_ptr(actual_type);
    3124         [ +  - ]:       1345 :     if (wanted_is_ptr == actual_is_ptr) {
    3125                 :            :         // We either bitcast the value directly or bitcast the pointer which does a pointer cast
    3126         [ -  + ]:       1345 :         LLVMTypeRef wanted_type_ref = wanted_is_ptr ?
    3127                 :          0 :             LLVMPointerType(get_llvm_type(g, wanted_type), 0) : get_llvm_type(g, wanted_type);
    3128                 :       1345 :         return LLVMBuildBitCast(g->builder, value, wanted_type_ref, "");
    3129         [ #  # ]:          0 :     } else if (actual_is_ptr) {
    3130                 :          0 :         LLVMTypeRef wanted_ptr_type_ref = LLVMPointerType(get_llvm_type(g, wanted_type), 0);
    3131                 :          0 :         LLVMValueRef bitcasted_ptr = LLVMBuildBitCast(g->builder, value, wanted_ptr_type_ref, "");
    3132                 :          0 :         uint32_t alignment = get_abi_alignment(g, actual_type);
    3133                 :          0 :         return gen_load_untyped(g, bitcasted_ptr, alignment, false, "");
    3134                 :            :     } else {
    3135                 :          0 :         zig_unreachable();
    3136                 :            :     }
    3137                 :            : }
    3138                 :            : 
    3139                 :       5231 : static LLVMValueRef ir_render_widen_or_shorten(CodeGen *g, IrExecutable *executable,
    3140                 :            :         IrInstructionWidenOrShorten *instruction)
    3141                 :            : {
    3142                 :       5231 :     ZigType *actual_type = instruction->target->value.type;
    3143                 :            :     // TODO instead of this logic, use the Noop instruction to change the type from
    3144                 :            :     // enum_tag to the underlying int type
    3145                 :            :     ZigType *int_type;
    3146         [ +  + ]:       5231 :     if (actual_type->id == ZigTypeIdEnum) {
    3147                 :         67 :         int_type = actual_type->data.enumeration.tag_int_type;
    3148                 :            :     } else {
    3149                 :       5164 :         int_type = actual_type;
    3150                 :            :     }
    3151                 :       5231 :     LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    3152                 :       5231 :     return gen_widen_or_shorten(g, ir_want_runtime_safety(g, &instruction->base), int_type,
    3153                 :       5231 :             instruction->base.value.type, target_val);
    3154                 :            : }
    3155                 :            : 
    3156                 :        431 : static LLVMValueRef ir_render_int_to_ptr(CodeGen *g, IrExecutable *executable, IrInstructionIntToPtr *instruction) {
    3157                 :        431 :     ZigType *wanted_type = instruction->base.value.type;
    3158                 :        431 :     LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    3159 [ +  - ][ +  + ]:        431 :     if (!ptr_allows_addr_zero(wanted_type) && ir_want_runtime_safety(g, &instruction->base)) {
                 [ +  + ]
    3160                 :        407 :         LLVMValueRef zero = LLVMConstNull(LLVMTypeOf(target_val));
    3161                 :        407 :         LLVMValueRef is_zero_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, target_val, zero, "");
    3162                 :        407 :         LLVMBasicBlockRef bad_block = LLVMAppendBasicBlock(g->cur_fn_val, "PtrToIntBad");
    3163                 :        407 :         LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "PtrToIntOk");
    3164                 :        407 :         LLVMBuildCondBr(g->builder, is_zero_bit, bad_block, ok_block);
    3165                 :            : 
    3166                 :        407 :         LLVMPositionBuilderAtEnd(g->builder, bad_block);
    3167                 :        407 :         gen_safety_crash(g, PanicMsgIdPtrCastNull);
    3168                 :            : 
    3169                 :        407 :         LLVMPositionBuilderAtEnd(g->builder, ok_block);
    3170                 :            :     }
    3171                 :        431 :     return LLVMBuildIntToPtr(g->builder, target_val, get_llvm_type(g, wanted_type), "");
    3172                 :            : }
    3173                 :            : 
    3174                 :        700 : static LLVMValueRef ir_render_ptr_to_int(CodeGen *g, IrExecutable *executable, IrInstructionPtrToInt *instruction) {
    3175                 :        700 :     ZigType *wanted_type = instruction->base.value.type;
    3176                 :        700 :     LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    3177                 :        700 :     return LLVMBuildPtrToInt(g->builder, target_val, get_llvm_type(g, wanted_type), "");
    3178                 :            : }
    3179                 :            : 
    3180                 :         10 : static LLVMValueRef ir_render_int_to_enum(CodeGen *g, IrExecutable *executable, IrInstructionIntToEnum *instruction) {
    3181                 :         10 :     ZigType *wanted_type = instruction->base.value.type;
    3182                 :         10 :     assert(wanted_type->id == ZigTypeIdEnum);
    3183                 :         10 :     ZigType *tag_int_type = wanted_type->data.enumeration.tag_int_type;
    3184                 :            : 
    3185                 :         10 :     LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    3186                 :         10 :     LLVMValueRef tag_int_value = gen_widen_or_shorten(g, ir_want_runtime_safety(g, &instruction->base),
    3187                 :         10 :             instruction->target->value.type, tag_int_type, target_val);
    3188                 :            : 
    3189         [ +  - ]:         10 :     if (ir_want_runtime_safety(g, &instruction->base)) {
    3190                 :         10 :         LLVMBasicBlockRef bad_value_block = LLVMAppendBasicBlock(g->cur_fn_val, "BadValue");
    3191                 :         10 :         LLVMBasicBlockRef ok_value_block = LLVMAppendBasicBlock(g->cur_fn_val, "OkValue");
    3192                 :         10 :         size_t field_count = wanted_type->data.enumeration.src_field_count;
    3193                 :         10 :         LLVMValueRef switch_instr = LLVMBuildSwitch(g->builder, tag_int_value, bad_value_block, field_count);
    3194         [ +  + ]:         54 :         for (size_t field_i = 0; field_i < field_count; field_i += 1) {
    3195                 :         44 :             LLVMValueRef this_tag_int_value = bigint_to_llvm_const(get_llvm_type(g, tag_int_type),
    3196                 :         44 :                     &wanted_type->data.enumeration.fields[field_i].value);
    3197                 :         44 :             LLVMAddCase(switch_instr, this_tag_int_value, ok_value_block);
    3198                 :            :         }
    3199                 :         10 :         LLVMPositionBuilderAtEnd(g->builder, bad_value_block);
    3200                 :         10 :         gen_safety_crash(g, PanicMsgIdBadEnumValue);
    3201                 :            : 
    3202                 :         10 :         LLVMPositionBuilderAtEnd(g->builder, ok_value_block);
    3203                 :            :     }
    3204                 :         10 :     return tag_int_value;
    3205                 :            : }
    3206                 :            : 
    3207                 :          9 : static LLVMValueRef ir_render_int_to_err(CodeGen *g, IrExecutable *executable, IrInstructionIntToErr *instruction) {
    3208                 :          9 :     ZigType *wanted_type = instruction->base.value.type;
    3209                 :          9 :     assert(wanted_type->id == ZigTypeIdErrorSet);
    3210                 :            : 
    3211                 :          9 :     ZigType *actual_type = instruction->target->value.type;
    3212                 :          9 :     assert(actual_type->id == ZigTypeIdInt);
    3213                 :          9 :     assert(!actual_type->data.integral.is_signed);
    3214                 :            : 
    3215                 :          9 :     LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    3216                 :            : 
    3217         [ +  - ]:          9 :     if (ir_want_runtime_safety(g, &instruction->base)) {
    3218                 :          9 :         add_error_range_check(g, wanted_type, actual_type, target_val);
    3219                 :            :     }
    3220                 :            : 
    3221                 :          9 :     return gen_widen_or_shorten(g, false, actual_type, g->err_tag_type, target_val);
    3222                 :            : }
    3223                 :            : 
    3224                 :          9 : static LLVMValueRef ir_render_err_to_int(CodeGen *g, IrExecutable *executable, IrInstructionErrToInt *instruction) {
    3225                 :          9 :     ZigType *wanted_type = instruction->base.value.type;
    3226                 :          9 :     assert(wanted_type->id == ZigTypeIdInt);
    3227                 :          9 :     assert(!wanted_type->data.integral.is_signed);
    3228                 :            : 
    3229                 :          9 :     ZigType *actual_type = instruction->target->value.type;
    3230                 :          9 :     LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    3231                 :            : 
    3232         [ +  - ]:          9 :     if (actual_type->id == ZigTypeIdErrorSet) {
    3233                 :          9 :         return gen_widen_or_shorten(g, ir_want_runtime_safety(g, &instruction->base),
    3234                 :          9 :             g->err_tag_type, wanted_type, target_val);
    3235         [ #  # ]:          0 :     } else if (actual_type->id == ZigTypeIdErrorUnion) {
    3236                 :            :         // this should have been a compile time constant
    3237                 :          0 :         assert(type_has_bits(actual_type->data.error_union.err_set_type));
    3238                 :            : 
    3239         [ #  # ]:          0 :         if (!type_has_bits(actual_type->data.error_union.payload_type)) {
    3240                 :          0 :             return gen_widen_or_shorten(g, ir_want_runtime_safety(g, &instruction->base),
    3241                 :          0 :                 g->err_tag_type, wanted_type, target_val);
    3242                 :            :         } else {
    3243                 :          0 :             zig_panic("TODO err to int when error union payload type not void");
    3244                 :            :         }
    3245                 :            :     } else {
    3246                 :          0 :         zig_unreachable();
    3247                 :            :     }
    3248                 :            : }
    3249                 :            : 
    3250                 :        942 : static LLVMValueRef ir_render_unreachable(CodeGen *g, IrExecutable *executable,
    3251                 :            :         IrInstructionUnreachable *unreachable_instruction)
    3252                 :            : {
    3253         [ +  + ]:        942 :     if (ir_want_runtime_safety(g, &unreachable_instruction->base)) {
    3254                 :        936 :         gen_safety_crash(g, PanicMsgIdUnreachable);
    3255                 :            :     } else {
    3256                 :          6 :         LLVMBuildUnreachable(g->builder);
    3257                 :            :     }
    3258                 :        942 :     return nullptr;
    3259                 :            : }
    3260                 :            : 
    3261                 :      20951 : static LLVMValueRef ir_render_cond_br(CodeGen *g, IrExecutable *executable,
    3262                 :            :         IrInstructionCondBr *cond_br_instruction)
    3263                 :            : {
    3264                 :      20951 :     LLVMBuildCondBr(g->builder,
    3265                 :            :             ir_llvm_value(g, cond_br_instruction->condition),
    3266                 :      20951 :             cond_br_instruction->then_block->llvm_block,
    3267                 :      20951 :             cond_br_instruction->else_block->llvm_block);
    3268                 :      20951 :     return nullptr;
    3269                 :            : }
    3270                 :            : 
    3271                 :      28010 : static LLVMValueRef ir_render_br(CodeGen *g, IrExecutable *executable, IrInstructionBr *br_instruction) {
    3272                 :      28010 :     LLVMBuildBr(g->builder, br_instruction->dest_block->llvm_block);
    3273                 :      28010 :     return nullptr;
    3274                 :            : }
    3275                 :            : 
    3276                 :        241 : static LLVMValueRef ir_render_un_op(CodeGen *g, IrExecutable *executable, IrInstructionUnOp *un_op_instruction) {
    3277                 :        241 :     IrUnOp op_id = un_op_instruction->op_id;
    3278                 :        241 :     LLVMValueRef expr = ir_llvm_value(g, un_op_instruction->value);
    3279                 :        241 :     ZigType *operand_type = un_op_instruction->value->value.type;
    3280         [ +  + ]:        241 :     ZigType *scalar_type = (operand_type->id == ZigTypeIdVector) ? operand_type->data.vector.elem_type : operand_type;
    3281                 :            : 
    3282   [ -  +  +  - ]:        241 :     switch (op_id) {
    3283                 :          0 :         case IrUnOpInvalid:
    3284                 :            :         case IrUnOpOptional:
    3285                 :            :         case IrUnOpDereference:
    3286                 :          0 :             zig_unreachable();
    3287                 :        186 :         case IrUnOpNegation:
    3288                 :            :         case IrUnOpNegationWrap:
    3289                 :            :             {
    3290         [ +  + ]:        186 :                 if (scalar_type->id == ZigTypeIdFloat) {
    3291                 :         60 :                     ZigLLVMSetFastMath(g->builder, ir_want_fast_math(g, &un_op_instruction->base));
    3292                 :         60 :                     return LLVMBuildFNeg(g->builder, expr, "");
    3293         [ +  - ]:        126 :                 } else if (scalar_type->id == ZigTypeIdInt) {
    3294         [ +  + ]:        126 :                     if (op_id == IrUnOpNegationWrap) {
    3295                 :         16 :                         return LLVMBuildNeg(g->builder, expr, "");
    3296         [ +  + ]:        110 :                     } else if (ir_want_runtime_safety(g, &un_op_instruction->base)) {
    3297                 :         54 :                         LLVMValueRef zero = LLVMConstNull(LLVMTypeOf(expr));
    3298                 :         54 :                         return gen_overflow_op(g, operand_type, AddSubMulSub, zero, expr);
    3299         [ +  - ]:         56 :                     } else if (scalar_type->data.integral.is_signed) {
    3300                 :         56 :                         return LLVMBuildNSWNeg(g->builder, expr, "");
    3301                 :            :                     } else {
    3302                 :          0 :                         return LLVMBuildNUWNeg(g->builder, expr, "");
    3303                 :            :                     }
    3304                 :            :                 } else {
    3305                 :          0 :                     zig_unreachable();
    3306                 :            :                 }
    3307                 :            :             }
    3308                 :         55 :         case IrUnOpBinNot:
    3309                 :         55 :             return LLVMBuildNot(g->builder, expr, "");
    3310                 :            :     }
    3311                 :            : 
    3312                 :          0 :     zig_unreachable();
    3313                 :            : }
    3314                 :            : 
    3315                 :       1384 : static LLVMValueRef ir_render_bool_not(CodeGen *g, IrExecutable *executable, IrInstructionBoolNot *instruction) {
    3316                 :       1384 :     LLVMValueRef value = ir_llvm_value(g, instruction->value);
    3317                 :       1384 :     LLVMValueRef zero = LLVMConstNull(LLVMTypeOf(value));
    3318                 :       1384 :     return LLVMBuildICmp(g->builder, LLVMIntEQ, value, zero, "");
    3319                 :            : }
    3320                 :            : 
    3321                 :      25496 : static void render_decl_var(CodeGen *g, ZigVar *var) {
    3322         [ +  + ]:      25496 :     if (!type_has_bits(var->var_type))
    3323                 :        569 :         return;
    3324                 :            : 
    3325                 :      24927 :     var->value_ref = ir_llvm_value(g, var->ptr_instruction);
    3326                 :      24927 :     gen_var_debug_decl(g, var);
    3327                 :            : }
    3328                 :            : 
    3329                 :      25280 : static LLVMValueRef ir_render_decl_var(CodeGen *g, IrExecutable *executable, IrInstructionDeclVarGen *instruction) {
    3330                 :      25280 :     instruction->var->ptr_instruction = instruction->var_ptr;
    3331                 :      25280 :     render_decl_var(g, instruction->var);
    3332                 :      25280 :     return nullptr;
    3333                 :            : }
    3334                 :            : 
    3335                 :     117989 : static LLVMValueRef ir_render_load_ptr(CodeGen *g, IrExecutable *executable, IrInstructionLoadPtrGen *instruction) {
    3336                 :     117989 :     ZigType *child_type = instruction->base.value.type;
    3337         [ -  + ]:     117989 :     if (!type_has_bits(child_type))
    3338                 :          0 :         return nullptr;
    3339                 :            : 
    3340                 :     117989 :     LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
    3341                 :     117989 :     ZigType *ptr_type = instruction->ptr->value.type;
    3342                 :     117989 :     assert(ptr_type->id == ZigTypeIdPointer);
    3343                 :            : 
    3344                 :     117989 :     uint32_t host_int_bytes = ptr_type->data.pointer.host_int_bytes;
    3345         [ +  + ]:     117989 :     if (host_int_bytes == 0)
    3346                 :     117399 :         return get_handle_value(g, ptr, child_type, ptr_type);
    3347                 :            : 
    3348                 :        590 :     bool big_endian = g->is_big_endian;
    3349                 :            : 
    3350                 :        590 :     LLVMValueRef containing_int = gen_load(g, ptr, ptr_type, "");
    3351                 :        590 :     uint32_t host_bit_count = LLVMGetIntTypeWidth(LLVMTypeOf(containing_int));
    3352                 :        590 :     assert(host_bit_count == host_int_bytes * 8);
    3353                 :        590 :     uint32_t size_in_bits = type_size_bits(g, child_type);
    3354                 :            : 
    3355                 :        590 :     uint32_t bit_offset = ptr_type->data.pointer.bit_offset_in_host;
    3356         [ -  + ]:        590 :     uint32_t shift_amt = big_endian ? host_bit_count - bit_offset - size_in_bits : bit_offset;
    3357                 :            : 
    3358                 :        590 :     LLVMValueRef shift_amt_val = LLVMConstInt(LLVMTypeOf(containing_int), shift_amt, false);
    3359                 :        590 :     LLVMValueRef shifted_value = LLVMBuildLShr(g->builder, containing_int, shift_amt_val, "");
    3360                 :            : 
    3361         [ +  + ]:        590 :     if (handle_is_ptr(child_type)) {
    3362                 :          8 :         LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    3363                 :          8 :         LLVMTypeRef same_size_int = LLVMIntType(size_in_bits);
    3364                 :          8 :         LLVMValueRef truncated_int = LLVMBuildTrunc(g->builder, shifted_value, same_size_int, "");
    3365                 :          8 :         LLVMValueRef bitcasted_ptr = LLVMBuildBitCast(g->builder, result_loc,
    3366                 :          8 :                                                       LLVMPointerType(same_size_int, 0), "");
    3367                 :          8 :         LLVMBuildStore(g->builder, truncated_int, bitcasted_ptr);
    3368                 :          8 :         return result_loc;
    3369                 :            :     }
    3370                 :            : 
    3371         [ +  + ]:        582 :     if (child_type->id == ZigTypeIdFloat) {
    3372                 :         96 :         LLVMTypeRef same_size_int = LLVMIntType(size_in_bits);
    3373                 :         96 :         LLVMValueRef truncated_int = LLVMBuildTrunc(g->builder, shifted_value, same_size_int, "");
    3374                 :         96 :         return LLVMBuildBitCast(g->builder, truncated_int, get_llvm_type(g, child_type), "");
    3375                 :            :     }
    3376                 :            : 
    3377                 :        486 :     return LLVMBuildTrunc(g->builder, shifted_value, get_llvm_type(g, child_type), "");
    3378                 :            : }
    3379                 :            : 
    3380                 :        392 : static bool value_is_all_undef_array(CodeGen *g, ConstExprValue *const_val, size_t len) {
    3381   [ -  +  +  - ]:        392 :     switch (const_val->data.x_array.special) {
    3382                 :          0 :         case ConstArraySpecialUndef:
    3383                 :          0 :             return true;
    3384                 :         58 :         case ConstArraySpecialBuf:
    3385                 :         58 :             return false;
    3386                 :        334 :         case ConstArraySpecialNone:
    3387         [ +  - ]:        334 :             for (size_t i = 0; i < len; i += 1) {
    3388         [ +  - ]:        334 :                 if (!value_is_all_undef(g, &const_val->data.x_array.data.s_none.elements[i]))
    3389                 :        334 :                     return false;
    3390                 :            :             }
    3391                 :          0 :             return true;
    3392                 :            :     }
    3393                 :          0 :     zig_unreachable();
    3394                 :            : }
    3395                 :            : 
    3396                 :      38290 : static bool value_is_all_undef(CodeGen *g, ConstExprValue *const_val) {
    3397                 :            :     Error err;
    3398 [ +  + ][ -  + ]:      38290 :     if (const_val->special == ConstValSpecialLazy &&
                 [ -  + ]
    3399                 :            :         (err = ir_resolve_lazy(g, nullptr, const_val)))
    3400                 :          0 :         report_errors_and_exit(g);
    3401                 :            : 
    3402   [ -  +  +  +  :      38290 :     switch (const_val->special) {
                      - ]
    3403                 :          0 :         case ConstValSpecialLazy:
    3404                 :          0 :             zig_unreachable();
    3405                 :      26302 :         case ConstValSpecialRuntime:
    3406                 :      26302 :             return false;
    3407                 :       1773 :         case ConstValSpecialUndef:
    3408                 :       1773 :             return true;
    3409                 :      10215 :         case ConstValSpecialStatic:
    3410         [ +  + ]:      10215 :             if (const_val->type->id == ZigTypeIdStruct) {
    3411         [ +  - ]:        562 :                 for (size_t i = 0; i < const_val->type->data.structure.src_field_count; i += 1) {
    3412         [ +  + ]:        562 :                     if (!value_is_all_undef(g, &const_val->data.x_struct.fields[i]))
    3413                 :        557 :                         return false;
    3414                 :            :                 }
    3415                 :          0 :                 return true;
    3416         [ +  + ]:       9658 :             } else if (const_val->type->id == ZigTypeIdArray) {
    3417                 :        296 :                 return value_is_all_undef_array(g, const_val, const_val->type->data.array.len);
    3418         [ +  + ]:       9362 :             } else if (const_val->type->id == ZigTypeIdVector) {
    3419                 :         96 :                 return value_is_all_undef_array(g, const_val, const_val->type->data.vector.len);
    3420                 :            :             } else {
    3421                 :       9266 :                 return false;
    3422                 :            :             }
    3423                 :            :     }
    3424                 :          0 :     zig_unreachable();
    3425                 :            : }
    3426                 :            : 
    3427                 :       1165 : static LLVMValueRef gen_valgrind_client_request(CodeGen *g, LLVMValueRef default_value, LLVMValueRef request,
    3428                 :            :         LLVMValueRef a1, LLVMValueRef a2, LLVMValueRef a3, LLVMValueRef a4, LLVMValueRef a5)
    3429                 :            : {
    3430         [ -  + ]:       1165 :     if (!target_has_valgrind_support(g->zig_target)) {
    3431                 :          0 :         return default_value;
    3432                 :            :     }
    3433                 :       1165 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    3434                 :       1165 :     bool asm_has_side_effects = true;
    3435                 :       1165 :     bool asm_is_alignstack = false;
    3436         [ +  - ]:       1165 :     if (g->zig_target->arch == ZigLLVM_x86_64) {
    3437 [ +  + ][ -  + ]:       1165 :         if (g->zig_target->os == OsLinux || target_os_is_darwin(g->zig_target->os) || g->zig_target->os == OsSolaris ||
         [ #  # ][ #  # ]
                 [ +  - ]
    3438         [ #  # ]:          0 :             (g->zig_target->os == OsWindows && g->zig_target->abi != ZigLLVM_MSVC))
    3439                 :            :         {
    3440         [ +  + ]:       1165 :             if (g->cur_fn->valgrind_client_request_array == nullptr) {
    3441                 :        912 :                 LLVMBasicBlockRef prev_block = LLVMGetInsertBlock(g->builder);
    3442                 :        912 :                 LLVMBasicBlockRef entry_block = LLVMGetEntryBasicBlock(g->cur_fn->llvm_value);
    3443                 :        912 :                 LLVMValueRef first_inst = LLVMGetFirstInstruction(entry_block);
    3444                 :        912 :                 LLVMPositionBuilderBefore(g->builder, first_inst);
    3445                 :        912 :                 LLVMTypeRef array_type_ref = LLVMArrayType(usize_type_ref, 6);
    3446                 :        912 :                 g->cur_fn->valgrind_client_request_array = LLVMBuildAlloca(g->builder, array_type_ref, "");
    3447                 :        912 :                 LLVMPositionBuilderAtEnd(g->builder, prev_block);
    3448                 :            :             }
    3449                 :       1165 :             LLVMValueRef array_ptr = g->cur_fn->valgrind_client_request_array;
    3450                 :       1165 :             LLVMValueRef array_elements[] = {request, a1, a2, a3, a4, a5};
    3451                 :       1165 :             LLVMValueRef zero = LLVMConstInt(usize_type_ref, 0, false);
    3452         [ +  + ]:       8155 :             for (unsigned i = 0; i < 6; i += 1) {
    3453                 :            :                 LLVMValueRef indexes[] = {
    3454                 :            :                     zero,
    3455                 :       6990 :                     LLVMConstInt(usize_type_ref, i, false),
    3456                 :      13980 :                 };
    3457                 :       6990 :                 LLVMValueRef elem_ptr = LLVMBuildInBoundsGEP(g->builder, array_ptr, indexes, 2, "");
    3458                 :       6990 :                 LLVMBuildStore(g->builder, array_elements[i], elem_ptr);
    3459                 :            :             }
    3460                 :            : 
    3461                 :            :             Buf *asm_template = buf_create_from_str(
    3462                 :            :                 "rolq $$3,  %rdi ; rolq $$13, %rdi\n"
    3463                 :            :                 "rolq $$61, %rdi ; rolq $$51, %rdi\n"
    3464                 :            :                 "xchgq %rbx,%rbx\n"
    3465                 :       1165 :             );
    3466                 :            :             Buf *asm_constraints = buf_create_from_str(
    3467                 :            :                 "={rdx},{rax},0,~{cc},~{memory}"
    3468                 :       1165 :             );
    3469                 :       1165 :             unsigned input_and_output_count = 2;
    3470                 :       1165 :             LLVMValueRef array_ptr_as_usize = LLVMBuildPtrToInt(g->builder, array_ptr, usize_type_ref, "");
    3471                 :       1165 :             LLVMValueRef param_values[] = { array_ptr_as_usize, default_value };
    3472                 :       1165 :             LLVMTypeRef param_types[] = {usize_type_ref, usize_type_ref};
    3473                 :            :             LLVMTypeRef function_type = LLVMFunctionType(usize_type_ref, param_types,
    3474                 :       1165 :                     input_and_output_count, false);
    3475                 :       1165 :             LLVMValueRef asm_fn = LLVMGetInlineAsm(function_type, buf_ptr(asm_template), buf_len(asm_template),
    3476                 :            :                     buf_ptr(asm_constraints), buf_len(asm_constraints), asm_has_side_effects, asm_is_alignstack,
    3477                 :       1165 :                     LLVMInlineAsmDialectATT);
    3478                 :       1165 :             return LLVMBuildCall(g->builder, asm_fn, param_values, input_and_output_count, "");
    3479                 :            :         }
    3480                 :            :     }
    3481                 :          0 :     zig_unreachable();
    3482                 :            : }
    3483                 :            : 
    3484                 :       1751 : static bool want_valgrind_support(CodeGen *g) {
    3485         [ +  + ]:       1751 :     if (!target_has_valgrind_support(g->zig_target))
    3486                 :        405 :         return false;
    3487   [ +  -  +  - ]:       1346 :     switch (g->valgrind_support) {
    3488                 :        160 :         case ValgrindSupportDisabled:
    3489                 :        160 :             return false;
    3490                 :          0 :         case ValgrindSupportEnabled:
    3491                 :          0 :             return true;
    3492                 :       1186 :         case ValgrindSupportAuto:
    3493                 :       1186 :             return g->build_mode == BuildModeDebug;
    3494                 :            :     }
    3495                 :          0 :     zig_unreachable();
    3496                 :            : }
    3497                 :            : 
    3498                 :       1165 : static void gen_valgrind_undef(CodeGen *g, LLVMValueRef dest_ptr, LLVMValueRef byte_count) {
    3499                 :            :     static const uint32_t VG_USERREQ__MAKE_MEM_UNDEFINED = 1296236545;
    3500                 :       1165 :     ZigType *usize = g->builtin_types.entry_usize;
    3501                 :       1165 :     LLVMValueRef zero = LLVMConstInt(usize->llvm_type, 0, false);
    3502                 :       1165 :     LLVMValueRef req = LLVMConstInt(usize->llvm_type, VG_USERREQ__MAKE_MEM_UNDEFINED, false);
    3503                 :       1165 :     LLVMValueRef ptr_as_usize = LLVMBuildPtrToInt(g->builder, dest_ptr, usize->llvm_type, "");
    3504                 :       1165 :     gen_valgrind_client_request(g, zero, req, ptr_as_usize, byte_count, zero, zero, zero);
    3505                 :       1165 : }
    3506                 :            : 
    3507                 :       1355 : static void gen_undef_init(CodeGen *g, uint32_t ptr_align_bytes, ZigType *value_type, LLVMValueRef ptr) {
    3508                 :       1355 :     assert(type_has_bits(value_type));
    3509                 :       1355 :     uint64_t size_bytes = LLVMStoreSizeOfType(g->target_data_ref, get_llvm_type(g, value_type));
    3510                 :       1355 :     assert(size_bytes > 0);
    3511                 :       1355 :     assert(ptr_align_bytes > 0);
    3512                 :            :     // memset uninitialized memory to 0xaa
    3513                 :       1355 :     LLVMTypeRef ptr_u8 = LLVMPointerType(LLVMInt8Type(), 0);
    3514                 :       1355 :     LLVMValueRef fill_char = LLVMConstInt(LLVMInt8Type(), 0xaa, false);
    3515                 :       1355 :     LLVMValueRef dest_ptr = LLVMBuildBitCast(g->builder, ptr, ptr_u8, "");
    3516                 :       1355 :     ZigType *usize = g->builtin_types.entry_usize;
    3517                 :       1355 :     LLVMValueRef byte_count = LLVMConstInt(usize->llvm_type, size_bytes, false);
    3518                 :       1355 :     ZigLLVMBuildMemSet(g->builder, dest_ptr, fill_char, byte_count, ptr_align_bytes, false);
    3519                 :            :     // then tell valgrind that the memory is undefined even though we just memset it
    3520         [ +  + ]:       1355 :     if (want_valgrind_support(g)) {
    3521                 :        956 :         gen_valgrind_undef(g, dest_ptr, byte_count);
    3522                 :            :     }
    3523                 :       1355 : }
    3524                 :            : 
    3525                 :      37122 : static LLVMValueRef ir_render_store_ptr(CodeGen *g, IrExecutable *executable, IrInstructionStorePtr *instruction) {
    3526                 :      37122 :     ZigType *ptr_type = instruction->ptr->value.type;
    3527                 :      37122 :     assert(ptr_type->id == ZigTypeIdPointer);
    3528         [ -  + ]:      37122 :     if (!type_has_bits(ptr_type))
    3529                 :          0 :         return nullptr;
    3530         [ +  + ]:      37122 :     if (instruction->ptr->ref_count == 0) {
    3531                 :            :         // In this case, this StorePtr instruction should be elided. Something happened like this:
    3532                 :            :         //     var t = true;
    3533                 :            :         //     const x = if (t) Num.Two else unreachable;
    3534                 :            :         // The if condition is a runtime value, so the StorePtr for `x = Num.Two` got generated
    3535                 :            :         // (this instruction being rendered) but because of `else unreachable` the result ended
    3536                 :            :         // up being a comptime const value.
    3537                 :          8 :         return nullptr;
    3538                 :            :     }
    3539                 :            : 
    3540                 :      37114 :     bool have_init_expr = !value_is_all_undef(g, &instruction->value->value);
    3541         [ +  + ]:      37114 :     if (have_init_expr) {
    3542                 :      35599 :         LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
    3543                 :      35599 :         LLVMValueRef value = ir_llvm_value(g, instruction->value);
    3544                 :      35599 :         gen_assign_raw(g, ptr, ptr_type, value);
    3545         [ +  + ]:       1515 :     } else if (ir_want_runtime_safety(g, &instruction->base)) {
    3546                 :       1339 :         gen_undef_init(g, get_ptr_align(g, ptr_type), instruction->value->value.type,
    3547                 :            :             ir_llvm_value(g, instruction->ptr));
    3548                 :            :     }
    3549                 :      37114 :     return nullptr;
    3550                 :            : }
    3551                 :            : 
    3552                 :     103697 : static LLVMValueRef ir_render_var_ptr(CodeGen *g, IrExecutable *executable, IrInstructionVarPtr *instruction) {
    3553         [ +  + ]:     103697 :     if (instruction->base.value.special != ConstValSpecialRuntime)
    3554                 :       2907 :         return ir_llvm_value(g, &instruction->base);
    3555                 :     100790 :     ZigVar *var = instruction->var;
    3556         [ +  + ]:     100790 :     if (type_has_bits(var->var_type)) {
    3557                 :     100726 :         assert(var->value_ref);
    3558                 :     100726 :         return var->value_ref;
    3559                 :            :     } else {
    3560                 :         64 :         return nullptr;
    3561                 :            :     }
    3562                 :            : }
    3563                 :            : 
    3564                 :       5391 : static LLVMValueRef ir_render_return_ptr(CodeGen *g, IrExecutable *executable,
    3565                 :            :         IrInstructionReturnPtr *instruction)
    3566                 :            : {
    3567         [ -  + ]:       5391 :     if (!type_has_bits(instruction->base.value.type))
    3568                 :          0 :         return nullptr;
    3569                 :       5391 :     src_assert(g->cur_ret_ptr != nullptr, instruction->base.source_node);
    3570                 :       5391 :     return g->cur_ret_ptr;
    3571                 :            : }
    3572                 :            : 
    3573                 :       6508 : static LLVMValueRef ir_render_elem_ptr(CodeGen *g, IrExecutable *executable, IrInstructionElemPtr *instruction) {
    3574                 :       6508 :     LLVMValueRef array_ptr_ptr = ir_llvm_value(g, instruction->array_ptr);
    3575                 :       6508 :     ZigType *array_ptr_type = instruction->array_ptr->value.type;
    3576                 :       6508 :     assert(array_ptr_type->id == ZigTypeIdPointer);
    3577                 :       6508 :     ZigType *array_type = array_ptr_type->data.pointer.child_type;
    3578                 :       6508 :     LLVMValueRef array_ptr = get_handle_value(g, array_ptr_ptr, array_type, array_ptr_type);
    3579                 :       6508 :     LLVMValueRef subscript_value = ir_llvm_value(g, instruction->elem_index);
    3580                 :       6508 :     assert(subscript_value);
    3581                 :            : 
    3582         [ -  + ]:       6508 :     if (!type_has_bits(array_type))
    3583                 :          0 :         return nullptr;
    3584                 :            : 
    3585 [ +  + ][ +  + ]:       6508 :     bool safety_check_on = ir_want_runtime_safety(g, &instruction->base) && instruction->safety_check_on;
    3586                 :            : 
    3587 [ +  + ][ +  + ]:       6508 :     if (array_type->id == ZigTypeIdArray ||
    3588         [ +  + ]:        355 :         (array_type->id == ZigTypeIdPointer && array_type->data.pointer.ptr_len == PtrLenSingle))
    3589                 :            :     {
    3590         [ +  + ]:       3214 :         if (array_type->id == ZigTypeIdPointer) {
    3591                 :         24 :             assert(array_type->data.pointer.child_type->id == ZigTypeIdArray);
    3592                 :         24 :             array_type = array_type->data.pointer.child_type;
    3593                 :            :         }
    3594         [ +  + ]:       3214 :         if (safety_check_on) {
    3595                 :        930 :             LLVMValueRef end = LLVMConstInt(g->builtin_types.entry_usize->llvm_type,
    3596                 :        930 :                     array_type->data.array.len, false);
    3597                 :        930 :             add_bounds_check(g, subscript_value, LLVMIntEQ, nullptr, LLVMIntULT, end);
    3598                 :            :         }
    3599         [ +  + ]:       3214 :         if (array_ptr_type->data.pointer.host_int_bytes != 0) {
    3600                 :        120 :             return array_ptr_ptr;
    3601                 :            :         }
    3602                 :       3094 :         ZigType *child_type = array_type->data.array.child_type;
    3603 [ +  + ][ +  + ]:       3094 :         if (child_type->id == ZigTypeIdStruct &&
    3604                 :        679 :             child_type->data.structure.layout == ContainerLayoutPacked)
    3605                 :            :         {
    3606                 :        140 :             ZigType *ptr_type = instruction->base.value.type;
    3607                 :        140 :             size_t host_int_bytes = ptr_type->data.pointer.host_int_bytes;
    3608         [ -  + ]:        140 :             if (host_int_bytes != 0) {
    3609                 :          0 :                 uint32_t size_in_bits = type_size_bits(g, ptr_type->data.pointer.child_type);
    3610                 :          0 :                 LLVMTypeRef ptr_u8_type_ref = LLVMPointerType(LLVMInt8Type(), 0);
    3611                 :          0 :                 LLVMValueRef u8_array_ptr = LLVMBuildBitCast(g->builder, array_ptr, ptr_u8_type_ref, "");
    3612                 :          0 :                 assert(size_in_bits % 8 == 0);
    3613                 :          0 :                 LLVMValueRef elem_size_bytes = LLVMConstInt(g->builtin_types.entry_usize->llvm_type,
    3614                 :          0 :                         size_in_bits / 8, false);
    3615                 :          0 :                 LLVMValueRef byte_offset = LLVMBuildNUWMul(g->builder, subscript_value, elem_size_bytes, "");
    3616                 :            :                 LLVMValueRef indices[] = {
    3617                 :            :                     byte_offset
    3618                 :          0 :                 };
    3619                 :          0 :                 LLVMValueRef elem_byte_ptr = LLVMBuildInBoundsGEP(g->builder, u8_array_ptr, indices, 1, "");
    3620                 :        140 :                 return LLVMBuildBitCast(g->builder, elem_byte_ptr, LLVMPointerType(get_llvm_type(g, child_type), 0), "");
    3621                 :            :             }
    3622                 :            :         }
    3623                 :            :         LLVMValueRef indices[] = {
    3624                 :       3094 :             LLVMConstNull(g->builtin_types.entry_usize->llvm_type),
    3625                 :            :             subscript_value
    3626                 :       3094 :         };
    3627                 :       3214 :         return LLVMBuildInBoundsGEP(g->builder, array_ptr, indices, 2, "");
    3628         [ +  + ]:       3294 :     } else if (array_type->id == ZigTypeIdPointer) {
    3629                 :        331 :         assert(LLVMGetTypeKind(LLVMTypeOf(array_ptr)) == LLVMPointerTypeKind);
    3630                 :            :         LLVMValueRef indices[] = {
    3631                 :            :             subscript_value
    3632                 :        331 :         };
    3633                 :        331 :         return LLVMBuildInBoundsGEP(g->builder, array_ptr, indices, 1, "");
    3634         [ +  - ]:       2963 :     } else if (array_type->id == ZigTypeIdStruct) {
    3635                 :       2963 :         assert(array_type->data.structure.is_slice);
    3636                 :            : 
    3637                 :       2963 :         ZigType *ptr_type = instruction->base.value.type;
    3638         [ +  + ]:       2963 :         if (!type_has_bits(ptr_type)) {
    3639         [ -  + ]:          8 :             if (safety_check_on) {
    3640                 :          0 :                 assert(LLVMGetTypeKind(LLVMTypeOf(array_ptr)) == LLVMIntegerTypeKind);
    3641                 :          0 :                 add_bounds_check(g, subscript_value, LLVMIntEQ, nullptr, LLVMIntULT, array_ptr);
    3642                 :            :             }
    3643                 :          8 :             return nullptr;
    3644                 :            :         }
    3645                 :            : 
    3646                 :       2955 :         assert(LLVMGetTypeKind(LLVMTypeOf(array_ptr)) == LLVMPointerTypeKind);
    3647                 :       2955 :         assert(LLVMGetTypeKind(LLVMGetElementType(LLVMTypeOf(array_ptr))) == LLVMStructTypeKind);
    3648                 :            : 
    3649         [ +  + ]:       2955 :         if (safety_check_on) {
    3650                 :       2582 :             size_t len_index = array_type->data.structure.fields[slice_len_index].gen_index;
    3651                 :       2582 :             assert(len_index != SIZE_MAX);
    3652                 :       2582 :             LLVMValueRef len_ptr = LLVMBuildStructGEP(g->builder, array_ptr, (unsigned)len_index, "");
    3653                 :       2582 :             LLVMValueRef len = gen_load_untyped(g, len_ptr, 0, false, "");
    3654                 :       2582 :             add_bounds_check(g, subscript_value, LLVMIntEQ, nullptr, LLVMIntULT, len);
    3655                 :            :         }
    3656                 :            : 
    3657                 :       2955 :         size_t ptr_index = array_type->data.structure.fields[slice_ptr_index].gen_index;
    3658                 :       2955 :         assert(ptr_index != SIZE_MAX);
    3659                 :       2955 :         LLVMValueRef ptr_ptr = LLVMBuildStructGEP(g->builder, array_ptr, (unsigned)ptr_index, "");
    3660                 :       2955 :         LLVMValueRef ptr = gen_load_untyped(g, ptr_ptr, 0, false, "");
    3661                 :       2955 :         return LLVMBuildInBoundsGEP(g->builder, ptr, &subscript_value, 1, "");
    3662                 :            :     } else {
    3663                 :       6508 :         zig_unreachable();
    3664                 :            :     }
    3665                 :            : }
    3666                 :            : 
    3667                 :         16 : static LLVMValueRef get_new_stack_addr(CodeGen *g, LLVMValueRef new_stack) {
    3668                 :         16 :     LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, new_stack, (unsigned)slice_ptr_index, "");
    3669                 :         16 :     LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, new_stack, (unsigned)slice_len_index, "");
    3670                 :            : 
    3671                 :         16 :     LLVMValueRef ptr_value = gen_load_untyped(g, ptr_field_ptr, 0, false, "");
    3672                 :         16 :     LLVMValueRef len_value = gen_load_untyped(g, len_field_ptr, 0, false, "");
    3673                 :            : 
    3674                 :         16 :     LLVMValueRef ptr_addr = LLVMBuildPtrToInt(g->builder, ptr_value, LLVMTypeOf(len_value), "");
    3675                 :         16 :     LLVMValueRef end_addr = LLVMBuildNUWAdd(g->builder, ptr_addr, len_value, "");
    3676                 :         16 :     LLVMValueRef align_amt = LLVMConstInt(LLVMTypeOf(end_addr), get_abi_alignment(g, g->builtin_types.entry_usize), false);
    3677                 :         16 :     LLVMValueRef align_adj = LLVMBuildURem(g->builder, end_addr, align_amt, "");
    3678                 :         16 :     return LLVMBuildNUWSub(g->builder, end_addr, align_adj, "");
    3679                 :            : }
    3680                 :            : 
    3681                 :         16 : static void gen_set_stack_pointer(CodeGen *g, LLVMValueRef aligned_end_addr) {
    3682                 :         16 :     LLVMValueRef write_register_fn_val = get_write_register_fn_val(g);
    3683                 :            : 
    3684         [ +  + ]:         16 :     if (g->sp_md_node == nullptr) {
    3685                 :          8 :         Buf *sp_reg_name = buf_create_from_str(arch_stack_pointer_register_name(g->zig_target->arch));
    3686                 :          8 :         LLVMValueRef str_node = LLVMMDString(buf_ptr(sp_reg_name), buf_len(sp_reg_name) + 1);
    3687                 :          8 :         g->sp_md_node = LLVMMDNode(&str_node, 1);
    3688                 :            :     }
    3689                 :            : 
    3690                 :            :     LLVMValueRef params[] = {
    3691                 :         16 :         g->sp_md_node,
    3692                 :            :         aligned_end_addr,
    3693                 :         16 :     };
    3694                 :            : 
    3695                 :         16 :     LLVMBuildCall(g->builder, write_register_fn_val, params, 2, "");
    3696                 :         16 : }
    3697                 :            : 
    3698                 :       6729 : static void set_call_instr_sret(CodeGen *g, LLVMValueRef call_instr) {
    3699                 :       6729 :     unsigned attr_kind_id = LLVMGetEnumAttributeKindForName("sret", 4);
    3700                 :       6729 :     LLVMAttributeRef sret_attr = LLVMCreateEnumAttribute(LLVMGetGlobalContext(), attr_kind_id, 0);
    3701                 :       6729 :     LLVMAddCallSiteAttribute(call_instr, 1, sret_attr);
    3702                 :       6729 : }
    3703                 :            : 
    3704                 :        824 : static void render_async_spills(CodeGen *g) {
    3705                 :        824 :     ZigType *fn_type = g->cur_fn->type_entry;
    3706                 :        824 :     ZigType *import = get_scope_import(&g->cur_fn->fndef_scope->base);
    3707                 :        824 :     uint32_t async_var_index = frame_index_arg(g, fn_type->data.fn.fn_type_id.return_type);
    3708         [ +  + ]:       3376 :     for (size_t var_i = 0; var_i < g->cur_fn->variable_list.length; var_i += 1) {
    3709                 :       2552 :         ZigVar *var = g->cur_fn->variable_list.at(var_i);
    3710                 :            : 
    3711         [ +  + ]:       2552 :         if (!type_has_bits(var->var_type)) {
    3712                 :         96 :             continue;
    3713                 :            :         }
    3714         [ -  + ]:       2456 :         if (ir_get_var_is_comptime(var))
    3715                 :          0 :             continue;
    3716   [ -  -  +  - ]:       2456 :         switch (type_requires_comptime(g, var->var_type)) {
    3717                 :          0 :             case ReqCompTimeInvalid:
    3718                 :          0 :                 zig_unreachable();
    3719                 :          0 :             case ReqCompTimeYes:
    3720                 :          0 :                 continue;
    3721                 :       2456 :             case ReqCompTimeNo:
    3722                 :       2456 :                 break;
    3723                 :            :         }
    3724         [ +  + ]:       2456 :         if (var->src_arg_index == SIZE_MAX) {
    3725                 :       1984 :             continue;
    3726                 :            :         }
    3727                 :            : 
    3728                 :        472 :         var->value_ref = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr, async_var_index,
    3729                 :        472 :                 buf_ptr(&var->name));
    3730                 :        472 :         async_var_index += 1;
    3731         [ +  - ]:        472 :         if (var->decl_node) {
    3732                 :        944 :             var->di_loc_var = ZigLLVMCreateAutoVariable(g->dbuilder, get_di_scope(g, var->parent_scope),
    3733                 :        472 :                 buf_ptr(&var->name), import->data.structure.root_struct->di_file,
    3734                 :        472 :                 (unsigned)(var->decl_node->line + 1),
    3735                 :        472 :                 get_llvm_di_type(g, var->var_type), !g->strip_debug_symbols, 0);
    3736                 :        472 :             gen_var_debug_decl(g, var);
    3737                 :            :         }
    3738                 :            :     }
    3739                 :            : 
    3740                 :        824 :     ZigType *frame_type = g->cur_fn->frame_type->data.frame.locals_struct;
    3741                 :            : 
    3742         [ +  + ]:       4104 :     for (size_t alloca_i = 0; alloca_i < g->cur_fn->alloca_gen_list.length; alloca_i += 1) {
    3743                 :       3280 :         IrInstructionAllocaGen *instruction = g->cur_fn->alloca_gen_list.at(alloca_i);
    3744         [ +  + ]:       3280 :         if (instruction->field_index == SIZE_MAX)
    3745                 :        936 :             continue;
    3746                 :            : 
    3747                 :       2344 :         size_t gen_index = frame_type->data.structure.fields[instruction->field_index].gen_index;
    3748                 :       2344 :         instruction->base.llvm_value = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr, gen_index,
    3749                 :            :                 instruction->name_hint);
    3750                 :            :     }
    3751                 :        824 : }
    3752                 :            : 
    3753                 :       1464 : static void render_async_var_decls(CodeGen *g, Scope *scope) {
    3754                 :            :     for (;;) {
    3755   [ -  +  +  +  :       4688 :         switch (scope->id) {
                      - ]
    3756                 :          0 :             case ScopeIdCImport:
    3757                 :          0 :                 zig_unreachable();
    3758                 :       1464 :             case ScopeIdFnDef:
    3759                 :       1464 :                 return;
    3760                 :       1272 :             case ScopeIdVarDecl: {
    3761                 :       1272 :                 ZigVar *var = reinterpret_cast<ScopeVarDecl *>(scope)->var;
    3762         [ +  + ]:       1272 :                 if (var->ptr_instruction != nullptr) {
    3763                 :        216 :                     render_decl_var(g, var);
    3764                 :            :                 }
    3765                 :            :                 // fallthrough
    3766                 :            :             }
    3767                 :            :             case ScopeIdDecls:
    3768                 :            :             case ScopeIdBlock:
    3769                 :            :             case ScopeIdDefer:
    3770                 :            :             case ScopeIdDeferExpr:
    3771                 :            :             case ScopeIdLoop:
    3772                 :            :             case ScopeIdSuspend:
    3773                 :            :             case ScopeIdCompTime:
    3774                 :            :             case ScopeIdRuntime:
    3775                 :            :             case ScopeIdTypeOf:
    3776                 :       3224 :                 scope = scope->parent;
    3777                 :       3224 :                 continue;
    3778                 :            :         }
    3779                 :       3224 :     }
    3780                 :            : }
    3781                 :            : 
    3782                 :         72 : static LLVMValueRef gen_frame_size(CodeGen *g, LLVMValueRef fn_val) {
    3783                 :         72 :     assert(g->need_frame_size_prefix_data);
    3784                 :         72 :     LLVMTypeRef usize_llvm_type = g->builtin_types.entry_usize->llvm_type;
    3785                 :         72 :     LLVMTypeRef ptr_usize_llvm_type = LLVMPointerType(usize_llvm_type, 0);
    3786                 :         72 :     LLVMValueRef casted_fn_val = LLVMBuildBitCast(g->builder, fn_val, ptr_usize_llvm_type, "");
    3787                 :         72 :     LLVMValueRef negative_one = LLVMConstInt(LLVMInt32Type(), -1, true);
    3788                 :         72 :     LLVMValueRef prefix_ptr = LLVMBuildInBoundsGEP(g->builder, casted_fn_val, &negative_one, 1, "");
    3789                 :         72 :     return LLVMBuildLoad(g->builder, prefix_ptr, "");
    3790                 :            : }
    3791                 :            : 
    3792                 :        592 : static void gen_init_stack_trace(CodeGen *g, LLVMValueRef trace_field_ptr, LLVMValueRef addrs_field_ptr) {
    3793                 :        592 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    3794                 :        592 :     LLVMValueRef zero = LLVMConstNull(usize_type_ref);
    3795                 :            : 
    3796                 :        592 :     LLVMValueRef index_ptr = LLVMBuildStructGEP(g->builder, trace_field_ptr, 0, "");
    3797                 :        592 :     LLVMBuildStore(g->builder, zero, index_ptr);
    3798                 :            : 
    3799                 :        592 :     LLVMValueRef addrs_slice_ptr = LLVMBuildStructGEP(g->builder, trace_field_ptr, 1, "");
    3800                 :        592 :     LLVMValueRef addrs_ptr_ptr = LLVMBuildStructGEP(g->builder, addrs_slice_ptr, slice_ptr_index, "");
    3801                 :        592 :     LLVMValueRef indices[] = { LLVMConstNull(usize_type_ref), LLVMConstNull(usize_type_ref) };
    3802                 :        592 :     LLVMValueRef trace_field_addrs_as_ptr = LLVMBuildInBoundsGEP(g->builder, addrs_field_ptr, indices, 2, "");
    3803                 :        592 :     LLVMBuildStore(g->builder, trace_field_addrs_as_ptr, addrs_ptr_ptr);
    3804                 :            : 
    3805                 :        592 :     LLVMValueRef addrs_len_ptr = LLVMBuildStructGEP(g->builder, addrs_slice_ptr, slice_len_index, "");
    3806                 :        592 :     LLVMBuildStore(g->builder, LLVMConstInt(usize_type_ref, stack_trace_ptr_count, false), addrs_len_ptr);
    3807                 :        592 : }
    3808                 :            : 
    3809                 :      45715 : static LLVMValueRef ir_render_call(CodeGen *g, IrExecutable *executable, IrInstructionCallGen *instruction) {
    3810                 :      45715 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    3811                 :            : 
    3812                 :            :     LLVMValueRef fn_val;
    3813                 :            :     ZigType *fn_type;
    3814                 :            :     bool callee_is_async;
    3815         [ +  + ]:      45715 :     if (instruction->fn_entry) {
    3816                 :      43130 :         fn_val = fn_llvm_value(g, instruction->fn_entry);
    3817                 :      43130 :         fn_type = instruction->fn_entry->type_entry;
    3818                 :      43130 :         callee_is_async = fn_is_async(instruction->fn_entry);
    3819                 :            :     } else {
    3820                 :       2585 :         assert(instruction->fn_ref);
    3821                 :       2585 :         fn_val = ir_llvm_value(g, instruction->fn_ref);
    3822                 :       2585 :         fn_type = instruction->fn_ref->value.type;
    3823                 :       2585 :         callee_is_async = fn_type->data.fn.fn_type_id.cc == CallingConventionAsync;
    3824                 :            :     }
    3825                 :            : 
    3826                 :      45715 :     FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id;
    3827                 :            : 
    3828                 :      45715 :     ZigType *src_return_type = fn_type_id->return_type;
    3829                 :      45715 :     bool ret_has_bits = type_has_bits(src_return_type);
    3830                 :            : 
    3831                 :      45715 :     CallingConvention cc = fn_type->data.fn.fn_type_id.cc;
    3832                 :            : 
    3833 [ +  + ][ +  + ]:      45715 :     bool first_arg_ret = ret_has_bits && want_first_arg_sret(g, fn_type_id);
    3834                 :      45715 :     bool prefix_arg_err_ret_stack = codegen_fn_has_err_ret_tracing_arg(g, fn_type_id->return_type);
    3835                 :      45715 :     bool is_var_args = fn_type_id->is_var_args;
    3836                 :      45715 :     ZigList<LLVMValueRef> gen_param_values = {};
    3837                 :      45715 :     ZigList<ZigType *> gen_param_types = {};
    3838         [ +  + ]:      45715 :     LLVMValueRef result_loc = instruction->result_loc ? ir_llvm_value(g, instruction->result_loc) : nullptr;
    3839                 :      45715 :     LLVMValueRef zero = LLVMConstNull(usize_type_ref);
    3840                 :            :     LLVMValueRef frame_result_loc;
    3841                 :            :     LLVMValueRef awaiter_init_val;
    3842                 :            :     LLVMValueRef ret_ptr;
    3843         [ +  + ]:      45715 :     if (callee_is_async) {
    3844         [ +  + ]:        856 :         if (instruction->new_stack == nullptr) {
    3845         [ +  + ]:        768 :             if (instruction->is_async) {
    3846                 :        592 :                 frame_result_loc = result_loc;
    3847                 :            :             } else {
    3848                 :        768 :                 frame_result_loc = ir_llvm_value(g, instruction->frame_result_loc);
    3849                 :            :             }
    3850                 :            :         } else {
    3851 [ +  + ][ +  - ]:         88 :             if (instruction->new_stack->value.type->id == ZigTypeIdPointer &&
    3852                 :         32 :                 instruction->new_stack->value.type->data.pointer.child_type->id == ZigTypeIdFnFrame)
    3853                 :            :             {
    3854                 :         32 :                 frame_result_loc = ir_llvm_value(g, instruction->new_stack);
    3855                 :            :             } else {
    3856                 :         56 :                 LLVMValueRef frame_slice_ptr = ir_llvm_value(g, instruction->new_stack);
    3857         [ +  - ]:         56 :                 if (ir_want_runtime_safety(g, &instruction->base)) {
    3858                 :         56 :                     LLVMValueRef given_len_ptr = LLVMBuildStructGEP(g->builder, frame_slice_ptr, slice_len_index, "");
    3859                 :         56 :                     LLVMValueRef given_frame_len = LLVMBuildLoad(g->builder, given_len_ptr, "");
    3860                 :         56 :                     LLVMValueRef actual_frame_len = gen_frame_size(g, fn_val);
    3861                 :            : 
    3862                 :         56 :                     LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "FrameSizeCheckFail");
    3863                 :         56 :                     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "FrameSizeCheckOk");
    3864                 :            : 
    3865                 :         56 :                     LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntUGE, given_frame_len, actual_frame_len, "");
    3866                 :         56 :                     LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    3867                 :            : 
    3868                 :         56 :                     LLVMPositionBuilderAtEnd(g->builder, fail_block);
    3869                 :         56 :                     gen_safety_crash(g, PanicMsgIdFrameTooSmall);
    3870                 :            : 
    3871                 :         56 :                     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    3872                 :            :                 }
    3873                 :         56 :                 LLVMValueRef frame_ptr_ptr = LLVMBuildStructGEP(g->builder, frame_slice_ptr, slice_ptr_index, "");
    3874                 :         56 :                 LLVMValueRef frame_ptr = LLVMBuildLoad(g->builder, frame_ptr_ptr, "");
    3875         [ +  + ]:         56 :                 if (instruction->fn_entry == nullptr) {
    3876                 :         48 :                     ZigType *anyframe_type = get_any_frame_type(g, src_return_type);
    3877                 :         48 :                     frame_result_loc = LLVMBuildBitCast(g->builder, frame_ptr, get_llvm_type(g, anyframe_type), "");
    3878                 :            :                 } else {
    3879                 :          8 :                     ZigType *ptr_frame_type = get_pointer_to_type(g,
    3880                 :          8 :                             get_fn_frame_type(g, instruction->fn_entry), false);
    3881                 :          8 :                     frame_result_loc = LLVMBuildBitCast(g->builder, frame_ptr,
    3882                 :            :                             get_llvm_type(g, ptr_frame_type), "");
    3883                 :            :                 }
    3884                 :            :             }
    3885                 :            :         }
    3886         [ +  + ]:        856 :         if (instruction->is_async) {
    3887         [ +  + ]:        656 :             if (instruction->new_stack == nullptr) {
    3888                 :        592 :                 awaiter_init_val = zero;
    3889                 :            : 
    3890         [ +  + ]:        592 :                 if (ret_has_bits) {
    3891                 :            :                     // Use the result location which is inside the frame if this is an async call.
    3892                 :        248 :                     ret_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_ret_start + 2, "");
    3893                 :            :                 }
    3894                 :            :             } else {
    3895                 :         64 :                 awaiter_init_val = zero;
    3896                 :            : 
    3897         [ +  + ]:         64 :                 if (ret_has_bits) {
    3898         [ +  + ]:         56 :                     if (result_loc != nullptr) {
    3899                 :            :                         // Use the result location provided to the @asyncCall builtin
    3900                 :         48 :                         ret_ptr = result_loc;
    3901                 :            :                     } else {
    3902                 :            :                         // no result location provided to @asyncCall - use the one inside the frame.
    3903                 :         56 :                         ret_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_ret_start + 2, "");
    3904                 :            :                     }
    3905                 :            :                 }
    3906                 :            :             }
    3907                 :            : 
    3908                 :            :             // even if prefix_arg_err_ret_stack is true, let the async function do its own
    3909                 :            :             // initialization.
    3910                 :            :         } else {
    3911                 :            :             // async function called as a normal function
    3912                 :            : 
    3913                 :        200 :             awaiter_init_val = LLVMBuildPtrToInt(g->builder, g->cur_frame_ptr, usize_type_ref, ""); // caller's own frame pointer
    3914         [ +  + ]:        200 :             if (ret_has_bits) {
    3915         [ +  + ]:        168 :                 if (result_loc == nullptr) {
    3916                 :            :                     // return type is a scalar, but we still need a pointer to it. Use the async fn frame.
    3917                 :        120 :                     ret_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_ret_start + 2, "");
    3918                 :            :                 } else {
    3919                 :            :                     // Use the call instruction's result location.
    3920                 :         48 :                     ret_ptr = result_loc;
    3921                 :            :                 }
    3922                 :            : 
    3923                 :            :                 // Store a zero in the awaiter's result ptr to indicate we do not need a copy made.
    3924                 :        168 :                 LLVMValueRef awaiter_ret_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_ret_start + 1, "");
    3925                 :        168 :                 LLVMValueRef zero_ptr = LLVMConstNull(LLVMGetElementType(LLVMTypeOf(awaiter_ret_ptr)));
    3926                 :        168 :                 LLVMBuildStore(g->builder, zero_ptr, awaiter_ret_ptr);
    3927                 :            :             }
    3928                 :            : 
    3929         [ +  + ]:        200 :             if (prefix_arg_err_ret_stack) {
    3930                 :        120 :                 LLVMValueRef err_ret_trace_ptr_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc,
    3931                 :        120 :                         frame_index_trace_arg(g, src_return_type) + 1, "");
    3932                 :        120 :                 LLVMValueRef my_err_ret_trace_val = get_cur_err_ret_trace_val(g, instruction->base.scope);
    3933                 :        120 :                 LLVMBuildStore(g->builder, my_err_ret_trace_val, err_ret_trace_ptr_ptr);
    3934                 :            :             }
    3935                 :            :         }
    3936                 :            : 
    3937                 :        856 :         assert(frame_result_loc != nullptr);
    3938                 :            : 
    3939                 :        856 :         LLVMValueRef fn_ptr_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_fn_ptr_index, "");
    3940                 :        856 :         LLVMValueRef bitcasted_fn_val = LLVMBuildBitCast(g->builder, fn_val,
    3941                 :        856 :                 LLVMGetElementType(LLVMTypeOf(fn_ptr_ptr)), "");
    3942                 :        856 :         LLVMBuildStore(g->builder, bitcasted_fn_val, fn_ptr_ptr);
    3943                 :            : 
    3944                 :        856 :         LLVMValueRef resume_index_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_resume_index, "");
    3945                 :        856 :         LLVMBuildStore(g->builder, zero, resume_index_ptr);
    3946                 :            : 
    3947                 :        856 :         LLVMValueRef awaiter_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_awaiter_index, "");
    3948                 :        856 :         LLVMBuildStore(g->builder, awaiter_init_val, awaiter_ptr);
    3949                 :            : 
    3950         [ +  + ]:        856 :         if (ret_has_bits) {
    3951                 :        472 :             LLVMValueRef ret_ptr_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_ret_start, "");
    3952                 :        856 :             LLVMBuildStore(g->builder, ret_ptr, ret_ptr_ptr);
    3953                 :            :         }
    3954         [ +  + ]:      44859 :     } else if (instruction->is_async) {
    3955                 :            :         // Async call of blocking function
    3956         [ -  + ]:        200 :         if (instruction->new_stack != nullptr) {
    3957                 :          0 :             zig_panic("TODO @asyncCall of non-async function");
    3958                 :            :         }
    3959                 :        200 :         frame_result_loc = result_loc;
    3960                 :        200 :         awaiter_init_val = LLVMConstAllOnes(usize_type_ref);
    3961                 :            : 
    3962                 :        200 :         LLVMValueRef awaiter_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_awaiter_index, "");
    3963                 :        200 :         LLVMBuildStore(g->builder, awaiter_init_val, awaiter_ptr);
    3964                 :            : 
    3965         [ +  + ]:        200 :         if (ret_has_bits) {
    3966                 :        152 :             ret_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_ret_start + 2, "");
    3967                 :        152 :             LLVMValueRef ret_ptr_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_ret_start, "");
    3968                 :        152 :             LLVMBuildStore(g->builder, ret_ptr, ret_ptr_ptr);
    3969                 :            : 
    3970         [ +  + ]:        152 :             if (first_arg_ret) {
    3971                 :        144 :                 gen_param_values.append(ret_ptr);
    3972                 :            :             }
    3973         [ +  + ]:        152 :             if (prefix_arg_err_ret_stack) {
    3974                 :            :                 // Set up the callee stack trace pointer pointing into the frame.
    3975                 :            :                 // Then we have to wire up the StackTrace pointers.
    3976                 :            :                 // Await is responsible for merging error return traces.
    3977                 :        144 :                 uint32_t trace_field_index_start = frame_index_trace_arg(g, src_return_type);
    3978                 :        144 :                 LLVMValueRef callee_trace_ptr_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc,
    3979                 :        144 :                         trace_field_index_start, "");
    3980                 :        144 :                 LLVMValueRef trace_field_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc,
    3981                 :        144 :                         trace_field_index_start + 2, "");
    3982                 :        144 :                 LLVMValueRef addrs_field_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc,
    3983                 :        144 :                         trace_field_index_start + 3, "");
    3984                 :            : 
    3985                 :        144 :                 LLVMBuildStore(g->builder, trace_field_ptr, callee_trace_ptr_ptr);
    3986                 :            : 
    3987                 :        144 :                 gen_init_stack_trace(g, trace_field_ptr, addrs_field_ptr);
    3988                 :            : 
    3989                 :        200 :                 gen_param_values.append(get_cur_err_ret_trace_val(g, instruction->base.scope));
    3990                 :            :             }
    3991                 :            :         }
    3992                 :            :     } else {
    3993         [ +  + ]:      44659 :         if (first_arg_ret) {
    3994                 :       6585 :             gen_param_values.append(result_loc);
    3995                 :            :         }
    3996         [ +  + ]:      44659 :         if (prefix_arg_err_ret_stack) {
    3997                 :      10262 :             gen_param_values.append(get_cur_err_ret_trace_val(g, instruction->base.scope));
    3998                 :            :         }
    3999                 :            :     }
    4000                 :      45715 :     FnWalk fn_walk = {};
    4001                 :      45715 :     fn_walk.id = FnWalkIdCall;
    4002                 :      45715 :     fn_walk.data.call.inst = instruction;
    4003                 :      45715 :     fn_walk.data.call.is_var_args = is_var_args;
    4004                 :      45715 :     fn_walk.data.call.gen_param_values = &gen_param_values;
    4005                 :      45715 :     fn_walk.data.call.gen_param_types = &gen_param_types;
    4006                 :      45715 :     walk_function_params(g, fn_type, &fn_walk);
    4007                 :            : 
    4008                 :            :     ZigLLVM_FnInline fn_inline;
    4009   [ +  +  +  - ]:      45715 :     switch (instruction->fn_inline) {
    4010                 :      45647 :         case FnInlineAuto:
    4011                 :      45647 :             fn_inline = ZigLLVM_FnInlineAuto;
    4012                 :      45647 :             break;
    4013                 :         65 :         case FnInlineAlways:
    4014         [ -  + ]:         65 :             fn_inline = (instruction->fn_entry == nullptr) ? ZigLLVM_FnInlineAuto : ZigLLVM_FnInlineAlways;
    4015                 :         65 :             break;
    4016                 :          3 :         case FnInlineNever:
    4017                 :          3 :             fn_inline = ZigLLVM_FnInlineNever;
    4018                 :          3 :             break;
    4019                 :            :     }
    4020                 :            : 
    4021                 :      45715 :     LLVMCallConv llvm_cc = get_llvm_cc(g, cc);
    4022                 :            :     LLVMValueRef result;
    4023                 :            : 
    4024         [ +  + ]:      45715 :     if (callee_is_async) {
    4025                 :        856 :         uint32_t arg_start_i = frame_index_arg(g, fn_type->data.fn.fn_type_id.return_type);
    4026                 :            : 
    4027                 :            :         LLVMValueRef casted_frame;
    4028 [ +  + ][ +  + ]:        856 :         if (instruction->new_stack != nullptr && instruction->fn_entry == nullptr) {
    4029                 :            :             // We need the frame type to be a pointer to a struct that includes the args
    4030                 :         48 :             size_t field_count = arg_start_i + gen_param_values.length;
    4031                 :         48 :             LLVMTypeRef *field_types = allocate_nonzero<LLVMTypeRef>(field_count);
    4032                 :         48 :             LLVMGetStructElementTypes(LLVMGetElementType(LLVMTypeOf(frame_result_loc)), field_types);
    4033                 :         48 :             assert(LLVMCountStructElementTypes(LLVMGetElementType(LLVMTypeOf(frame_result_loc))) == arg_start_i);
    4034         [ +  + ]:         64 :             for (size_t arg_i = 0; arg_i < gen_param_values.length; arg_i += 1) {
    4035                 :         16 :                 field_types[arg_start_i + arg_i] = LLVMTypeOf(gen_param_values.at(arg_i));
    4036                 :            :             }
    4037                 :         48 :             LLVMTypeRef frame_with_args_type = LLVMStructType(field_types, field_count, false);
    4038                 :         48 :             LLVMTypeRef ptr_frame_with_args_type = LLVMPointerType(frame_with_args_type, 0);
    4039                 :            : 
    4040                 :         48 :             casted_frame = LLVMBuildBitCast(g->builder, frame_result_loc, ptr_frame_with_args_type, "");
    4041                 :            :         } else {
    4042                 :        808 :             casted_frame = frame_result_loc;
    4043                 :            :         }
    4044                 :            : 
    4045         [ +  + ]:       1384 :         for (size_t arg_i = 0; arg_i < gen_param_values.length; arg_i += 1) {
    4046                 :        528 :             LLVMValueRef arg_ptr = LLVMBuildStructGEP(g->builder, casted_frame, arg_start_i + arg_i, "");
    4047                 :        528 :             gen_assign_raw(g, arg_ptr, get_pointer_to_type(g, gen_param_types.at(arg_i), true),
    4048                 :        528 :                     gen_param_values.at(arg_i));
    4049                 :            :         }
    4050                 :            : 
    4051         [ +  + ]:        856 :         if (instruction->is_async) {
    4052                 :        656 :             gen_resume(g, fn_val, frame_result_loc, ResumeIdCall);
    4053         [ +  + ]:        656 :             if (instruction->new_stack != nullptr) {
    4054                 :         64 :                 return LLVMBuildBitCast(g->builder, frame_result_loc,
    4055                 :         64 :                         get_llvm_type(g, instruction->base.value.type), "");
    4056                 :            :             }
    4057                 :        592 :             return nullptr;
    4058                 :            :         } else {
    4059                 :        200 :             ZigType *ptr_result_type = get_pointer_to_type(g, src_return_type, true);
    4060                 :            : 
    4061                 :        200 :             LLVMBasicBlockRef call_bb = gen_suspend_begin(g, "CallResume");
    4062                 :            : 
    4063                 :        200 :             LLVMValueRef call_inst = gen_resume(g, fn_val, frame_result_loc, ResumeIdCall);
    4064                 :        200 :             set_tail_call_if_appropriate(g, call_inst);
    4065                 :        200 :             LLVMBuildRetVoid(g->builder);
    4066                 :            : 
    4067                 :        200 :             LLVMPositionBuilderAtEnd(g->builder, call_bb);
    4068                 :        200 :             gen_assert_resume_id(g, &instruction->base, ResumeIdReturn, PanicMsgIdResumedAnAwaitingFn, nullptr);
    4069                 :        200 :             render_async_var_decls(g, instruction->base.scope);
    4070                 :            : 
    4071         [ +  + ]:        200 :             if (!type_has_bits(src_return_type))
    4072                 :         32 :                 return nullptr;
    4073                 :            : 
    4074         [ +  + ]:        168 :             if (result_loc != nullptr) 
    4075                 :         48 :                 return get_handle_value(g, result_loc, src_return_type, ptr_result_type);
    4076                 :            : 
    4077                 :        120 :             LLVMValueRef result_ptr = LLVMBuildStructGEP(g->builder, frame_result_loc, frame_ret_start + 2, "");
    4078                 :        120 :             return LLVMBuildLoad(g->builder, result_ptr, "");
    4079                 :            :         }
    4080                 :            :     }
    4081                 :            : 
    4082 [ +  + ][ -  + ]:      44859 :     if (instruction->new_stack == nullptr || instruction->is_async_call_builtin) {
    4083                 :      44843 :         result = ZigLLVMBuildCall(g->builder, fn_val,
    4084                 :      44843 :                 gen_param_values.items, (unsigned)gen_param_values.length, llvm_cc, fn_inline, "");
    4085         [ -  + ]:         16 :     } else if (instruction->is_async) {
    4086                 :          0 :         zig_panic("TODO @asyncCall of non-async function");
    4087                 :            :     } else {
    4088                 :         16 :         LLVMValueRef stacksave_fn_val = get_stacksave_fn_val(g);
    4089                 :         16 :         LLVMValueRef stackrestore_fn_val = get_stackrestore_fn_val(g);
    4090                 :            : 
    4091                 :         16 :         LLVMValueRef new_stack_addr = get_new_stack_addr(g, ir_llvm_value(g, instruction->new_stack));
    4092                 :         16 :         LLVMValueRef old_stack_ref = LLVMBuildCall(g->builder, stacksave_fn_val, nullptr, 0, "");
    4093                 :         16 :         gen_set_stack_pointer(g, new_stack_addr);
    4094                 :         16 :         result = ZigLLVMBuildCall(g->builder, fn_val,
    4095                 :         16 :                 gen_param_values.items, (unsigned)gen_param_values.length, llvm_cc, fn_inline, "");
    4096                 :         16 :         LLVMBuildCall(g->builder, stackrestore_fn_val, &old_stack_ref, 1, "");
    4097                 :            :     }
    4098                 :            : 
    4099         [ +  + ]:      44859 :     if (src_return_type->id == ZigTypeIdUnreachable) {
    4100                 :        984 :         return LLVMBuildUnreachable(g->builder);
    4101         [ +  + ]:      43875 :     } else if (!ret_has_bits) {
    4102                 :      23081 :         return nullptr;
    4103         [ +  + ]:      20794 :     } else if (first_arg_ret) {
    4104                 :       6729 :         set_call_instr_sret(g, result);
    4105                 :       6729 :         return result_loc;
    4106         [ +  + ]:      14065 :     } else if (handle_is_ptr(src_return_type)) {
    4107                 :          8 :         LLVMValueRef store_instr = LLVMBuildStore(g->builder, result, result_loc);
    4108                 :          8 :         LLVMSetAlignment(store_instr, get_ptr_align(g, instruction->result_loc->value.type));
    4109                 :          8 :         return result_loc;
    4110 [ +  - ][ +  + ]:      14057 :     } else if (!callee_is_async && instruction->is_async) {
    4111                 :          8 :         LLVMBuildStore(g->builder, result, ret_ptr);
    4112                 :          8 :         return result_loc;
    4113                 :            :     } else {
    4114                 :      45715 :         return result;
    4115                 :            :     }
    4116                 :            : }
    4117                 :            : 
    4118                 :      22444 : static LLVMValueRef ir_render_struct_field_ptr(CodeGen *g, IrExecutable *executable,
    4119                 :            :     IrInstructionStructFieldPtr *instruction)
    4120                 :            : {
    4121                 :            :     Error err;
    4122                 :            : 
    4123         [ +  + ]:      22444 :     if (instruction->base.value.special != ConstValSpecialRuntime)
    4124                 :         62 :         return nullptr;
    4125                 :            : 
    4126                 :      22382 :     LLVMValueRef struct_ptr = ir_llvm_value(g, instruction->struct_ptr);
    4127                 :            :     // not necessarily a pointer. could be ZigTypeIdStruct
    4128                 :      22382 :     ZigType *struct_ptr_type = instruction->struct_ptr->value.type;
    4129                 :      22382 :     TypeStructField *field = instruction->field;
    4130                 :            : 
    4131         [ -  + ]:      22382 :     if (!type_has_bits(field->type_entry))
    4132                 :          0 :         return nullptr;
    4133                 :            : 
    4134 [ +  - ][ -  + ]:      22382 :     if (struct_ptr_type->id == ZigTypeIdPointer &&
    4135                 :      22382 :         struct_ptr_type->data.pointer.host_int_bytes != 0)
    4136                 :            :     {
    4137                 :          0 :         return struct_ptr;
    4138                 :            :     }
    4139                 :            : 
    4140         [ +  - ]:      22382 :     ZigType *struct_type = (struct_ptr_type->id == ZigTypeIdPointer) ?
    4141                 :            :         struct_ptr_type->data.pointer.child_type : struct_ptr_type;
    4142         [ -  + ]:      22382 :     if ((err = type_resolve(g, struct_type, ResolveStatusLLVMFull)))
    4143                 :          0 :         report_errors_and_exit(g);
    4144                 :            : 
    4145                 :      22382 :     assert(field->gen_index != SIZE_MAX);
    4146                 :      22382 :     return LLVMBuildStructGEP(g->builder, struct_ptr, (unsigned)field->gen_index, "");
    4147                 :            : }
    4148                 :            : 
    4149                 :       1462 : static LLVMValueRef ir_render_union_field_ptr(CodeGen *g, IrExecutable *executable,
    4150                 :            :     IrInstructionUnionFieldPtr *instruction)
    4151                 :            : {
    4152         [ +  + ]:       1462 :     if (instruction->base.value.special != ConstValSpecialRuntime)
    4153                 :        489 :         return nullptr;
    4154                 :            : 
    4155                 :        973 :     ZigType *union_ptr_type = instruction->union_ptr->value.type;
    4156                 :        973 :     assert(union_ptr_type->id == ZigTypeIdPointer);
    4157                 :        973 :     ZigType *union_type = union_ptr_type->data.pointer.child_type;
    4158                 :        973 :     assert(union_type->id == ZigTypeIdUnion);
    4159                 :            : 
    4160                 :        973 :     TypeUnionField *field = instruction->field;
    4161                 :            : 
    4162         [ +  + ]:        973 :     if (!type_has_bits(field->type_entry)) {
    4163         [ -  + ]:         25 :         if (union_type->data.unionation.gen_tag_index == SIZE_MAX) {
    4164                 :          0 :             return nullptr;
    4165                 :            :         }
    4166         [ +  + ]:         25 :         if (instruction->initializing) {
    4167                 :         17 :             LLVMValueRef union_ptr = ir_llvm_value(g, instruction->union_ptr);
    4168                 :         17 :             LLVMValueRef tag_field_ptr = LLVMBuildStructGEP(g->builder, union_ptr,
    4169                 :         17 :                     union_type->data.unionation.gen_tag_index, "");
    4170                 :         17 :             LLVMValueRef tag_value = bigint_to_llvm_const(get_llvm_type(g, union_type->data.unionation.tag_type),
    4171                 :         17 :                     &field->enum_field->value);
    4172                 :         17 :             gen_store_untyped(g, tag_value, tag_field_ptr, 0, false);
    4173                 :            :         }
    4174                 :         25 :         return nullptr;
    4175                 :            :     }
    4176                 :            : 
    4177                 :        948 :     LLVMValueRef union_ptr = ir_llvm_value(g, instruction->union_ptr);
    4178                 :        948 :     LLVMTypeRef field_type_ref = LLVMPointerType(get_llvm_type(g, field->type_entry), 0);
    4179                 :            : 
    4180         [ +  + ]:        948 :     if (union_type->data.unionation.gen_tag_index == SIZE_MAX) {
    4181                 :        393 :         LLVMValueRef union_field_ptr = LLVMBuildStructGEP(g->builder, union_ptr, 0, "");
    4182                 :        393 :         LLVMValueRef bitcasted_union_field_ptr = LLVMBuildBitCast(g->builder, union_field_ptr, field_type_ref, "");
    4183                 :        393 :         return bitcasted_union_field_ptr;
    4184                 :            :     }
    4185                 :            : 
    4186         [ +  + ]:        555 :     if (instruction->initializing) {
    4187                 :        177 :         LLVMValueRef tag_field_ptr = LLVMBuildStructGEP(g->builder, union_ptr, union_type->data.unionation.gen_tag_index, "");
    4188                 :        177 :         LLVMValueRef tag_value = bigint_to_llvm_const(get_llvm_type(g, union_type->data.unionation.tag_type),
    4189                 :        177 :                 &field->enum_field->value);
    4190                 :        177 :         gen_store_untyped(g, tag_value, tag_field_ptr, 0, false);
    4191 [ +  + ][ +  - ]:        378 :     } else if (instruction->safety_check_on && ir_want_runtime_safety(g, &instruction->base)) {
                 [ +  + ]
    4192                 :        130 :         LLVMValueRef tag_field_ptr = LLVMBuildStructGEP(g->builder, union_ptr, union_type->data.unionation.gen_tag_index, "");
    4193                 :        130 :         LLVMValueRef tag_value = gen_load_untyped(g, tag_field_ptr, 0, false, "");
    4194                 :            : 
    4195                 :            : 
    4196                 :        130 :         LLVMValueRef expected_tag_value = bigint_to_llvm_const(get_llvm_type(g, union_type->data.unionation.tag_type),
    4197                 :        130 :                 &field->enum_field->value);
    4198                 :        130 :         LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnionCheckOk");
    4199                 :        130 :         LLVMBasicBlockRef bad_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnionCheckFail");
    4200                 :        130 :         LLVMValueRef ok_val = LLVMBuildICmp(g->builder, LLVMIntEQ, tag_value, expected_tag_value, "");
    4201                 :        130 :         LLVMBuildCondBr(g->builder, ok_val, ok_block, bad_block);
    4202                 :            : 
    4203                 :        130 :         LLVMPositionBuilderAtEnd(g->builder, bad_block);
    4204                 :        130 :         gen_safety_crash(g, PanicMsgIdBadUnionField);
    4205                 :            : 
    4206                 :        130 :         LLVMPositionBuilderAtEnd(g->builder, ok_block);
    4207                 :            :     }
    4208                 :            : 
    4209                 :        555 :     LLVMValueRef union_field_ptr = LLVMBuildStructGEP(g->builder, union_ptr,
    4210                 :        555 :             union_type->data.unionation.gen_union_index, "");
    4211                 :        555 :     LLVMValueRef bitcasted_union_field_ptr = LLVMBuildBitCast(g->builder, union_field_ptr, field_type_ref, "");
    4212                 :        555 :     return bitcasted_union_field_ptr;
    4213                 :            : }
    4214                 :            : 
    4215                 :          0 : static size_t find_asm_index(CodeGen *g, AstNode *node, AsmToken *tok, Buf *src_template) {
    4216                 :          0 :     const char *ptr = buf_ptr(src_template) + tok->start + 2;
    4217                 :          0 :     size_t len = tok->end - tok->start - 2;
    4218                 :          0 :     size_t result = 0;
    4219         [ #  # ]:          0 :     for (size_t i = 0; i < node->data.asm_expr.output_list.length; i += 1, result += 1) {
    4220                 :          0 :         AsmOutput *asm_output = node->data.asm_expr.output_list.at(i);
    4221         [ #  # ]:          0 :         if (buf_eql_mem(asm_output->asm_symbolic_name, ptr, len)) {
    4222                 :          0 :             return result;
    4223                 :            :         }
    4224                 :            :     }
    4225         [ #  # ]:          0 :     for (size_t i = 0; i < node->data.asm_expr.input_list.length; i += 1, result += 1) {
    4226                 :          0 :         AsmInput *asm_input = node->data.asm_expr.input_list.at(i);
    4227         [ #  # ]:          0 :         if (buf_eql_mem(asm_input->asm_symbolic_name, ptr, len)) {
    4228                 :          0 :             return result;
    4229                 :            :         }
    4230                 :            :     }
    4231                 :          0 :     return SIZE_MAX;
    4232                 :            : }
    4233                 :            : 
    4234                 :        121 : static LLVMValueRef ir_render_asm(CodeGen *g, IrExecutable *executable, IrInstructionAsm *instruction) {
    4235                 :        121 :     AstNode *asm_node = instruction->base.source_node;
    4236                 :        121 :     assert(asm_node->type == NodeTypeAsmExpr);
    4237                 :        121 :     AstNodeAsmExpr *asm_expr = &asm_node->data.asm_expr;
    4238                 :            : 
    4239                 :        121 :     Buf *src_template = instruction->asm_template;
    4240                 :            : 
    4241                 :        121 :     Buf llvm_template = BUF_INIT;
    4242                 :        121 :     buf_resize(&llvm_template, 0);
    4243                 :            : 
    4244         [ +  + ]:        399 :     for (size_t token_i = 0; token_i < instruction->token_list_len; token_i += 1) {
    4245                 :        278 :         AsmToken *asm_token = &instruction->token_list[token_i];
    4246   [ +  +  -  -  :        278 :         switch (asm_token->id) {
                      - ]
    4247                 :        154 :             case AsmTokenIdTemplate:
    4248         [ +  + ]:       2788 :                 for (size_t offset = asm_token->start; offset < asm_token->end; offset += 1) {
    4249                 :       2634 :                     uint8_t c = *((uint8_t*)(buf_ptr(src_template) + offset));
    4250         [ +  + ]:       2634 :                     if (c == '$') {
    4251                 :         36 :                         buf_append_str(&llvm_template, "$$");
    4252                 :            :                     } else {
    4253                 :       2598 :                         buf_append_char(&llvm_template, c);
    4254                 :            :                     }
    4255                 :            :                 }
    4256                 :        154 :                 break;
    4257                 :        124 :             case AsmTokenIdPercent:
    4258                 :        124 :                 buf_append_char(&llvm_template, '%');
    4259                 :        124 :                 break;
    4260                 :          0 :             case AsmTokenIdVar:
    4261                 :            :                 {
    4262                 :          0 :                     size_t index = find_asm_index(g, asm_node, asm_token, src_template);
    4263                 :          0 :                     assert(index < SIZE_MAX);
    4264                 :          0 :                     buf_appendf(&llvm_template, "$%" ZIG_PRI_usize "", index);
    4265                 :          0 :                     break;
    4266                 :            :                 }
    4267                 :          0 :             case AsmTokenIdUniqueId:
    4268                 :          0 :                 buf_append_str(&llvm_template, "${:uid}");
    4269                 :          0 :                 break;
    4270                 :            :         }
    4271                 :            :     }
    4272                 :            : 
    4273                 :        121 :     Buf constraint_buf = BUF_INIT;
    4274                 :        121 :     buf_resize(&constraint_buf, 0);
    4275                 :            : 
    4276 [ +  - ][ +  + ]:        121 :     assert(instruction->return_count == 0 || instruction->return_count == 1);
    4277                 :            : 
    4278                 :        363 :     size_t total_constraint_count = asm_expr->output_list.length +
    4279                 :        121 :                                  asm_expr->input_list.length +
    4280                 :        121 :                                  asm_expr->clobber_list.length;
    4281                 :        363 :     size_t input_and_output_count = asm_expr->output_list.length +
    4282                 :        121 :                                  asm_expr->input_list.length -
    4283                 :        121 :                                  instruction->return_count;
    4284                 :        121 :     size_t total_index = 0;
    4285                 :        121 :     size_t param_index = 0;
    4286                 :        121 :     LLVMTypeRef *param_types = allocate<LLVMTypeRef>(input_and_output_count);
    4287                 :        121 :     LLVMValueRef *param_values = allocate<LLVMValueRef>(input_and_output_count);
    4288         [ +  + ]:        168 :     for (size_t i = 0; i < asm_expr->output_list.length; i += 1, total_index += 1) {
    4289                 :         47 :         AsmOutput *asm_output = asm_expr->output_list.at(i);
    4290                 :         47 :         bool is_return = (asm_output->return_type != nullptr);
    4291                 :         47 :         assert(*buf_ptr(asm_output->constraint) == '=');
    4292                 :            :         // LLVM uses commas internally to separate different constraints,
    4293                 :            :         // alternative constraints are achieved with pipes.
    4294                 :            :         // We still allow the user to use commas in a way that is similar
    4295                 :            :         // to GCC's inline assembly.
    4296                 :            :         // http://llvm.org/docs/LangRef.html#constraint-codes
    4297                 :         47 :         buf_replace(asm_output->constraint, ',', '|');
    4298                 :            : 
    4299         [ +  + ]:         47 :         if (is_return) {
    4300                 :         23 :             buf_appendf(&constraint_buf, "=%s", buf_ptr(asm_output->constraint) + 1);
    4301                 :            :         } else {
    4302                 :         24 :             buf_appendf(&constraint_buf, "=*%s", buf_ptr(asm_output->constraint) + 1);
    4303                 :            :         }
    4304         [ +  + ]:         47 :         if (total_index + 1 < total_constraint_count) {
    4305                 :         44 :             buf_append_char(&constraint_buf, ',');
    4306                 :            :         }
    4307                 :            : 
    4308         [ +  + ]:         47 :         if (!is_return) {
    4309                 :         24 :             ZigVar *variable = instruction->output_vars[i];
    4310                 :         24 :             assert(variable);
    4311                 :         24 :             param_types[param_index] = LLVMTypeOf(variable->value_ref);
    4312                 :         24 :             param_values[param_index] = variable->value_ref;
    4313                 :         24 :             param_index += 1;
    4314                 :            :         }
    4315                 :            :     }
    4316         [ +  + ]:        271 :     for (size_t i = 0; i < asm_expr->input_list.length; i += 1, total_index += 1, param_index += 1) {
    4317                 :        150 :         AsmInput *asm_input = asm_expr->input_list.at(i);
    4318                 :        150 :         buf_replace(asm_input->constraint, ',', '|');
    4319                 :        150 :         IrInstruction *ir_input = instruction->input_list[i];
    4320                 :        150 :         buf_append_buf(&constraint_buf, asm_input->constraint);
    4321         [ +  - ]:        150 :         if (total_index + 1 < total_constraint_count) {
    4322                 :        150 :             buf_append_char(&constraint_buf, ',');
    4323                 :            :         }
    4324                 :            : 
    4325                 :        150 :         ZigType *const type = ir_input->value.type;
    4326                 :        150 :         LLVMTypeRef type_ref = get_llvm_type(g, type);
    4327                 :        150 :         LLVMValueRef value_ref = ir_llvm_value(g, ir_input);
    4328                 :            :         // Handle integers of non pot bitsize by widening them.
    4329         [ +  + ]:        150 :         if (type->id == ZigTypeIdInt) {
    4330                 :        134 :             const size_t bitsize = type->data.integral.bit_count;
    4331 [ +  + ][ +  + ]:        134 :             if (bitsize < 8 || !is_power_of_2(bitsize)) {
                 [ +  + ]
    4332                 :         40 :                 const bool is_signed = type->data.integral.is_signed;
    4333         [ +  + ]:         40 :                 const size_t wider_bitsize = bitsize < 8 ? 8 : round_to_next_power_of_2(bitsize);
    4334                 :         40 :                 ZigType *const wider_type = get_int_type(g, is_signed, wider_bitsize);
    4335                 :         40 :                 type_ref = get_llvm_type(g, wider_type);
    4336                 :        134 :                 value_ref = gen_widen_or_shorten(g, false, type, wider_type, value_ref);
    4337                 :            :             }
    4338                 :            :         }
    4339                 :            : 
    4340                 :        150 :         param_types[param_index] = type_ref;
    4341                 :        150 :         param_values[param_index] = value_ref;
    4342                 :            :     }
    4343         [ +  + ]:        255 :     for (size_t i = 0; i < asm_expr->clobber_list.length; i += 1, total_index += 1) {
    4344                 :        134 :         Buf *clobber_buf = asm_expr->clobber_list.at(i);
    4345                 :        134 :         buf_appendf(&constraint_buf, "~{%s}", buf_ptr(clobber_buf));
    4346         [ +  + ]:        134 :         if (total_index + 1 < total_constraint_count) {
    4347                 :         23 :             buf_append_char(&constraint_buf, ',');
    4348                 :            :         }
    4349                 :            :     }
    4350                 :            : 
    4351                 :            :     LLVMTypeRef ret_type;
    4352         [ +  + ]:        121 :     if (instruction->return_count == 0) {
    4353                 :         98 :         ret_type = LLVMVoidType();
    4354                 :            :     } else {
    4355                 :         23 :         ret_type = get_llvm_type(g, instruction->base.value.type);
    4356                 :            :     }
    4357                 :        121 :     LLVMTypeRef function_type = LLVMFunctionType(ret_type, param_types, (unsigned)input_and_output_count, false);
    4358                 :            : 
    4359 [ -  + ][ +  + ]:        121 :     bool is_volatile = instruction->has_side_effects || (asm_expr->output_list.length == 0);
    4360                 :        121 :     LLVMValueRef asm_fn = LLVMGetInlineAsm(function_type, buf_ptr(&llvm_template), buf_len(&llvm_template),
    4361                 :        121 :             buf_ptr(&constraint_buf), buf_len(&constraint_buf), is_volatile, false, LLVMInlineAsmDialectATT);
    4362                 :            : 
    4363                 :        121 :     return LLVMBuildCall(g->builder, asm_fn, param_values, (unsigned)input_and_output_count, "");
    4364                 :            : }
    4365                 :            : 
    4366                 :       1663 : static LLVMValueRef gen_non_null_bit(CodeGen *g, ZigType *maybe_type, LLVMValueRef maybe_handle) {
    4367 [ +  + ][ +  - ]:       1759 :     assert(maybe_type->id == ZigTypeIdOptional ||
    4368         [ +  - ]:         96 :             (maybe_type->id == ZigTypeIdPointer && maybe_type->data.pointer.allow_zero));
    4369                 :            : 
    4370                 :       1663 :     ZigType *child_type = maybe_type->data.maybe.child_type;
    4371         [ +  + ]:       1663 :     if (!type_has_bits(child_type))
    4372                 :         64 :         return maybe_handle;
    4373                 :            : 
    4374                 :       1599 :     bool is_scalar = !handle_is_ptr(maybe_type);
    4375         [ +  + ]:       1599 :     if (is_scalar)
    4376                 :        810 :         return LLVMBuildICmp(g->builder, LLVMIntNE, maybe_handle, LLVMConstNull(get_llvm_type(g, maybe_type)), "");
    4377                 :            : 
    4378                 :        789 :     LLVMValueRef maybe_field_ptr = LLVMBuildStructGEP(g->builder, maybe_handle, maybe_null_index, "");
    4379                 :        789 :     return gen_load_untyped(g, maybe_field_ptr, 0, false, "");
    4380                 :            : }
    4381                 :            : 
    4382                 :       1383 : static LLVMValueRef ir_render_test_non_null(CodeGen *g, IrExecutable *executable,
    4383                 :            :     IrInstructionTestNonNull *instruction)
    4384                 :            : {
    4385                 :       1383 :     return gen_non_null_bit(g, instruction->value->value.type, ir_llvm_value(g, instruction->value));
    4386                 :            : }
    4387                 :            : 
    4388                 :       1757 : static LLVMValueRef ir_render_optional_unwrap_ptr(CodeGen *g, IrExecutable *executable,
    4389                 :            :         IrInstructionOptionalUnwrapPtr *instruction)
    4390                 :            : {
    4391         [ -  + ]:       1757 :     if (instruction->base.value.special != ConstValSpecialRuntime)
    4392                 :          0 :         return nullptr;
    4393                 :            : 
    4394                 :       1757 :     ZigType *ptr_type = instruction->base_ptr->value.type;
    4395                 :       1757 :     assert(ptr_type->id == ZigTypeIdPointer);
    4396                 :       1757 :     ZigType *maybe_type = ptr_type->data.pointer.child_type;
    4397                 :       1757 :     assert(maybe_type->id == ZigTypeIdOptional);
    4398                 :       1757 :     ZigType *child_type = maybe_type->data.maybe.child_type;
    4399                 :       1757 :     LLVMValueRef base_ptr = ir_llvm_value(g, instruction->base_ptr);
    4400 [ +  + ][ +  + ]:       1757 :     if (instruction->safety_check_on && ir_want_runtime_safety(g, &instruction->base)) {
                 [ +  + ]
    4401                 :        280 :         LLVMValueRef maybe_handle = get_handle_value(g, base_ptr, maybe_type, ptr_type);
    4402                 :        280 :         LLVMValueRef non_null_bit = gen_non_null_bit(g, maybe_type, maybe_handle);
    4403                 :        280 :         LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnwrapOptionalFail");
    4404                 :        280 :         LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnwrapOptionalOk");
    4405                 :        280 :         LLVMBuildCondBr(g->builder, non_null_bit, ok_block, fail_block);
    4406                 :            : 
    4407                 :        280 :         LLVMPositionBuilderAtEnd(g->builder, fail_block);
    4408                 :        280 :         gen_safety_crash(g, PanicMsgIdUnwrapOptionalFail);
    4409                 :            : 
    4410                 :        280 :         LLVMPositionBuilderAtEnd(g->builder, ok_block);
    4411                 :            :     }
    4412         [ +  + ]:       1757 :     if (!type_has_bits(child_type)) {
    4413                 :          8 :         return nullptr;
    4414                 :            :     } else {
    4415                 :       1749 :         bool is_scalar = !handle_is_ptr(maybe_type);
    4416         [ +  + ]:       1749 :         if (is_scalar) {
    4417                 :        774 :             return base_ptr;
    4418                 :            :         } else {
    4419                 :        975 :             LLVMValueRef optional_struct_ref = get_handle_value(g, base_ptr, maybe_type, ptr_type);
    4420         [ +  + ]:        975 :             if (instruction->initializing) {
    4421                 :        297 :                 LLVMValueRef non_null_bit_ptr = LLVMBuildStructGEP(g->builder, optional_struct_ref,
    4422                 :        297 :                         maybe_null_index, "");
    4423                 :        297 :                 LLVMValueRef non_null_bit = LLVMConstInt(LLVMInt1Type(), 1, false);
    4424                 :        297 :                 gen_store_untyped(g, non_null_bit, non_null_bit_ptr, 0, false);
    4425                 :            :             }
    4426                 :        975 :             return LLVMBuildStructGEP(g->builder, optional_struct_ref, maybe_child_index, "");
    4427                 :            :         }
    4428                 :            :     }
    4429                 :            : }
    4430                 :            : 
    4431                 :        427 : static LLVMValueRef get_int_builtin_fn(CodeGen *g, ZigType *int_type, BuiltinFnId fn_id) {
    4432                 :        427 :     ZigLLVMFnKey key = {};
    4433                 :            :     const char *fn_name;
    4434                 :            :     uint32_t n_args;
    4435         [ +  + ]:        427 :     if (fn_id == BuiltinFnIdCtz) {
    4436                 :         40 :         fn_name = "cttz";
    4437                 :         40 :         n_args = 2;
    4438                 :         40 :         key.id = ZigLLVMFnIdCtz;
    4439                 :         40 :         key.data.ctz.bit_count = (uint32_t)int_type->data.integral.bit_count;
    4440         [ +  + ]:        387 :     } else if (fn_id == BuiltinFnIdClz) {
    4441                 :        182 :         fn_name = "ctlz";
    4442                 :        182 :         n_args = 2;
    4443                 :        182 :         key.id = ZigLLVMFnIdClz;
    4444                 :        182 :         key.data.clz.bit_count = (uint32_t)int_type->data.integral.bit_count;
    4445         [ +  + ]:        205 :     } else if (fn_id == BuiltinFnIdPopCount) {
    4446                 :         65 :         fn_name = "ctpop";
    4447                 :         65 :         n_args = 1;
    4448                 :         65 :         key.id = ZigLLVMFnIdPopCount;
    4449                 :         65 :         key.data.pop_count.bit_count = (uint32_t)int_type->data.integral.bit_count;
    4450         [ +  + ]:        140 :     } else if (fn_id == BuiltinFnIdBswap) {
    4451                 :         28 :         fn_name = "bswap";
    4452                 :         28 :         n_args = 1;
    4453                 :         28 :         key.id = ZigLLVMFnIdBswap;
    4454                 :         28 :         key.data.bswap.bit_count = (uint32_t)int_type->data.integral.bit_count;
    4455         [ +  - ]:        112 :     } else if (fn_id == BuiltinFnIdBitReverse) {
    4456                 :        112 :         fn_name = "bitreverse";
    4457                 :        112 :         n_args = 1;
    4458                 :        112 :         key.id = ZigLLVMFnIdBitReverse;
    4459                 :        112 :         key.data.bit_reverse.bit_count = (uint32_t)int_type->data.integral.bit_count;
    4460                 :            :     } else {
    4461                 :          0 :         zig_unreachable();
    4462                 :            :     }
    4463                 :            : 
    4464                 :        427 :     auto existing_entry = g->llvm_fn_table.maybe_get(key);
    4465         [ +  + ]:        427 :     if (existing_entry)
    4466                 :        221 :         return existing_entry->value;
    4467                 :            : 
    4468                 :            :     char llvm_name[64];
    4469                 :        206 :     sprintf(llvm_name, "llvm.%s.i%" PRIu32, fn_name, int_type->data.integral.bit_count);
    4470                 :            :     LLVMTypeRef param_types[] = {
    4471                 :        206 :         get_llvm_type(g, int_type),
    4472                 :        206 :         LLVMInt1Type(),
    4473                 :        412 :     };
    4474                 :        206 :     LLVMTypeRef fn_type = LLVMFunctionType(get_llvm_type(g, int_type), param_types, n_args, false);
    4475                 :        206 :     LLVMValueRef fn_val = LLVMAddFunction(g->module, llvm_name, fn_type);
    4476                 :        206 :     assert(LLVMGetIntrinsicID(fn_val));
    4477                 :            : 
    4478                 :        206 :     g->llvm_fn_table.put(key, fn_val);
    4479                 :            : 
    4480                 :        427 :     return fn_val;
    4481                 :            : }
    4482                 :            : 
    4483                 :        182 : static LLVMValueRef ir_render_clz(CodeGen *g, IrExecutable *executable, IrInstructionClz *instruction) {
    4484                 :        182 :     ZigType *int_type = instruction->op->value.type;
    4485                 :        182 :     LLVMValueRef fn_val = get_int_builtin_fn(g, int_type, BuiltinFnIdClz);
    4486                 :        182 :     LLVMValueRef operand = ir_llvm_value(g, instruction->op);
    4487                 :            :     LLVMValueRef params[] {
    4488                 :            :         operand,
    4489                 :        182 :         LLVMConstNull(LLVMInt1Type()),
    4490                 :        364 :     };
    4491                 :        182 :     LLVMValueRef wrong_size_int = LLVMBuildCall(g->builder, fn_val, params, 2, "");
    4492                 :        182 :     return gen_widen_or_shorten(g, false, int_type, instruction->base.value.type, wrong_size_int);
    4493                 :            : }
    4494                 :            : 
    4495                 :         40 : static LLVMValueRef ir_render_ctz(CodeGen *g, IrExecutable *executable, IrInstructionCtz *instruction) {
    4496                 :         40 :     ZigType *int_type = instruction->op->value.type;
    4497                 :         40 :     LLVMValueRef fn_val = get_int_builtin_fn(g, int_type, BuiltinFnIdCtz);
    4498                 :         40 :     LLVMValueRef operand = ir_llvm_value(g, instruction->op);
    4499                 :            :     LLVMValueRef params[] {
    4500                 :            :         operand,
    4501                 :         40 :         LLVMConstNull(LLVMInt1Type()),
    4502                 :         80 :     };
    4503                 :         40 :     LLVMValueRef wrong_size_int = LLVMBuildCall(g->builder, fn_val, params, 2, "");
    4504                 :         40 :     return gen_widen_or_shorten(g, false, int_type, instruction->base.value.type, wrong_size_int);
    4505                 :            : }
    4506                 :            : 
    4507                 :         65 : static LLVMValueRef ir_render_pop_count(CodeGen *g, IrExecutable *executable, IrInstructionPopCount *instruction) {
    4508                 :         65 :     ZigType *int_type = instruction->op->value.type;
    4509                 :         65 :     LLVMValueRef fn_val = get_int_builtin_fn(g, int_type, BuiltinFnIdPopCount);
    4510                 :         65 :     LLVMValueRef operand = ir_llvm_value(g, instruction->op);
    4511                 :         65 :     LLVMValueRef wrong_size_int = LLVMBuildCall(g->builder, fn_val, &operand, 1, "");
    4512                 :         65 :     return gen_widen_or_shorten(g, false, int_type, instruction->base.value.type, wrong_size_int);
    4513                 :            : }
    4514                 :            : 
    4515                 :        898 : static LLVMValueRef ir_render_switch_br(CodeGen *g, IrExecutable *executable, IrInstructionSwitchBr *instruction) {
    4516                 :        898 :     LLVMValueRef target_value = ir_llvm_value(g, instruction->target_value);
    4517                 :        898 :     LLVMBasicBlockRef else_block = instruction->else_block->llvm_block;
    4518                 :        898 :     LLVMValueRef switch_instr = LLVMBuildSwitch(g->builder, target_value, else_block,
    4519                 :        898 :             (unsigned)instruction->case_count);
    4520         [ +  + ]:       3931 :     for (size_t i = 0; i < instruction->case_count; i += 1) {
    4521                 :       3033 :         IrInstructionSwitchBrCase *this_case = &instruction->cases[i];
    4522                 :       3033 :         LLVMAddCase(switch_instr, ir_llvm_value(g, this_case->value), this_case->block->llvm_block);
    4523                 :            :     }
    4524                 :        898 :     return nullptr;
    4525                 :            : }
    4526                 :            : 
    4527                 :       1446 : static LLVMValueRef ir_render_phi(CodeGen *g, IrExecutable *executable, IrInstructionPhi *instruction) {
    4528         [ -  + ]:       1446 :     if (!type_has_bits(instruction->base.value.type))
    4529                 :          0 :         return nullptr;
    4530                 :            : 
    4531                 :            :     LLVMTypeRef phi_type;
    4532         [ +  + ]:       1446 :     if (handle_is_ptr(instruction->base.value.type)) {
    4533                 :        168 :         phi_type = LLVMPointerType(get_llvm_type(g,instruction->base.value.type), 0);
    4534                 :            :     } else {
    4535                 :       1278 :         phi_type = get_llvm_type(g, instruction->base.value.type);
    4536                 :            :     }
    4537                 :            : 
    4538                 :       1446 :     LLVMValueRef phi = LLVMBuildPhi(g->builder, phi_type, "");
    4539                 :       1446 :     LLVMValueRef *incoming_values = allocate<LLVMValueRef>(instruction->incoming_count);
    4540                 :       1446 :     LLVMBasicBlockRef *incoming_blocks = allocate<LLVMBasicBlockRef>(instruction->incoming_count);
    4541         [ +  + ]:       4648 :     for (size_t i = 0; i < instruction->incoming_count; i += 1) {
    4542                 :       3202 :         incoming_values[i] = ir_llvm_value(g, instruction->incoming_values[i]);
    4543                 :       3202 :         incoming_blocks[i] = instruction->incoming_blocks[i]->llvm_exit_block;
    4544                 :            :     }
    4545                 :       1446 :     LLVMAddIncoming(phi, incoming_values, incoming_blocks, (unsigned)instruction->incoming_count);
    4546                 :       1446 :     return phi;
    4547                 :            : }
    4548                 :            : 
    4549                 :      10685 : static LLVMValueRef ir_render_ref(CodeGen *g, IrExecutable *executable, IrInstructionRefGen *instruction) {
    4550         [ -  + ]:      10685 :     if (!type_has_bits(instruction->base.value.type)) {
    4551                 :          0 :         return nullptr;
    4552                 :            :     }
    4553                 :      10685 :     LLVMValueRef value = ir_llvm_value(g, instruction->operand);
    4554         [ +  + ]:      10685 :     if (handle_is_ptr(instruction->operand->value.type)) {
    4555                 :       5941 :         return value;
    4556                 :            :     } else {
    4557                 :       4744 :         LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    4558                 :       4744 :         gen_store_untyped(g, value, result_loc, 0, false);
    4559                 :       4744 :         return result_loc;
    4560                 :            :     }
    4561                 :            : }
    4562                 :            : 
    4563                 :        335 : static LLVMValueRef ir_render_err_name(CodeGen *g, IrExecutable *executable, IrInstructionErrName *instruction) {
    4564                 :        335 :     assert(g->generate_error_name_table);
    4565                 :            : 
    4566         [ -  + ]:        335 :     if (g->errors_by_index.length == 1) {
    4567                 :          0 :         LLVMBuildUnreachable(g->builder);
    4568                 :          0 :         return nullptr;
    4569                 :            :     }
    4570                 :            : 
    4571                 :        335 :     LLVMValueRef err_val = ir_llvm_value(g, instruction->value);
    4572         [ +  - ]:        335 :     if (ir_want_runtime_safety(g, &instruction->base)) {
    4573                 :        335 :         LLVMValueRef zero = LLVMConstNull(LLVMTypeOf(err_val));
    4574                 :        335 :         LLVMValueRef end_val = LLVMConstInt(LLVMTypeOf(err_val), g->errors_by_index.length, false);
    4575                 :        335 :         add_bounds_check(g, err_val, LLVMIntNE, zero, LLVMIntULT, end_val);
    4576                 :            :     }
    4577                 :            : 
    4578                 :            :     LLVMValueRef indices[] = {
    4579                 :        335 :         LLVMConstNull(g->builtin_types.entry_usize->llvm_type),
    4580                 :            :         err_val,
    4581                 :        335 :     };
    4582                 :        335 :     return LLVMBuildInBoundsGEP(g->builder, g->err_name_table, indices, 2, "");
    4583                 :            : }
    4584                 :            : 
    4585                 :         36 : static LLVMValueRef get_enum_tag_name_function(CodeGen *g, ZigType *enum_type) {
    4586                 :         36 :     assert(enum_type->id == ZigTypeIdEnum);
    4587         [ +  + ]:         36 :     if (enum_type->data.enumeration.name_function)
    4588                 :         13 :         return enum_type->data.enumeration.name_function;
    4589                 :            : 
    4590                 :         23 :     ZigType *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, false, false,
    4591                 :         23 :             PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0, false);
    4592                 :         23 :     ZigType *u8_slice_type = get_slice_type(g, u8_ptr_type);
    4593                 :         23 :     ZigType *tag_int_type = enum_type->data.enumeration.tag_int_type;
    4594                 :            : 
    4595                 :         23 :     LLVMTypeRef tag_int_llvm_type = get_llvm_type(g, tag_int_type);
    4596                 :         23 :     LLVMTypeRef fn_type_ref = LLVMFunctionType(LLVMPointerType(get_llvm_type(g, u8_slice_type), 0),
    4597                 :         23 :             &tag_int_llvm_type, 1, false);
    4598                 :            : 
    4599                 :         23 :     Buf *fn_name = get_mangled_name(g, buf_sprintf("__zig_tag_name_%s", buf_ptr(&enum_type->name)), false);
    4600                 :         23 :     LLVMValueRef fn_val = LLVMAddFunction(g->module, buf_ptr(fn_name), fn_type_ref);
    4601                 :         23 :     LLVMSetLinkage(fn_val, LLVMInternalLinkage);
    4602                 :         23 :     LLVMSetFunctionCallConv(fn_val, get_llvm_cc(g, CallingConventionUnspecified));
    4603                 :         23 :     addLLVMFnAttr(fn_val, "nounwind");
    4604                 :         23 :     add_uwtable_attr(g, fn_val);
    4605         [ +  - ]:         23 :     if (codegen_have_frame_pointer(g)) {
    4606                 :         23 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim", "true");
    4607                 :         23 :         ZigLLVMAddFunctionAttr(fn_val, "no-frame-pointer-elim-non-leaf", nullptr);
    4608                 :            :     }
    4609                 :            : 
    4610                 :         23 :     LLVMBasicBlockRef prev_block = LLVMGetInsertBlock(g->builder);
    4611                 :         23 :     LLVMValueRef prev_debug_location = LLVMGetCurrentDebugLocation(g->builder);
    4612                 :         23 :     ZigFn *prev_cur_fn = g->cur_fn;
    4613                 :         23 :     LLVMValueRef prev_cur_fn_val = g->cur_fn_val;
    4614                 :            : 
    4615                 :         23 :     LLVMBasicBlockRef entry_block = LLVMAppendBasicBlock(fn_val, "Entry");
    4616                 :         23 :     LLVMPositionBuilderAtEnd(g->builder, entry_block);
    4617                 :         23 :     ZigLLVMClearCurrentDebugLocation(g->builder);
    4618                 :         23 :     g->cur_fn = nullptr;
    4619                 :         23 :     g->cur_fn_val = fn_val;
    4620                 :            : 
    4621                 :         23 :     size_t field_count = enum_type->data.enumeration.src_field_count;
    4622                 :         23 :     LLVMBasicBlockRef bad_value_block = LLVMAppendBasicBlock(g->cur_fn_val, "BadValue");
    4623                 :         23 :     LLVMValueRef tag_int_value = LLVMGetParam(fn_val, 0);
    4624                 :         23 :     LLVMValueRef switch_instr = LLVMBuildSwitch(g->builder, tag_int_value, bad_value_block, field_count);
    4625                 :            : 
    4626                 :            : 
    4627                 :         23 :     ZigType *usize = g->builtin_types.entry_usize;
    4628                 :            :     LLVMValueRef array_ptr_indices[] = {
    4629                 :         23 :         LLVMConstNull(usize->llvm_type),
    4630                 :         23 :         LLVMConstNull(usize->llvm_type),
    4631                 :         46 :     };
    4632                 :            : 
    4633         [ +  + ]:        205 :     for (size_t field_i = 0; field_i < field_count; field_i += 1) {
    4634                 :        182 :         Buf *name = enum_type->data.enumeration.fields[field_i].name;
    4635                 :        182 :         LLVMValueRef str_init = LLVMConstString(buf_ptr(name), (unsigned)buf_len(name), true);
    4636                 :        182 :         LLVMValueRef str_global = LLVMAddGlobal(g->module, LLVMTypeOf(str_init), "");
    4637                 :        182 :         LLVMSetInitializer(str_global, str_init);
    4638                 :        182 :         LLVMSetLinkage(str_global, LLVMPrivateLinkage);
    4639                 :        182 :         LLVMSetGlobalConstant(str_global, true);
    4640                 :        182 :         LLVMSetUnnamedAddr(str_global, true);
    4641                 :        182 :         LLVMSetAlignment(str_global, LLVMABIAlignmentOfType(g->target_data_ref, LLVMTypeOf(str_init)));
    4642                 :            : 
    4643                 :            :         LLVMValueRef fields[] = {
    4644                 :        182 :             LLVMConstGEP(str_global, array_ptr_indices, 2),
    4645                 :        182 :             LLVMConstInt(g->builtin_types.entry_usize->llvm_type, buf_len(name), false),
    4646                 :        364 :         };
    4647                 :        182 :         LLVMValueRef slice_init_value = LLVMConstNamedStruct(get_llvm_type(g, u8_slice_type), fields, 2);
    4648                 :            : 
    4649                 :        182 :         LLVMValueRef slice_global = LLVMAddGlobal(g->module, LLVMTypeOf(slice_init_value), "");
    4650                 :        182 :         LLVMSetInitializer(slice_global, slice_init_value);
    4651                 :        182 :         LLVMSetLinkage(slice_global, LLVMPrivateLinkage);
    4652                 :        182 :         LLVMSetGlobalConstant(slice_global, true);
    4653                 :        182 :         LLVMSetUnnamedAddr(slice_global, true);
    4654                 :        182 :         LLVMSetAlignment(slice_global, LLVMABIAlignmentOfType(g->target_data_ref, LLVMTypeOf(slice_init_value)));
    4655                 :            : 
    4656                 :        182 :         LLVMBasicBlockRef return_block = LLVMAppendBasicBlock(g->cur_fn_val, "Name");
    4657                 :        182 :         LLVMValueRef this_tag_int_value = bigint_to_llvm_const(get_llvm_type(g, tag_int_type),
    4658                 :        182 :                 &enum_type->data.enumeration.fields[field_i].value);
    4659                 :        182 :         LLVMAddCase(switch_instr, this_tag_int_value, return_block);
    4660                 :            : 
    4661                 :        182 :         LLVMPositionBuilderAtEnd(g->builder, return_block);
    4662                 :        182 :         LLVMBuildRet(g->builder, slice_global);
    4663                 :            :     }
    4664                 :            : 
    4665                 :         23 :     LLVMPositionBuilderAtEnd(g->builder, bad_value_block);
    4666 [ #  # ][ -  + ]:         23 :     if (g->build_mode == BuildModeDebug || g->build_mode == BuildModeSafeRelease) {
    4667                 :         23 :         gen_safety_crash(g, PanicMsgIdBadEnumValue);
    4668                 :            :     } else {
    4669                 :          0 :         LLVMBuildUnreachable(g->builder);
    4670                 :            :     }
    4671                 :            : 
    4672                 :         23 :     g->cur_fn = prev_cur_fn;
    4673                 :         23 :     g->cur_fn_val = prev_cur_fn_val;
    4674                 :         23 :     LLVMPositionBuilderAtEnd(g->builder, prev_block);
    4675         [ +  - ]:         23 :     if (!g->strip_debug_symbols) {
    4676                 :         23 :         LLVMSetCurrentDebugLocation(g->builder, prev_debug_location);
    4677                 :            :     }
    4678                 :            : 
    4679                 :         23 :     enum_type->data.enumeration.name_function = fn_val;
    4680                 :         36 :     return fn_val;
    4681                 :            : }
    4682                 :            : 
    4683                 :         36 : static LLVMValueRef ir_render_enum_tag_name(CodeGen *g, IrExecutable *executable,
    4684                 :            :         IrInstructionTagName *instruction)
    4685                 :            : {
    4686                 :         36 :     ZigType *enum_type = instruction->target->value.type;
    4687                 :         36 :     assert(enum_type->id == ZigTypeIdEnum);
    4688                 :            : 
    4689                 :         36 :     LLVMValueRef enum_name_function = get_enum_tag_name_function(g, enum_type);
    4690                 :            : 
    4691                 :         36 :     LLVMValueRef enum_tag_value = ir_llvm_value(g, instruction->target);
    4692                 :         36 :     return ZigLLVMBuildCall(g->builder, enum_name_function, &enum_tag_value, 1,
    4693                 :         36 :             get_llvm_cc(g, CallingConventionUnspecified), ZigLLVM_FnInlineAuto, "");
    4694                 :            : }
    4695                 :            : 
    4696                 :        107 : static LLVMValueRef ir_render_field_parent_ptr(CodeGen *g, IrExecutable *executable,
    4697                 :            :         IrInstructionFieldParentPtr *instruction)
    4698                 :            : {
    4699                 :        107 :     ZigType *container_ptr_type = instruction->base.value.type;
    4700                 :        107 :     assert(container_ptr_type->id == ZigTypeIdPointer);
    4701                 :            : 
    4702                 :        107 :     ZigType *container_type = container_ptr_type->data.pointer.child_type;
    4703                 :            : 
    4704                 :        107 :     size_t byte_offset = LLVMOffsetOfElement(g->target_data_ref,
    4705                 :        107 :             get_llvm_type(g, container_type), instruction->field->gen_index);
    4706                 :            : 
    4707                 :        107 :     LLVMValueRef field_ptr_val = ir_llvm_value(g, instruction->field_ptr);
    4708                 :            : 
    4709         [ +  + ]:        107 :     if (byte_offset == 0) {
    4710                 :         58 :         return LLVMBuildBitCast(g->builder, field_ptr_val, get_llvm_type(g, container_ptr_type), "");
    4711                 :            :     } else {
    4712                 :         49 :         ZigType *usize = g->builtin_types.entry_usize;
    4713                 :            : 
    4714                 :         49 :         LLVMValueRef field_ptr_int = LLVMBuildPtrToInt(g->builder, field_ptr_val, usize->llvm_type, "");
    4715                 :            : 
    4716                 :         49 :         LLVMValueRef base_ptr_int = LLVMBuildNUWSub(g->builder, field_ptr_int,
    4717                 :         49 :                 LLVMConstInt(usize->llvm_type, byte_offset, false), "");
    4718                 :            : 
    4719                 :         49 :         return LLVMBuildIntToPtr(g->builder, base_ptr_int, get_llvm_type(g, container_ptr_type), "");
    4720                 :            :     }
    4721                 :            : }
    4722                 :            : 
    4723                 :        142 : static LLVMValueRef ir_render_align_cast(CodeGen *g, IrExecutable *executable, IrInstructionAlignCast *instruction) {
    4724                 :        142 :     LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    4725                 :        142 :     assert(target_val);
    4726                 :            : 
    4727                 :        142 :     bool want_runtime_safety = ir_want_runtime_safety(g, &instruction->base);
    4728         [ -  + ]:        142 :     if (!want_runtime_safety) {
    4729                 :          0 :         return target_val;
    4730                 :            :     }
    4731                 :            : 
    4732                 :        142 :     ZigType *target_type = instruction->base.value.type;
    4733                 :            :     uint32_t align_bytes;
    4734                 :            :     LLVMValueRef ptr_val;
    4735                 :            : 
    4736         [ +  + ]:        142 :     if (target_type->id == ZigTypeIdPointer) {
    4737                 :         23 :         align_bytes = get_ptr_align(g, target_type);
    4738                 :         23 :         ptr_val = target_val;
    4739         [ +  + ]:        119 :     } else if (target_type->id == ZigTypeIdFn) {
    4740                 :          8 :         align_bytes = target_type->data.fn.fn_type_id.alignment;
    4741                 :          8 :         ptr_val = target_val;
    4742 [ +  + ][ +  - ]:        111 :     } else if (target_type->id == ZigTypeIdOptional &&
    4743                 :          1 :             target_type->data.maybe.child_type->id == ZigTypeIdPointer)
    4744                 :            :     {
    4745                 :          1 :         align_bytes = get_ptr_align(g, target_type->data.maybe.child_type);
    4746                 :          1 :         ptr_val = target_val;
    4747 [ -  + ][ #  # ]:        110 :     } else if (target_type->id == ZigTypeIdOptional &&
    4748                 :          0 :             target_type->data.maybe.child_type->id == ZigTypeIdFn)
    4749                 :            :     {
    4750                 :          0 :         align_bytes = target_type->data.maybe.child_type->data.fn.fn_type_id.alignment;
    4751                 :          0 :         ptr_val = target_val;
    4752 [ +  - ][ +  - ]:        110 :     } else if (target_type->id == ZigTypeIdStruct && target_type->data.structure.is_slice) {
    4753                 :        110 :         ZigType *slice_ptr_type = target_type->data.structure.fields[slice_ptr_index].type_entry;
    4754                 :        110 :         align_bytes = get_ptr_align(g, slice_ptr_type);
    4755                 :            : 
    4756                 :        110 :         size_t ptr_index = target_type->data.structure.fields[slice_ptr_index].gen_index;
    4757                 :        110 :         LLVMValueRef ptr_val_ptr = LLVMBuildStructGEP(g->builder, target_val, (unsigned)ptr_index, "");
    4758                 :        110 :         ptr_val = gen_load_untyped(g, ptr_val_ptr, 0, false, "");
    4759                 :            :     } else {
    4760                 :          0 :         zig_unreachable();
    4761                 :            :     }
    4762                 :            : 
    4763                 :        142 :     assert(align_bytes != 1);
    4764                 :            : 
    4765                 :        142 :     ZigType *usize = g->builtin_types.entry_usize;
    4766                 :        142 :     LLVMValueRef ptr_as_int_val = LLVMBuildPtrToInt(g->builder, ptr_val, usize->llvm_type, "");
    4767                 :        142 :     LLVMValueRef alignment_minus_1 = LLVMConstInt(usize->llvm_type, align_bytes - 1, false);
    4768                 :        142 :     LLVMValueRef anded_val = LLVMBuildAnd(g->builder, ptr_as_int_val, alignment_minus_1, "");
    4769                 :        142 :     LLVMValueRef ok_bit = LLVMBuildICmp(g->builder, LLVMIntEQ, anded_val, LLVMConstNull(usize->llvm_type), "");
    4770                 :            : 
    4771                 :        142 :     LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "AlignCastOk");
    4772                 :        142 :     LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "AlignCastFail");
    4773                 :            : 
    4774                 :        142 :     LLVMBuildCondBr(g->builder, ok_bit, ok_block, fail_block);
    4775                 :            : 
    4776                 :        142 :     LLVMPositionBuilderAtEnd(g->builder, fail_block);
    4777                 :        142 :     gen_safety_crash(g, PanicMsgIdIncorrectAlignment);
    4778                 :            : 
    4779                 :        142 :     LLVMPositionBuilderAtEnd(g->builder, ok_block);
    4780                 :            : 
    4781                 :        142 :     return target_val;
    4782                 :            : }
    4783                 :            : 
    4784                 :         17 : static LLVMValueRef ir_render_error_return_trace(CodeGen *g, IrExecutable *executable,
    4785                 :            :         IrInstructionErrorReturnTrace *instruction)
    4786                 :            : {
    4787                 :         17 :     LLVMValueRef cur_err_ret_trace_val = get_cur_err_ret_trace_val(g, instruction->base.scope);
    4788         [ -  + ]:         17 :     if (cur_err_ret_trace_val == nullptr) {
    4789                 :          0 :         return LLVMConstNull(get_llvm_type(g, ptr_to_stack_trace_type(g)));
    4790                 :            :     }
    4791                 :         17 :     return cur_err_ret_trace_val;
    4792                 :            : }
    4793                 :            : 
    4794                 :        302 : static LLVMAtomicOrdering to_LLVMAtomicOrdering(AtomicOrder atomic_order) {
    4795   [ -  +  +  +  :        302 :     switch (atomic_order) {
                -  +  - ]
    4796                 :          0 :         case AtomicOrderUnordered: return LLVMAtomicOrderingUnordered;
    4797                 :         19 :         case AtomicOrderMonotonic: return LLVMAtomicOrderingMonotonic;
    4798                 :          9 :         case AtomicOrderAcquire: return LLVMAtomicOrderingAcquire;
    4799                 :          6 :         case AtomicOrderRelease: return LLVMAtomicOrderingRelease;
    4800                 :          0 :         case AtomicOrderAcqRel: return LLVMAtomicOrderingAcquireRelease;
    4801                 :        268 :         case AtomicOrderSeqCst: return LLVMAtomicOrderingSequentiallyConsistent;
    4802                 :            :     }
    4803                 :          0 :     zig_unreachable();
    4804                 :            : }
    4805                 :            : 
    4806                 :        156 : static LLVMAtomicRMWBinOp to_LLVMAtomicRMWBinOp(AtomicRmwOp op, bool is_signed) {
    4807   [ +  -  +  -  :        156 :     switch (op) {
          -  -  -  -  -  
                      - ]
    4808                 :        153 :         case AtomicRmwOp_xchg: return LLVMAtomicRMWBinOpXchg;
    4809                 :          0 :         case AtomicRmwOp_add: return LLVMAtomicRMWBinOpAdd;
    4810                 :          3 :         case AtomicRmwOp_sub: return LLVMAtomicRMWBinOpSub;
    4811                 :          0 :         case AtomicRmwOp_and: return LLVMAtomicRMWBinOpAnd;
    4812                 :          0 :         case AtomicRmwOp_nand: return LLVMAtomicRMWBinOpNand;
    4813                 :          0 :         case AtomicRmwOp_or: return LLVMAtomicRMWBinOpOr;
    4814                 :          0 :         case AtomicRmwOp_xor: return LLVMAtomicRMWBinOpXor;
    4815                 :          0 :         case AtomicRmwOp_max:
    4816         [ #  # ]:          0 :             return is_signed ? LLVMAtomicRMWBinOpMax : LLVMAtomicRMWBinOpUMax;
    4817                 :          0 :         case AtomicRmwOp_min:
    4818         [ #  # ]:          0 :             return is_signed ? LLVMAtomicRMWBinOpMin : LLVMAtomicRMWBinOpUMin;
    4819                 :            :     }
    4820                 :          0 :     zig_unreachable();
    4821                 :            : }
    4822                 :            : 
    4823                 :         63 : static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutable *executable, IrInstructionCmpxchgGen *instruction) {
    4824                 :         63 :     LLVMValueRef ptr_val = ir_llvm_value(g, instruction->ptr);
    4825                 :         63 :     LLVMValueRef cmp_val = ir_llvm_value(g, instruction->cmp_value);
    4826                 :         63 :     LLVMValueRef new_val = ir_llvm_value(g, instruction->new_value);
    4827                 :            : 
    4828                 :         63 :     LLVMAtomicOrdering success_order = to_LLVMAtomicOrdering(instruction->success_order);
    4829                 :         63 :     LLVMAtomicOrdering failure_order = to_LLVMAtomicOrdering(instruction->failure_order);
    4830                 :            : 
    4831                 :         63 :     LLVMValueRef result_val = ZigLLVMBuildCmpXchg(g->builder, ptr_val, cmp_val, new_val,
    4832                 :         63 :             success_order, failure_order, instruction->is_weak);
    4833                 :            : 
    4834                 :         63 :     ZigType *optional_type = instruction->base.value.type;
    4835                 :         63 :     assert(optional_type->id == ZigTypeIdOptional);
    4836                 :         63 :     ZigType *child_type = optional_type->data.maybe.child_type;
    4837                 :            : 
    4838         [ +  + ]:         63 :     if (!handle_is_ptr(optional_type)) {
    4839                 :         24 :         LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, "");
    4840                 :         24 :         LLVMValueRef success_bit = LLVMBuildExtractValue(g->builder, result_val, 1, "");
    4841                 :         24 :         return LLVMBuildSelect(g->builder, success_bit, LLVMConstNull(get_llvm_type(g, child_type)), payload_val, "");
    4842                 :            :     }
    4843                 :            : 
    4844                 :            :     // When the cmpxchg is discarded, the result location will have no bits.
    4845         [ +  + ]:         39 :     if (!type_has_bits(instruction->result_loc->value.type)) {
    4846                 :          8 :         return nullptr;
    4847                 :            :     }
    4848                 :            : 
    4849                 :         31 :     LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    4850                 :         31 :     src_assert(result_loc != nullptr, instruction->base.source_node);
    4851                 :         31 :     src_assert(type_has_bits(child_type), instruction->base.source_node);
    4852                 :            : 
    4853                 :         31 :     LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, "");
    4854                 :         31 :     LLVMValueRef val_ptr = LLVMBuildStructGEP(g->builder, result_loc, maybe_child_index, "");
    4855                 :         31 :     gen_assign_raw(g, val_ptr, get_pointer_to_type(g, child_type, false), payload_val);
    4856                 :            : 
    4857                 :         31 :     LLVMValueRef success_bit = LLVMBuildExtractValue(g->builder, result_val, 1, "");
    4858                 :         31 :     LLVMValueRef nonnull_bit = LLVMBuildNot(g->builder, success_bit, "");
    4859                 :         31 :     LLVMValueRef maybe_ptr = LLVMBuildStructGEP(g->builder, result_loc, maybe_null_index, "");
    4860                 :         31 :     gen_store_untyped(g, nonnull_bit, maybe_ptr, 0, false);
    4861                 :         31 :     return result_loc;
    4862                 :            : }
    4863                 :            : 
    4864                 :          8 : static LLVMValueRef ir_render_fence(CodeGen *g, IrExecutable *executable, IrInstructionFence *instruction) {
    4865                 :          8 :     LLVMAtomicOrdering atomic_order = to_LLVMAtomicOrdering(instruction->order);
    4866                 :          8 :     LLVMBuildFence(g->builder, atomic_order, false, "");
    4867                 :          8 :     return nullptr;
    4868                 :            : }
    4869                 :            : 
    4870                 :        346 : static LLVMValueRef ir_render_truncate(CodeGen *g, IrExecutable *executable, IrInstructionTruncate *instruction) {
    4871                 :        346 :     LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    4872                 :        346 :     ZigType *dest_type = instruction->base.value.type;
    4873                 :        346 :     ZigType *src_type = instruction->target->value.type;
    4874         [ +  + ]:        346 :     if (dest_type == src_type) {
    4875                 :            :         // no-op
    4876                 :         20 :         return target_val;
    4877         [ -  + ]:        326 :     } if (src_type->data.integral.bit_count == dest_type->data.integral.bit_count) {
    4878                 :          0 :         return LLVMBuildBitCast(g->builder, target_val, get_llvm_type(g, dest_type), "");
    4879                 :            :     } else {
    4880                 :        326 :         LLVMValueRef target_val = ir_llvm_value(g, instruction->target);
    4881                 :        326 :         return LLVMBuildTrunc(g->builder, target_val, get_llvm_type(g, dest_type), "");
    4882                 :            :     }
    4883                 :            : }
    4884                 :            : 
    4885                 :        280 : static LLVMValueRef ir_render_memset(CodeGen *g, IrExecutable *executable, IrInstructionMemset *instruction) {
    4886                 :        280 :     LLVMValueRef dest_ptr = ir_llvm_value(g, instruction->dest_ptr);
    4887                 :        280 :     LLVMValueRef len_val = ir_llvm_value(g, instruction->count);
    4888                 :            : 
    4889                 :        280 :     LLVMTypeRef ptr_u8 = LLVMPointerType(LLVMInt8Type(), 0);
    4890                 :        280 :     LLVMValueRef dest_ptr_casted = LLVMBuildBitCast(g->builder, dest_ptr, ptr_u8, "");
    4891                 :            : 
    4892                 :        280 :     ZigType *ptr_type = instruction->dest_ptr->value.type;
    4893                 :        280 :     assert(ptr_type->id == ZigTypeIdPointer);
    4894                 :            : 
    4895                 :        280 :     bool val_is_undef = value_is_all_undef(g, &instruction->byte->value);
    4896                 :            :     LLVMValueRef fill_char;
    4897         [ +  + ]:        280 :     if (val_is_undef) {
    4898                 :        253 :         fill_char = LLVMConstInt(LLVMInt8Type(), 0xaa, false);
    4899                 :            :     } else {
    4900                 :         27 :         fill_char = ir_llvm_value(g, instruction->byte);
    4901                 :            :     }
    4902                 :        280 :     ZigLLVMBuildMemSet(g->builder, dest_ptr_casted, fill_char, len_val, get_ptr_align(g, ptr_type),
    4903                 :        280 :             ptr_type->data.pointer.is_volatile);
    4904                 :            : 
    4905 [ +  + ][ +  + ]:        280 :     if (val_is_undef && want_valgrind_support(g)) {
                 [ +  + ]
    4906                 :        209 :         gen_valgrind_undef(g, dest_ptr_casted, len_val);
    4907                 :            :     }
    4908                 :        280 :     return nullptr;
    4909                 :            : }
    4910                 :            : 
    4911                 :         61 : static LLVMValueRef ir_render_memcpy(CodeGen *g, IrExecutable *executable, IrInstructionMemcpy *instruction) {
    4912                 :         61 :     LLVMValueRef dest_ptr = ir_llvm_value(g, instruction->dest_ptr);
    4913                 :         61 :     LLVMValueRef src_ptr = ir_llvm_value(g, instruction->src_ptr);
    4914                 :         61 :     LLVMValueRef len_val = ir_llvm_value(g, instruction->count);
    4915                 :            : 
    4916                 :         61 :     LLVMTypeRef ptr_u8 = LLVMPointerType(LLVMInt8Type(), 0);
    4917                 :            : 
    4918                 :         61 :     LLVMValueRef dest_ptr_casted = LLVMBuildBitCast(g->builder, dest_ptr, ptr_u8, "");
    4919                 :         61 :     LLVMValueRef src_ptr_casted = LLVMBuildBitCast(g->builder, src_ptr, ptr_u8, "");
    4920                 :            : 
    4921                 :         61 :     ZigType *dest_ptr_type = instruction->dest_ptr->value.type;
    4922                 :         61 :     ZigType *src_ptr_type = instruction->src_ptr->value.type;
    4923                 :            : 
    4924                 :         61 :     assert(dest_ptr_type->id == ZigTypeIdPointer);
    4925                 :         61 :     assert(src_ptr_type->id == ZigTypeIdPointer);
    4926                 :            : 
    4927 [ -  + ][ +  - ]:         61 :     bool is_volatile = (dest_ptr_type->data.pointer.is_volatile || src_ptr_type->data.pointer.is_volatile);
    4928                 :         61 :     ZigLLVMBuildMemCpy(g->builder, dest_ptr_casted, get_ptr_align(g, dest_ptr_type),
    4929                 :            :             src_ptr_casted, get_ptr_align(g, src_ptr_type), len_val, is_volatile);
    4930                 :         61 :     return nullptr;
    4931                 :            : }
    4932                 :            : 
    4933                 :       3633 : static LLVMValueRef ir_render_slice(CodeGen *g, IrExecutable *executable, IrInstructionSliceGen *instruction) {
    4934                 :       3633 :     LLVMValueRef array_ptr_ptr = ir_llvm_value(g, instruction->ptr);
    4935                 :       3633 :     ZigType *array_ptr_type = instruction->ptr->value.type;
    4936                 :       3633 :     assert(array_ptr_type->id == ZigTypeIdPointer);
    4937                 :       3633 :     ZigType *array_type = array_ptr_type->data.pointer.child_type;
    4938                 :       3633 :     LLVMValueRef array_ptr = get_handle_value(g, array_ptr_ptr, array_type, array_ptr_type);
    4939                 :            : 
    4940                 :       3633 :     LLVMValueRef tmp_struct_ptr = ir_llvm_value(g, instruction->result_loc);
    4941                 :            : 
    4942 [ +  - ][ +  + ]:       3633 :     bool want_runtime_safety = instruction->safety_check_on && ir_want_runtime_safety(g, &instruction->base);
    4943                 :            : 
    4944 [ +  + ][ +  + ]:       3633 :     if (array_type->id == ZigTypeIdArray ||
    4945         [ +  + ]:        578 :         (array_type->id == ZigTypeIdPointer && array_type->data.pointer.ptr_len == PtrLenSingle))
    4946                 :            :     {
    4947         [ +  + ]:       1825 :         if (array_type->id == ZigTypeIdPointer) {
    4948                 :         98 :             array_type = array_type->data.pointer.child_type;
    4949                 :            :         }
    4950                 :       1825 :         LLVMValueRef start_val = ir_llvm_value(g, instruction->start);
    4951                 :            :         LLVMValueRef end_val;
    4952         [ +  + ]:       1825 :         if (instruction->end) {
    4953                 :       1126 :             end_val = ir_llvm_value(g, instruction->end);
    4954                 :            :         } else {
    4955                 :        699 :             end_val = LLVMConstInt(g->builtin_types.entry_usize->llvm_type, array_type->data.array.len, false);
    4956                 :            :         }
    4957         [ +  + ]:       1825 :         if (want_runtime_safety) {
    4958 [ +  + ][ +  + ]:        918 :             if (instruction->start->value.special == ConstValSpecialRuntime || instruction->end) {
    4959                 :        383 :                 add_bounds_check(g, start_val, LLVMIntEQ, nullptr, LLVMIntULE, end_val);
    4960                 :            :             }
    4961         [ +  + ]:        918 :             if (instruction->end) {
    4962                 :        219 :                 LLVMValueRef array_end = LLVMConstInt(g->builtin_types.entry_usize->llvm_type,
    4963                 :        219 :                         array_type->data.array.len, false);
    4964                 :        918 :                 add_bounds_check(g, end_val, LLVMIntEQ, nullptr, LLVMIntULE, array_end);
    4965                 :            :             }
    4966                 :            :         }
    4967         [ -  + ]:       1825 :         if (!type_has_bits(array_type)) {
    4968                 :          0 :             LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, tmp_struct_ptr, slice_len_index, "");
    4969                 :            : 
    4970                 :            :             // TODO if runtime safety is on, store 0xaaaaaaa in ptr field
    4971                 :          0 :             LLVMValueRef len_value = LLVMBuildNSWSub(g->builder, end_val, start_val, "");
    4972                 :          0 :             gen_store_untyped(g, len_value, len_field_ptr, 0, false);
    4973                 :          0 :             return tmp_struct_ptr;
    4974                 :            :         }
    4975                 :            : 
    4976                 :            : 
    4977                 :       1825 :         LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, tmp_struct_ptr, slice_ptr_index, "");
    4978                 :            :         LLVMValueRef indices[] = {
    4979                 :       1825 :             LLVMConstNull(g->builtin_types.entry_usize->llvm_type),
    4980                 :            :             start_val,
    4981                 :       1825 :         };
    4982                 :       1825 :         LLVMValueRef slice_start_ptr = LLVMBuildInBoundsGEP(g->builder, array_ptr, indices, 2, "");
    4983                 :       1825 :         gen_store_untyped(g, slice_start_ptr, ptr_field_ptr, 0, false);
    4984                 :            : 
    4985                 :       1825 :         LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, tmp_struct_ptr, slice_len_index, "");
    4986                 :       1825 :         LLVMValueRef len_value = LLVMBuildNSWSub(g->builder, end_val, start_val, "");
    4987                 :       1825 :         gen_store_untyped(g, len_value, len_field_ptr, 0, false);
    4988                 :            : 
    4989                 :       1825 :         return tmp_struct_ptr;
    4990         [ +  + ]:       1808 :     } else if (array_type->id == ZigTypeIdPointer) {
    4991                 :        480 :         assert(array_type->data.pointer.ptr_len != PtrLenSingle);
    4992                 :        480 :         LLVMValueRef start_val = ir_llvm_value(g, instruction->start);
    4993                 :        480 :         LLVMValueRef end_val = ir_llvm_value(g, instruction->end);
    4994                 :            : 
    4995         [ +  - ]:        480 :         if (want_runtime_safety) {
    4996                 :        480 :             add_bounds_check(g, start_val, LLVMIntEQ, nullptr, LLVMIntULE, end_val);
    4997                 :            :         }
    4998                 :            : 
    4999         [ +  + ]:        480 :         if (type_has_bits(array_type)) {
    5000                 :        472 :             size_t gen_ptr_index = instruction->base.value.type->data.structure.fields[slice_ptr_index].gen_index;
    5001                 :        472 :             LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, tmp_struct_ptr, gen_ptr_index, "");
    5002                 :        472 :             LLVMValueRef slice_start_ptr = LLVMBuildInBoundsGEP(g->builder, array_ptr, &start_val, 1, "");
    5003                 :        472 :             gen_store_untyped(g, slice_start_ptr, ptr_field_ptr, 0, false);
    5004                 :            :         }
    5005                 :            : 
    5006                 :        480 :         size_t gen_len_index = instruction->base.value.type->data.structure.fields[slice_len_index].gen_index;
    5007                 :        480 :         LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, tmp_struct_ptr, gen_len_index, "");
    5008                 :        480 :         LLVMValueRef len_value = LLVMBuildNSWSub(g->builder, end_val, start_val, "");
    5009                 :        480 :         gen_store_untyped(g, len_value, len_field_ptr, 0, false);
    5010                 :            : 
    5011                 :        480 :         return tmp_struct_ptr;
    5012         [ +  - ]:       1328 :     } else if (array_type->id == ZigTypeIdStruct) {
    5013                 :       1328 :         assert(array_type->data.structure.is_slice);
    5014                 :       1328 :         assert(LLVMGetTypeKind(LLVMTypeOf(array_ptr)) == LLVMPointerTypeKind);
    5015                 :       1328 :         assert(LLVMGetTypeKind(LLVMGetElementType(LLVMTypeOf(array_ptr))) == LLVMStructTypeKind);
    5016                 :       1328 :         assert(LLVMGetTypeKind(LLVMGetElementType(LLVMTypeOf(tmp_struct_ptr))) == LLVMStructTypeKind);
    5017                 :            : 
    5018                 :       1328 :         size_t ptr_index = array_type->data.structure.fields[slice_ptr_index].gen_index;
    5019                 :       1328 :         assert(ptr_index != SIZE_MAX);
    5020                 :       1328 :         size_t len_index = array_type->data.structure.fields[slice_len_index].gen_index;
    5021                 :       1328 :         assert(len_index != SIZE_MAX);
    5022                 :            : 
    5023                 :       1328 :         LLVMValueRef prev_end = nullptr;
    5024 [ +  - ][ +  + ]:       1328 :         if (!instruction->end || want_runtime_safety) {
    5025                 :       1328 :             LLVMValueRef src_len_ptr = LLVMBuildStructGEP(g->builder, array_ptr, (unsigned)len_index, "");
    5026                 :       1328 :             prev_end = gen_load_untyped(g, src_len_ptr, 0, false, "");
    5027                 :            :         }
    5028                 :            : 
    5029                 :       1328 :         LLVMValueRef start_val = ir_llvm_value(g, instruction->start);
    5030                 :            :         LLVMValueRef end_val;
    5031         [ +  + ]:       1328 :         if (instruction->end) {
    5032                 :        567 :             end_val = ir_llvm_value(g, instruction->end);
    5033                 :            :         } else {
    5034                 :        761 :             end_val = prev_end;
    5035                 :            :         }
    5036                 :            : 
    5037         [ +  - ]:       1328 :         if (want_runtime_safety) {
    5038                 :       1328 :             assert(prev_end);
    5039                 :       1328 :             add_bounds_check(g, start_val, LLVMIntEQ, nullptr, LLVMIntULE, end_val);
    5040         [ +  + ]:       1328 :             if (instruction->end) {
    5041                 :        567 :                 add_bounds_check(g, end_val, LLVMIntEQ, nullptr, LLVMIntULE, prev_end);
    5042                 :            :             }
    5043                 :            :         }
    5044                 :            : 
    5045                 :       1328 :         LLVMValueRef src_ptr_ptr = LLVMBuildStructGEP(g->builder, array_ptr, (unsigned)ptr_index, "");
    5046                 :       1328 :         LLVMValueRef src_ptr = gen_load_untyped(g, src_ptr_ptr, 0, false, "");
    5047                 :       1328 :         LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, tmp_struct_ptr, (unsigned)ptr_index, "");
    5048                 :       1328 :         LLVMValueRef slice_start_ptr = LLVMBuildInBoundsGEP(g->builder, src_ptr, &start_val, (unsigned)len_index, "");
    5049                 :       1328 :         gen_store_untyped(g, slice_start_ptr, ptr_field_ptr, 0, false);
    5050                 :            : 
    5051                 :       1328 :         LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, tmp_struct_ptr, (unsigned)len_index, "");
    5052                 :       1328 :         LLVMValueRef len_value = LLVMBuildNSWSub(g->builder, end_val, start_val, "");
    5053                 :       1328 :         gen_store_untyped(g, len_value, len_field_ptr, 0, false);
    5054                 :            : 
    5055                 :       1328 :         return tmp_struct_ptr;
    5056                 :            :     } else {
    5057                 :          0 :         zig_unreachable();
    5058                 :            :     }
    5059                 :            : }
    5060                 :            : 
    5061                 :          2 : static LLVMValueRef get_trap_fn_val(CodeGen *g) {
    5062         [ -  + ]:          2 :     if (g->trap_fn_val)
    5063                 :          0 :         return g->trap_fn_val;
    5064                 :            : 
    5065                 :          2 :     LLVMTypeRef fn_type = LLVMFunctionType(LLVMVoidType(), nullptr, 0, false);
    5066                 :          2 :     g->trap_fn_val = LLVMAddFunction(g->module, "llvm.debugtrap", fn_type);
    5067                 :          2 :     assert(LLVMGetIntrinsicID(g->trap_fn_val));
    5068                 :            : 
    5069                 :          2 :     return g->trap_fn_val;
    5070                 :            : }
    5071                 :            : 
    5072                 :            : 
    5073                 :          2 : static LLVMValueRef ir_render_breakpoint(CodeGen *g, IrExecutable *executable, IrInstructionBreakpoint *instruction) {
    5074                 :          2 :     LLVMBuildCall(g->builder, get_trap_fn_val(g), nullptr, 0, "");
    5075                 :          2 :     return nullptr;
    5076                 :            : }
    5077                 :            : 
    5078                 :        126 : static LLVMValueRef ir_render_return_address(CodeGen *g, IrExecutable *executable,
    5079                 :            :         IrInstructionReturnAddress *instruction)
    5080                 :            : {
    5081                 :        126 :     LLVMValueRef zero = LLVMConstNull(g->builtin_types.entry_i32->llvm_type);
    5082                 :        126 :     LLVMValueRef ptr_val = LLVMBuildCall(g->builder, get_return_address_fn_val(g), &zero, 1, "");
    5083                 :        126 :     return LLVMBuildPtrToInt(g->builder, ptr_val, g->builtin_types.entry_usize->llvm_type, "");
    5084                 :            : }
    5085                 :            : 
    5086                 :          7 : static LLVMValueRef get_frame_address_fn_val(CodeGen *g) {
    5087         [ -  + ]:          7 :     if (g->frame_address_fn_val)
    5088                 :          0 :         return g->frame_address_fn_val;
    5089                 :            : 
    5090                 :          7 :     ZigType *return_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);
    5091                 :            : 
    5092                 :          7 :     LLVMTypeRef fn_type = LLVMFunctionType(get_llvm_type(g, return_type),
    5093                 :          7 :             &g->builtin_types.entry_i32->llvm_type, 1, false);
    5094                 :          7 :     g->frame_address_fn_val = LLVMAddFunction(g->module, "llvm.frameaddress", fn_type);
    5095                 :          7 :     assert(LLVMGetIntrinsicID(g->frame_address_fn_val));
    5096                 :            : 
    5097                 :          7 :     return g->frame_address_fn_val;
    5098                 :            : }
    5099                 :            : 
    5100                 :          7 : static LLVMValueRef ir_render_frame_address(CodeGen *g, IrExecutable *executable,
    5101                 :            :         IrInstructionFrameAddress *instruction)
    5102                 :            : {
    5103                 :          7 :     LLVMValueRef zero = LLVMConstNull(g->builtin_types.entry_i32->llvm_type);
    5104                 :          7 :     LLVMValueRef ptr_val = LLVMBuildCall(g->builder, get_frame_address_fn_val(g), &zero, 1, "");
    5105                 :          7 :     return LLVMBuildPtrToInt(g->builder, ptr_val, g->builtin_types.entry_usize->llvm_type, "");
    5106                 :            : }
    5107                 :            : 
    5108                 :        320 : static LLVMValueRef ir_render_handle(CodeGen *g, IrExecutable *executable, IrInstructionFrameHandle *instruction) {
    5109                 :        320 :     return g->cur_frame_ptr;
    5110                 :            : }
    5111                 :            : 
    5112                 :         45 : static LLVMValueRef render_shl_with_overflow(CodeGen *g, IrInstructionOverflowOp *instruction) {
    5113                 :         45 :     ZigType *int_type = instruction->result_ptr_type;
    5114                 :         45 :     assert(int_type->id == ZigTypeIdInt);
    5115                 :            : 
    5116                 :         45 :     LLVMValueRef op1 = ir_llvm_value(g, instruction->op1);
    5117                 :         45 :     LLVMValueRef op2 = ir_llvm_value(g, instruction->op2);
    5118                 :         45 :     LLVMValueRef ptr_result = ir_llvm_value(g, instruction->result_ptr);
    5119                 :            : 
    5120                 :         45 :     LLVMValueRef op2_casted = gen_widen_or_shorten(g, false, instruction->op2->value.type,
    5121                 :         45 :             instruction->op1->value.type, op2);
    5122                 :            : 
    5123                 :         45 :     LLVMValueRef result = LLVMBuildShl(g->builder, op1, op2_casted, "");
    5124                 :            :     LLVMValueRef orig_val;
    5125         [ -  + ]:         45 :     if (int_type->data.integral.is_signed) {
    5126                 :          0 :         orig_val = LLVMBuildAShr(g->builder, result, op2_casted, "");
    5127                 :            :     } else {
    5128                 :         45 :         orig_val = LLVMBuildLShr(g->builder, result, op2_casted, "");
    5129                 :            :     }
    5130                 :         45 :     LLVMValueRef overflow_bit = LLVMBuildICmp(g->builder, LLVMIntNE, op1, orig_val, "");
    5131                 :            : 
    5132                 :         45 :     gen_store(g, result, ptr_result, instruction->result_ptr->value.type);
    5133                 :            : 
    5134                 :         45 :     return overflow_bit;
    5135                 :            : }
    5136                 :            : 
    5137                 :         83 : static LLVMValueRef ir_render_overflow_op(CodeGen *g, IrExecutable *executable, IrInstructionOverflowOp *instruction) {
    5138                 :            :     AddSubMul add_sub_mul;
    5139   [ +  -  +  +  :         83 :     switch (instruction->op) {
                      - ]
    5140                 :         29 :         case IrOverflowOpAdd:
    5141                 :         29 :             add_sub_mul = AddSubMulAdd;
    5142                 :         29 :             break;
    5143                 :          0 :         case IrOverflowOpSub:
    5144                 :          0 :             add_sub_mul = AddSubMulSub;
    5145                 :          0 :             break;
    5146                 :          9 :         case IrOverflowOpMul:
    5147                 :          9 :             add_sub_mul = AddSubMulMul;
    5148                 :          9 :             break;
    5149                 :         45 :         case IrOverflowOpShl:
    5150                 :         45 :             return render_shl_with_overflow(g, instruction);
    5151                 :            :     }
    5152                 :            : 
    5153                 :         38 :     ZigType *int_type = instruction->result_ptr_type;
    5154                 :         38 :     assert(int_type->id == ZigTypeIdInt);
    5155                 :            : 
    5156                 :         38 :     LLVMValueRef fn_val = get_int_overflow_fn(g, int_type, add_sub_mul);
    5157                 :            : 
    5158                 :         38 :     LLVMValueRef op1 = ir_llvm_value(g, instruction->op1);
    5159                 :         38 :     LLVMValueRef op2 = ir_llvm_value(g, instruction->op2);
    5160                 :         38 :     LLVMValueRef ptr_result = ir_llvm_value(g, instruction->result_ptr);
    5161                 :            : 
    5162                 :            :     LLVMValueRef params[] = {
    5163                 :            :         op1,
    5164                 :            :         op2,
    5165                 :         38 :     };
    5166                 :            : 
    5167                 :         38 :     LLVMValueRef result_struct = LLVMBuildCall(g->builder, fn_val, params, 2, "");
    5168                 :         38 :     LLVMValueRef result = LLVMBuildExtractValue(g->builder, result_struct, 0, "");
    5169                 :         38 :     LLVMValueRef overflow_bit = LLVMBuildExtractValue(g->builder, result_struct, 1, "");
    5170                 :         38 :     gen_store(g, result, ptr_result, instruction->result_ptr->value.type);
    5171                 :            : 
    5172                 :         83 :     return overflow_bit;
    5173                 :            : }
    5174                 :            : 
    5175                 :      10272 : static LLVMValueRef ir_render_test_err(CodeGen *g, IrExecutable *executable, IrInstructionTestErrGen *instruction) {
    5176                 :      10272 :     ZigType *err_union_type = instruction->err_union->value.type;
    5177                 :      10272 :     ZigType *payload_type = err_union_type->data.error_union.payload_type;
    5178                 :      10272 :     LLVMValueRef err_union_handle = ir_llvm_value(g, instruction->err_union);
    5179                 :            : 
    5180                 :            :     LLVMValueRef err_val;
    5181         [ +  + ]:      10272 :     if (type_has_bits(payload_type)) {
    5182                 :       4652 :         LLVMValueRef err_val_ptr = LLVMBuildStructGEP(g->builder, err_union_handle, err_union_err_index, "");
    5183                 :       4652 :         err_val = gen_load_untyped(g, err_val_ptr, 0, false, "");
    5184                 :            :     } else {
    5185                 :       5620 :         err_val = err_union_handle;
    5186                 :            :     }
    5187                 :            : 
    5188                 :      10272 :     LLVMValueRef zero = LLVMConstNull(get_llvm_type(g, g->err_tag_type));
    5189                 :      10272 :     return LLVMBuildICmp(g->builder, LLVMIntNE, err_val, zero, "");
    5190                 :            : }
    5191                 :            : 
    5192                 :       8877 : static LLVMValueRef ir_render_unwrap_err_code(CodeGen *g, IrExecutable *executable,
    5193                 :            :         IrInstructionUnwrapErrCode *instruction)
    5194                 :            : {
    5195         [ -  + ]:       8877 :     if (instruction->base.value.special != ConstValSpecialRuntime)
    5196                 :          0 :         return nullptr;
    5197                 :            : 
    5198                 :       8877 :     ZigType *ptr_type = instruction->err_union_ptr->value.type;
    5199                 :       8877 :     assert(ptr_type->id == ZigTypeIdPointer);
    5200                 :       8877 :     ZigType *err_union_type = ptr_type->data.pointer.child_type;
    5201                 :       8877 :     ZigType *payload_type = err_union_type->data.error_union.payload_type;
    5202                 :       8877 :     LLVMValueRef err_union_ptr = ir_llvm_value(g, instruction->err_union_ptr);
    5203         [ +  + ]:       8877 :     if (!type_has_bits(payload_type)) {
    5204                 :       3103 :         return err_union_ptr;
    5205                 :            :     } else {
    5206                 :            :         // TODO assign undef to the payload
    5207                 :       5774 :         LLVMValueRef err_union_handle = get_handle_value(g, err_union_ptr, err_union_type, ptr_type);
    5208                 :       5774 :         return LLVMBuildStructGEP(g->builder, err_union_handle, err_union_err_index, "");
    5209                 :            :     }
    5210                 :            : }
    5211                 :            : 
    5212                 :       7193 : static LLVMValueRef ir_render_unwrap_err_payload(CodeGen *g, IrExecutable *executable,
    5213                 :            :         IrInstructionUnwrapErrPayload *instruction)
    5214                 :            : {
    5215         [ -  + ]:       7193 :     if (instruction->base.value.special != ConstValSpecialRuntime)
    5216                 :          0 :         return nullptr;
    5217                 :            : 
    5218 [ +  + ][ +  - ]:       7193 :     bool want_safety = instruction->safety_check_on && ir_want_runtime_safety(g, &instruction->base) &&
                 [ +  - ]
    5219                 :       7889 :         g->errors_by_index.length > 1;
    5220 [ +  + ][ +  + ]:       7193 :     if (!want_safety && !type_has_bits(instruction->base.value.type))
                 [ +  + ]
    5221                 :        176 :         return nullptr;
    5222                 :       7017 :     ZigType *ptr_type = instruction->value->value.type;
    5223                 :       7017 :     assert(ptr_type->id == ZigTypeIdPointer);
    5224                 :       7017 :     ZigType *err_union_type = ptr_type->data.pointer.child_type;
    5225                 :       7017 :     ZigType *payload_type = err_union_type->data.error_union.payload_type;
    5226                 :       7017 :     LLVMValueRef err_union_ptr = ir_llvm_value(g, instruction->value);
    5227                 :       7017 :     LLVMValueRef err_union_handle = get_handle_value(g, err_union_ptr, err_union_type, ptr_type);
    5228                 :            : 
    5229         [ -  + ]:       7017 :     if (!type_has_bits(err_union_type->data.error_union.err_set_type)) {
    5230                 :          0 :         return err_union_handle;
    5231                 :            :     }
    5232                 :            : 
    5233         [ +  + ]:       7017 :     if (want_safety) {
    5234                 :            :         LLVMValueRef err_val;
    5235         [ +  + ]:        696 :         if (type_has_bits(payload_type)) {
    5236                 :        563 :             LLVMValueRef err_val_ptr = LLVMBuildStructGEP(g->builder, err_union_handle, err_union_err_index, "");
    5237                 :        563 :             err_val = gen_load_untyped(g, err_val_ptr, 0, false, "");
    5238                 :            :         } else {
    5239                 :        133 :             err_val = err_union_handle;
    5240                 :            :         }
    5241                 :        696 :         LLVMValueRef zero = LLVMConstNull(get_llvm_type(g, g->err_tag_type));
    5242                 :        696 :         LLVMValueRef cond_val = LLVMBuildICmp(g->builder, LLVMIntEQ, err_val, zero, "");
    5243                 :        696 :         LLVMBasicBlockRef err_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnwrapErrError");
    5244                 :        696 :         LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "UnwrapErrOk");
    5245                 :        696 :         LLVMBuildCondBr(g->builder, cond_val, ok_block, err_block);
    5246                 :            : 
    5247                 :        696 :         LLVMPositionBuilderAtEnd(g->builder, err_block);
    5248                 :        696 :         gen_safety_crash_for_err(g, err_val, instruction->base.scope);
    5249                 :            : 
    5250                 :        696 :         LLVMPositionBuilderAtEnd(g->builder, ok_block);
    5251                 :            :     }
    5252                 :            : 
    5253         [ +  + ]:       7017 :     if (type_has_bits(payload_type)) {
    5254         [ +  + ]:       6884 :         if (instruction->initializing) {
    5255                 :       2264 :             LLVMValueRef err_tag_ptr = LLVMBuildStructGEP(g->builder, err_union_handle, err_union_err_index, "");
    5256                 :       2264 :             LLVMValueRef ok_err_val = LLVMConstNull(get_llvm_type(g, g->err_tag_type));
    5257                 :       2264 :             gen_store_untyped(g, ok_err_val, err_tag_ptr, 0, false);
    5258                 :            :         }
    5259                 :       6884 :         return LLVMBuildStructGEP(g->builder, err_union_handle, err_union_payload_index, "");
    5260                 :            :     } else {
    5261                 :        133 :         return nullptr;
    5262                 :            :     }
    5263                 :            : }
    5264                 :            : 
    5265                 :        267 : static LLVMValueRef ir_render_optional_wrap(CodeGen *g, IrExecutable *executable, IrInstructionOptionalWrap *instruction) {
    5266                 :        267 :     ZigType *wanted_type = instruction->base.value.type;
    5267                 :            : 
    5268                 :        267 :     assert(wanted_type->id == ZigTypeIdOptional);
    5269                 :            : 
    5270                 :        267 :     ZigType *child_type = wanted_type->data.maybe.child_type;
    5271                 :            : 
    5272         [ +  + ]:        267 :     if (!type_has_bits(child_type)) {
    5273                 :          8 :         LLVMValueRef result = LLVMConstAllOnes(LLVMInt1Type());
    5274         [ +  - ]:          8 :         if (instruction->result_loc != nullptr) {
    5275                 :          8 :             LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    5276                 :          8 :             gen_store_untyped(g, result, result_loc, 0, false);
    5277                 :            :         }
    5278                 :          8 :         return result;
    5279                 :            :     }
    5280                 :            : 
    5281                 :        259 :     LLVMValueRef payload_val = ir_llvm_value(g, instruction->operand);
    5282         [ +  + ]:        259 :     if (!handle_is_ptr(wanted_type)) {
    5283         [ +  + ]:         10 :         if (instruction->result_loc != nullptr) {
    5284                 :          8 :             LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    5285                 :          8 :             gen_store_untyped(g, payload_val, result_loc, 0, false);
    5286                 :            :         }
    5287                 :         10 :         return payload_val;
    5288                 :            :     }
    5289                 :            : 
    5290                 :        249 :     LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    5291                 :            : 
    5292                 :        249 :     LLVMValueRef val_ptr = LLVMBuildStructGEP(g->builder, result_loc, maybe_child_index, "");
    5293                 :            :     // child_type and instruction->value->value.type may differ by constness
    5294                 :        249 :     gen_assign_raw(g, val_ptr, get_pointer_to_type(g, child_type, false), payload_val);
    5295                 :        249 :     LLVMValueRef maybe_ptr = LLVMBuildStructGEP(g->builder, result_loc, maybe_null_index, "");
    5296                 :        249 :     gen_store_untyped(g, LLVMConstAllOnes(LLVMInt1Type()), maybe_ptr, 0, false);
    5297                 :            : 
    5298                 :        249 :     return result_loc;
    5299                 :            : }
    5300                 :            : 
    5301                 :       3337 : static LLVMValueRef ir_render_err_wrap_code(CodeGen *g, IrExecutable *executable, IrInstructionErrWrapCode *instruction) {
    5302                 :       3337 :     ZigType *wanted_type = instruction->base.value.type;
    5303                 :            : 
    5304                 :       3337 :     assert(wanted_type->id == ZigTypeIdErrorUnion);
    5305                 :            : 
    5306                 :       3337 :     LLVMValueRef err_val = ir_llvm_value(g, instruction->operand);
    5307                 :            : 
    5308         [ +  + ]:       3337 :     if (!handle_is_ptr(wanted_type))
    5309                 :       3327 :         return err_val;
    5310                 :            : 
    5311                 :         10 :     LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    5312                 :            : 
    5313                 :         10 :     LLVMValueRef err_tag_ptr = LLVMBuildStructGEP(g->builder, result_loc, err_union_err_index, "");
    5314                 :         10 :     gen_store_untyped(g, err_val, err_tag_ptr, 0, false);
    5315                 :            : 
    5316                 :            :     // TODO store undef to the payload
    5317                 :            : 
    5318                 :         10 :     return result_loc;
    5319                 :            : }
    5320                 :            : 
    5321                 :        186 : static LLVMValueRef ir_render_err_wrap_payload(CodeGen *g, IrExecutable *executable, IrInstructionErrWrapPayload *instruction) {
    5322                 :        186 :     ZigType *wanted_type = instruction->base.value.type;
    5323                 :            : 
    5324                 :        186 :     assert(wanted_type->id == ZigTypeIdErrorUnion);
    5325                 :            : 
    5326                 :        186 :     ZigType *payload_type = wanted_type->data.error_union.payload_type;
    5327                 :        186 :     ZigType *err_set_type = wanted_type->data.error_union.err_set_type;
    5328                 :            : 
    5329         [ -  + ]:        186 :     if (!type_has_bits(err_set_type)) {
    5330                 :          0 :         return ir_llvm_value(g, instruction->operand);
    5331                 :            :     }
    5332                 :            : 
    5333                 :        186 :     LLVMValueRef ok_err_val = LLVMConstNull(get_llvm_type(g, g->err_tag_type));
    5334                 :            : 
    5335         [ +  + ]:        186 :     if (!type_has_bits(payload_type))
    5336                 :         10 :         return ok_err_val;
    5337                 :            : 
    5338                 :            : 
    5339                 :        176 :     LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    5340                 :            : 
    5341                 :        176 :     LLVMValueRef payload_val = ir_llvm_value(g, instruction->operand);
    5342                 :            : 
    5343                 :        176 :     LLVMValueRef err_tag_ptr = LLVMBuildStructGEP(g->builder, result_loc, err_union_err_index, "");
    5344                 :        176 :     gen_store_untyped(g, ok_err_val, err_tag_ptr, 0, false);
    5345                 :            : 
    5346                 :        176 :     LLVMValueRef payload_ptr = LLVMBuildStructGEP(g->builder, result_loc, err_union_payload_index, "");
    5347                 :        176 :     gen_assign_raw(g, payload_ptr, get_pointer_to_type(g, payload_type, false), payload_val);
    5348                 :            : 
    5349                 :        176 :     return result_loc;
    5350                 :            : }
    5351                 :            : 
    5352                 :        273 : static LLVMValueRef ir_render_union_tag(CodeGen *g, IrExecutable *executable, IrInstructionUnionTag *instruction) {
    5353                 :        273 :     ZigType *union_type = instruction->value->value.type;
    5354                 :            : 
    5355                 :        273 :     ZigType *tag_type = union_type->data.unionation.tag_type;
    5356         [ -  + ]:        273 :     if (!type_has_bits(tag_type))
    5357                 :          0 :         return nullptr;
    5358                 :            : 
    5359                 :        273 :     LLVMValueRef union_val = ir_llvm_value(g, instruction->value);
    5360         [ +  + ]:        273 :     if (union_type->data.unionation.gen_field_count == 0)
    5361                 :         16 :         return union_val;
    5362                 :            : 
    5363                 :        257 :     assert(union_type->data.unionation.gen_tag_index != SIZE_MAX);
    5364                 :        257 :     LLVMValueRef tag_field_ptr = LLVMBuildStructGEP(g->builder, union_val,
    5365                 :        257 :             union_type->data.unionation.gen_tag_index, "");
    5366                 :        257 :     ZigType *ptr_type = get_pointer_to_type(g, tag_type, false);
    5367                 :        257 :     return get_handle_value(g, tag_field_ptr, tag_type, ptr_type);
    5368                 :            : }
    5369                 :            : 
    5370                 :        289 : static LLVMValueRef ir_render_panic(CodeGen *g, IrExecutable *executable, IrInstructionPanic *instruction) {
    5371                 :        289 :     gen_panic(g, ir_llvm_value(g, instruction->msg), get_cur_err_ret_trace_val(g, instruction->base.scope));
    5372                 :        289 :     return nullptr;
    5373                 :            : }
    5374                 :            : 
    5375                 :        156 : static LLVMValueRef ir_render_atomic_rmw(CodeGen *g, IrExecutable *executable,
    5376                 :            :         IrInstructionAtomicRmw *instruction)
    5377                 :            : {
    5378                 :            :     bool is_signed;
    5379                 :        156 :     ZigType *operand_type = instruction->operand->value.type;
    5380         [ +  - ]:        156 :     if (operand_type->id == ZigTypeIdInt) {
    5381                 :        156 :         is_signed = operand_type->data.integral.is_signed;
    5382                 :            :     } else {
    5383                 :          0 :         is_signed = false;
    5384                 :            :     }
    5385                 :        156 :     LLVMAtomicRMWBinOp op = to_LLVMAtomicRMWBinOp(instruction->resolved_op, is_signed);
    5386                 :        156 :     LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->resolved_ordering);
    5387                 :        156 :     LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
    5388                 :        156 :     LLVMValueRef operand = ir_llvm_value(g, instruction->operand);
    5389                 :            : 
    5390         [ +  - ]:        156 :     if (get_codegen_ptr_type(operand_type) == nullptr) {
    5391                 :        156 :         return LLVMBuildAtomicRMW(g->builder, op, ptr, operand, ordering, g->is_single_threaded);
    5392                 :            :     }
    5393                 :            : 
    5394                 :            :     // it's a pointer but we need to treat it as an int
    5395                 :          0 :     LLVMValueRef casted_ptr = LLVMBuildBitCast(g->builder, ptr,
    5396                 :          0 :         LLVMPointerType(g->builtin_types.entry_usize->llvm_type, 0), "");
    5397                 :          0 :     LLVMValueRef casted_operand = LLVMBuildPtrToInt(g->builder, operand, g->builtin_types.entry_usize->llvm_type, "");
    5398                 :          0 :     LLVMValueRef uncasted_result = LLVMBuildAtomicRMW(g->builder, op, casted_ptr, casted_operand, ordering,
    5399                 :          0 :             g->is_single_threaded);
    5400                 :          0 :     return LLVMBuildIntToPtr(g->builder, uncasted_result, get_llvm_type(g, operand_type), "");
    5401                 :            : }
    5402                 :            : 
    5403                 :         12 : static LLVMValueRef ir_render_atomic_load(CodeGen *g, IrExecutable *executable,
    5404                 :            :         IrInstructionAtomicLoad *instruction)
    5405                 :            : {
    5406                 :         12 :     LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->resolved_ordering);
    5407                 :         12 :     LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
    5408                 :         12 :     LLVMValueRef load_inst = gen_load(g, ptr, instruction->ptr->value.type, "");
    5409                 :         12 :     LLVMSetOrdering(load_inst, ordering);
    5410                 :         12 :     return load_inst;
    5411                 :            : }
    5412                 :            : 
    5413                 :        264 : static LLVMValueRef ir_render_float_op(CodeGen *g, IrExecutable *executable, IrInstructionFloatOp *instruction) {
    5414                 :        264 :     LLVMValueRef op = ir_llvm_value(g, instruction->op1);
    5415                 :        264 :     assert(instruction->base.value.type->id == ZigTypeIdFloat);
    5416                 :        264 :     LLVMValueRef fn_val = get_float_fn(g, instruction->base.value.type, ZigLLVMFnIdFloatOp, instruction->op);
    5417                 :        264 :     return LLVMBuildCall(g->builder, fn_val, &op, 1, "");
    5418                 :            : }
    5419                 :            : 
    5420                 :         24 : static LLVMValueRef ir_render_mul_add(CodeGen *g, IrExecutable *executable, IrInstructionMulAdd *instruction) {
    5421                 :         24 :     LLVMValueRef op1 = ir_llvm_value(g, instruction->op1);
    5422                 :         24 :     LLVMValueRef op2 = ir_llvm_value(g, instruction->op2);
    5423                 :         24 :     LLVMValueRef op3 = ir_llvm_value(g, instruction->op3);
    5424 [ #  # ][ -  + ]:         24 :     assert(instruction->base.value.type->id == ZigTypeIdFloat ||
    5425                 :          0 :            instruction->base.value.type->id == ZigTypeIdVector);
    5426                 :         24 :     LLVMValueRef fn_val = get_float_fn(g, instruction->base.value.type, ZigLLVMFnIdFMA, BuiltinFnIdMulAdd);
    5427                 :            :     LLVMValueRef args[3] = {
    5428                 :            :         op1,
    5429                 :            :         op2,
    5430                 :            :         op3,
    5431                 :         24 :     };
    5432                 :         24 :     return LLVMBuildCall(g->builder, fn_val, args, 3, "");
    5433                 :            : }
    5434                 :            : 
    5435                 :         28 : static LLVMValueRef ir_render_bswap(CodeGen *g, IrExecutable *executable, IrInstructionBswap *instruction) {
    5436                 :         28 :     LLVMValueRef op = ir_llvm_value(g, instruction->op);
    5437                 :         28 :     ZigType *int_type = instruction->base.value.type;
    5438                 :         28 :     assert(int_type->id == ZigTypeIdInt);
    5439         [ +  - ]:         28 :     if (int_type->data.integral.bit_count % 16 == 0) {
    5440                 :         28 :         LLVMValueRef fn_val = get_int_builtin_fn(g, instruction->base.value.type, BuiltinFnIdBswap);
    5441                 :         28 :         return LLVMBuildCall(g->builder, fn_val, &op, 1, "");
    5442                 :            :     }
    5443                 :            :     // Not an even number of bytes, so we zext 1 byte, then bswap, shift right 1 byte, truncate
    5444                 :          0 :     ZigType *extended_type = get_int_type(g, int_type->data.integral.is_signed,
    5445                 :          0 :             int_type->data.integral.bit_count + 8);
    5446                 :            :     // aabbcc
    5447                 :          0 :     LLVMValueRef extended = LLVMBuildZExt(g->builder, op, get_llvm_type(g, extended_type), "");
    5448                 :            :     // 00aabbcc
    5449                 :          0 :     LLVMValueRef fn_val = get_int_builtin_fn(g, extended_type, BuiltinFnIdBswap);
    5450                 :          0 :     LLVMValueRef swapped = LLVMBuildCall(g->builder, fn_val, &extended, 1, "");
    5451                 :            :     // ccbbaa00
    5452                 :          0 :     LLVMValueRef shifted = ZigLLVMBuildLShrExact(g->builder, swapped,
    5453                 :          0 :             LLVMConstInt(get_llvm_type(g, extended_type), 8, false), "");
    5454                 :            :     // 00ccbbaa
    5455                 :         28 :     return LLVMBuildTrunc(g->builder, shifted, get_llvm_type(g, int_type), "");
    5456                 :            : }
    5457                 :            : 
    5458                 :        112 : static LLVMValueRef ir_render_bit_reverse(CodeGen *g, IrExecutable *executable, IrInstructionBitReverse *instruction) {
    5459                 :        112 :     LLVMValueRef op = ir_llvm_value(g, instruction->op);
    5460                 :        112 :     ZigType *int_type = instruction->base.value.type;
    5461                 :        112 :     assert(int_type->id == ZigTypeIdInt);
    5462                 :        112 :     LLVMValueRef fn_val = get_int_builtin_fn(g, instruction->base.value.type, BuiltinFnIdBitReverse);
    5463                 :        112 :     return LLVMBuildCall(g->builder, fn_val, &op, 1, "");
    5464                 :            : }
    5465                 :            : 
    5466                 :        144 : static LLVMValueRef ir_render_vector_to_array(CodeGen *g, IrExecutable *executable,
    5467                 :            :         IrInstructionVectorToArray *instruction)
    5468                 :            : {
    5469                 :        144 :     ZigType *array_type = instruction->base.value.type;
    5470                 :        144 :     assert(array_type->id == ZigTypeIdArray);
    5471                 :        144 :     assert(handle_is_ptr(array_type));
    5472                 :        144 :     LLVMValueRef result_loc = ir_llvm_value(g, instruction->result_loc);
    5473                 :        144 :     LLVMValueRef vector = ir_llvm_value(g, instruction->vector);
    5474                 :        144 :     LLVMValueRef casted_ptr = LLVMBuildBitCast(g->builder, result_loc,
    5475                 :        144 :             LLVMPointerType(get_llvm_type(g, instruction->vector->value.type), 0), "");
    5476                 :        144 :     uint32_t alignment = get_ptr_align(g, instruction->result_loc->value.type);
    5477                 :        144 :     gen_store_untyped(g, vector, casted_ptr, alignment, false);
    5478                 :        144 :     return result_loc;
    5479                 :            : }
    5480                 :            : 
    5481                 :          8 : static LLVMValueRef ir_render_array_to_vector(CodeGen *g, IrExecutable *executable,
    5482                 :            :         IrInstructionArrayToVector *instruction)
    5483                 :            : {
    5484                 :          8 :     ZigType *vector_type = instruction->base.value.type;
    5485                 :          8 :     assert(vector_type->id == ZigTypeIdVector);
    5486                 :          8 :     assert(!handle_is_ptr(vector_type));
    5487                 :          8 :     LLVMValueRef array_ptr = ir_llvm_value(g, instruction->array);
    5488                 :          8 :     LLVMValueRef casted_ptr = LLVMBuildBitCast(g->builder, array_ptr,
    5489                 :          8 :             LLVMPointerType(get_llvm_type(g, vector_type), 0), "");
    5490                 :          8 :     ZigType *array_type = instruction->array->value.type;
    5491                 :          8 :     assert(array_type->id == ZigTypeIdArray);
    5492                 :          8 :     uint32_t alignment = get_abi_alignment(g, array_type->data.array.child_type);
    5493                 :          8 :     return gen_load_untyped(g, casted_ptr, alignment, false, "");
    5494                 :            : }
    5495                 :            : 
    5496                 :         32 : static LLVMValueRef ir_render_assert_zero(CodeGen *g, IrExecutable *executable,
    5497                 :            :         IrInstructionAssertZero *instruction)
    5498                 :            : {
    5499                 :         32 :     LLVMValueRef target = ir_llvm_value(g, instruction->target);
    5500                 :         32 :     ZigType *int_type = instruction->target->value.type;
    5501         [ +  - ]:         32 :     if (ir_want_runtime_safety(g, &instruction->base)) {
    5502                 :         32 :         return gen_assert_zero(g, target, int_type);
    5503                 :            :     }
    5504                 :          0 :     return nullptr;
    5505                 :            : }
    5506                 :            : 
    5507                 :          8 : static LLVMValueRef ir_render_assert_non_null(CodeGen *g, IrExecutable *executable,
    5508                 :            :         IrInstructionAssertNonNull *instruction)
    5509                 :            : {
    5510                 :          8 :     LLVMValueRef target = ir_llvm_value(g, instruction->target);
    5511                 :          8 :     ZigType *target_type = instruction->target->value.type;
    5512                 :            : 
    5513         [ +  - ]:          8 :     if (target_type->id == ZigTypeIdPointer) {
    5514                 :          8 :         assert(target_type->data.pointer.ptr_len == PtrLenC);
    5515                 :          8 :         LLVMValueRef non_null_bit = LLVMBuildICmp(g->builder, LLVMIntNE, target,
    5516                 :          8 :                 LLVMConstNull(get_llvm_type(g, target_type)), "");
    5517                 :            : 
    5518                 :          8 :         LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "AssertNonNullFail");
    5519                 :          8 :         LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "AssertNonNullOk");
    5520                 :          8 :         LLVMBuildCondBr(g->builder, non_null_bit, ok_block, fail_block);
    5521                 :            : 
    5522                 :          8 :         LLVMPositionBuilderAtEnd(g->builder, fail_block);
    5523                 :          8 :         gen_assertion(g, PanicMsgIdUnwrapOptionalFail, &instruction->base);
    5524                 :            : 
    5525                 :          8 :         LLVMPositionBuilderAtEnd(g->builder, ok_block);
    5526                 :            :     } else {
    5527                 :          0 :         zig_unreachable();
    5528                 :            :     }
    5529                 :          8 :     return nullptr;
    5530                 :            : }
    5531                 :            : 
    5532                 :        448 : static LLVMValueRef ir_render_suspend_begin(CodeGen *g, IrExecutable *executable,
    5533                 :            :         IrInstructionSuspendBegin *instruction)
    5534                 :            : {
    5535         [ +  + ]:        448 :     if (fn_is_async(g->cur_fn)) {
    5536                 :        440 :         instruction->resume_bb = gen_suspend_begin(g, "SuspendResume");
    5537                 :            :     }
    5538                 :        448 :     return nullptr;
    5539                 :            : }
    5540                 :            : 
    5541                 :        440 : static LLVMValueRef ir_render_suspend_finish(CodeGen *g, IrExecutable *executable,
    5542                 :            :         IrInstructionSuspendFinish *instruction)
    5543                 :            : {
    5544                 :        440 :     LLVMBuildRetVoid(g->builder);
    5545                 :            : 
    5546                 :        440 :     LLVMPositionBuilderAtEnd(g->builder, instruction->begin->resume_bb);
    5547                 :        440 :     render_async_var_decls(g, instruction->base.scope);
    5548                 :        440 :     return nullptr;
    5549                 :            : }
    5550                 :            : 
    5551                 :        992 : static LLVMValueRef gen_await_early_return(CodeGen *g, IrInstruction *source_instr,
    5552                 :            :         LLVMValueRef target_frame_ptr, ZigType *result_type, ZigType *ptr_result_type,
    5553                 :            :         LLVMValueRef result_loc, bool non_async)
    5554                 :            : {
    5555                 :        992 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    5556                 :        992 :     LLVMValueRef their_result_ptr = nullptr;
    5557 [ +  + ][ +  + ]:        992 :     if (type_has_bits(result_type) && (non_async || result_loc != nullptr)) {
         [ +  + ][ +  + ]
    5558                 :        928 :         LLVMValueRef their_result_ptr_ptr = LLVMBuildStructGEP(g->builder, target_frame_ptr, frame_ret_start, "");
    5559                 :        928 :         their_result_ptr = LLVMBuildLoad(g->builder, their_result_ptr_ptr, "");
    5560         [ +  + ]:        928 :         if (result_loc != nullptr) {
    5561                 :        896 :             LLVMTypeRef ptr_u8 = LLVMPointerType(LLVMInt8Type(), 0);
    5562                 :        896 :             LLVMValueRef dest_ptr_casted = LLVMBuildBitCast(g->builder, result_loc, ptr_u8, "");
    5563                 :        896 :             LLVMValueRef src_ptr_casted = LLVMBuildBitCast(g->builder, their_result_ptr, ptr_u8, "");
    5564                 :        896 :             bool is_volatile = false;
    5565                 :        896 :             uint32_t abi_align = get_abi_alignment(g, result_type);
    5566                 :        896 :             LLVMValueRef byte_count_val = LLVMConstInt(usize_type_ref, type_size(g, result_type), false);
    5567                 :        928 :             ZigLLVMBuildMemCpy(g->builder,
    5568                 :            :                     dest_ptr_casted, abi_align,
    5569                 :            :                     src_ptr_casted, abi_align, byte_count_val, is_volatile);
    5570                 :            :         }
    5571                 :            :     }
    5572         [ +  + ]:        992 :     if (codegen_fn_has_err_ret_tracing_arg(g, result_type)) {
    5573                 :        904 :         LLVMValueRef their_trace_ptr_ptr = LLVMBuildStructGEP(g->builder, target_frame_ptr,
    5574                 :        904 :                 frame_index_trace_arg(g, result_type), "");
    5575                 :        904 :         LLVMValueRef src_trace_ptr = LLVMBuildLoad(g->builder, their_trace_ptr_ptr, "");
    5576                 :        904 :         LLVMValueRef dest_trace_ptr = get_cur_err_ret_trace_val(g, source_instr->scope);
    5577                 :        904 :         LLVMValueRef args[] = { dest_trace_ptr, src_trace_ptr };
    5578                 :        904 :         ZigLLVMBuildCall(g->builder, get_merge_err_ret_traces_fn_val(g), args, 2,
    5579                 :        904 :                 get_llvm_cc(g, CallingConventionUnspecified), ZigLLVM_FnInlineAuto, "");
    5580                 :            :     }
    5581 [ +  + ][ +  - ]:        992 :     if (non_async && type_has_bits(result_type)) {
                 [ +  + ]
    5582         [ +  + ]:        440 :         LLVMValueRef result_ptr = (result_loc == nullptr) ? their_result_ptr : result_loc;
    5583                 :        440 :         return get_handle_value(g, result_ptr, result_type, ptr_result_type);
    5584                 :            :     } else {
    5585                 :        552 :         return nullptr;
    5586                 :            :     }
    5587                 :            : }
    5588                 :            : 
    5589                 :        992 : static LLVMValueRef ir_render_await(CodeGen *g, IrExecutable *executable, IrInstructionAwaitGen *instruction) {
    5590                 :        992 :     LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    5591                 :        992 :     LLVMValueRef zero = LLVMConstNull(usize_type_ref);
    5592                 :        992 :     LLVMValueRef target_frame_ptr = ir_llvm_value(g, instruction->frame);
    5593                 :        992 :     ZigType *result_type = instruction->base.value.type;
    5594                 :        992 :     ZigType *ptr_result_type = get_pointer_to_type(g, result_type, true);
    5595                 :            : 
    5596         [ +  + ]:        992 :     LLVMValueRef result_loc = (instruction->result_loc == nullptr) ?
    5597                 :       1960 :         nullptr : ir_llvm_value(g, instruction->result_loc);
    5598                 :            : 
    5599 [ +  + ][ +  + ]:        992 :     if (instruction->target_fn != nullptr && !fn_is_async(instruction->target_fn)) {
                 [ +  + ]
    5600                 :        440 :         return gen_await_early_return(g, &instruction->base, target_frame_ptr, result_type,
    5601                 :        440 :                 ptr_result_type, result_loc, true);
    5602                 :            :     }
    5603                 :            : 
    5604                 :            :     // Prepare to be suspended
    5605                 :        552 :     LLVMBasicBlockRef resume_bb = gen_suspend_begin(g, "AwaitResume");
    5606                 :        552 :     LLVMBasicBlockRef end_bb = LLVMAppendBasicBlock(g->cur_fn_val, "AwaitEnd");
    5607                 :            : 
    5608                 :            :     // At this point resuming the function will continue from resume_bb.
    5609                 :            :     // This code is as if it is running inside the suspend block.
    5610                 :            : 
    5611                 :            : 
    5612                 :            :     // supply the awaiter return pointer
    5613         [ +  + ]:        552 :     if (type_has_bits(result_type)) {
    5614                 :        528 :         LLVMValueRef awaiter_ret_ptr_ptr = LLVMBuildStructGEP(g->builder, target_frame_ptr, frame_ret_start + 1, "");
    5615         [ +  + ]:        528 :         if (result_loc == nullptr) {
    5616                 :            :             // no copy needed
    5617                 :         40 :             LLVMBuildStore(g->builder, LLVMConstNull(LLVMGetElementType(LLVMTypeOf(awaiter_ret_ptr_ptr))),
    5618                 :            :                     awaiter_ret_ptr_ptr);
    5619                 :            :         } else {
    5620                 :        528 :             LLVMBuildStore(g->builder, result_loc, awaiter_ret_ptr_ptr);
    5621                 :            :         }
    5622                 :            :     }
    5623                 :            : 
    5624                 :            :     // supply the error return trace pointer
    5625         [ +  + ]:        552 :     if (codegen_fn_has_err_ret_tracing_arg(g, result_type)) {
    5626                 :        472 :         LLVMValueRef my_err_ret_trace_val = get_cur_err_ret_trace_val(g, instruction->base.scope);
    5627                 :        472 :         assert(my_err_ret_trace_val != nullptr);
    5628                 :        472 :         LLVMValueRef err_ret_trace_ptr_ptr = LLVMBuildStructGEP(g->builder, target_frame_ptr,
    5629                 :        472 :                 frame_index_trace_arg(g, result_type) + 1, "");
    5630                 :        472 :         LLVMBuildStore(g->builder, my_err_ret_trace_val, err_ret_trace_ptr_ptr);
    5631                 :            :     }
    5632                 :            : 
    5633                 :            :     // caller's own frame pointer
    5634                 :        552 :     LLVMValueRef awaiter_init_val = LLVMBuildPtrToInt(g->builder, g->cur_frame_ptr, usize_type_ref, "");
    5635                 :        552 :     LLVMValueRef awaiter_ptr = LLVMBuildStructGEP(g->builder, target_frame_ptr, frame_awaiter_index, "");
    5636                 :            :     LLVMValueRef prev_val = gen_maybe_atomic_op(g, LLVMAtomicRMWBinOpXchg, awaiter_ptr, awaiter_init_val,
    5637                 :        552 :             LLVMAtomicOrderingRelease);
    5638                 :            : 
    5639                 :        552 :     LLVMBasicBlockRef bad_await_block = LLVMAppendBasicBlock(g->cur_fn_val, "BadAwait");
    5640                 :        552 :     LLVMBasicBlockRef complete_suspend_block = LLVMAppendBasicBlock(g->cur_fn_val, "CompleteSuspend");
    5641                 :        552 :     LLVMBasicBlockRef early_return_block = LLVMAppendBasicBlock(g->cur_fn_val, "EarlyReturn");
    5642                 :            : 
    5643                 :        552 :     LLVMValueRef all_ones = LLVMConstAllOnes(usize_type_ref);
    5644                 :        552 :     LLVMValueRef switch_instr = LLVMBuildSwitch(g->builder, prev_val, bad_await_block, 2);
    5645                 :            : 
    5646                 :        552 :     LLVMAddCase(switch_instr, zero, complete_suspend_block);
    5647                 :        552 :     LLVMAddCase(switch_instr, all_ones, early_return_block);
    5648                 :            : 
    5649                 :            :     // We discovered that another awaiter was already here.
    5650                 :        552 :     LLVMPositionBuilderAtEnd(g->builder, bad_await_block);
    5651                 :        552 :     gen_assertion(g, PanicMsgIdBadAwait, &instruction->base);
    5652                 :            : 
    5653                 :            :     // Rely on the target to resume us from suspension.
    5654                 :        552 :     LLVMPositionBuilderAtEnd(g->builder, complete_suspend_block);
    5655                 :        552 :     LLVMBuildRetVoid(g->builder);
    5656                 :            : 
    5657                 :            :     // Early return: The async function has already completed. We must copy the result and
    5658                 :            :     // the error return trace if applicable.
    5659                 :        552 :     LLVMPositionBuilderAtEnd(g->builder, early_return_block);
    5660                 :        552 :     gen_await_early_return(g, &instruction->base, target_frame_ptr, result_type, ptr_result_type,
    5661                 :            :             result_loc, false);
    5662                 :        552 :     LLVMBuildBr(g->builder, end_bb);
    5663                 :            : 
    5664                 :        552 :     LLVMPositionBuilderAtEnd(g->builder, resume_bb);
    5665                 :        552 :     gen_assert_resume_id(g, &instruction->base, ResumeIdReturn, PanicMsgIdResumedAnAwaitingFn, nullptr);
    5666                 :        552 :     LLVMBuildBr(g->builder, end_bb);
    5667                 :            : 
    5668                 :        552 :     LLVMPositionBuilderAtEnd(g->builder, end_bb);
    5669 [ +  + ][ +  + ]:        552 :     if (type_has_bits(result_type) && result_loc != nullptr) {
                 [ +  + ]
    5670                 :        488 :         return get_handle_value(g, result_loc, result_type, ptr_result_type);
    5671                 :            :     }
    5672                 :         64 :     return nullptr;
    5673                 :            : }
    5674                 :            : 
    5675                 :        432 : static LLVMValueRef ir_render_resume(CodeGen *g, IrExecutable *executable, IrInstructionResume *instruction) {
    5676                 :        432 :     LLVMValueRef frame = ir_llvm_value(g, instruction->frame);
    5677                 :        432 :     ZigType *frame_type = instruction->frame->value.type;
    5678                 :        432 :     assert(frame_type->id == ZigTypeIdAnyFrame);
    5679                 :            : 
    5680                 :        432 :     gen_resume(g, nullptr, frame, ResumeIdManual);
    5681                 :        432 :     return nullptr;
    5682                 :            : }
    5683                 :            : 
    5684                 :         16 : static LLVMValueRef ir_render_frame_size(CodeGen *g, IrExecutable *executable,
    5685                 :            :         IrInstructionFrameSizeGen *instruction)
    5686                 :            : {
    5687                 :         16 :     LLVMValueRef fn_val = ir_llvm_value(g, instruction->fn);
    5688                 :         16 :     return gen_frame_size(g, fn_val);
    5689                 :            : }
    5690                 :            : 
    5691                 :       5396 : static LLVMValueRef ir_render_spill_begin(CodeGen *g, IrExecutable *executable,
    5692                 :            :         IrInstructionSpillBegin *instruction)
    5693                 :            : {
    5694         [ +  + ]:       5396 :     if (!fn_is_async(g->cur_fn))
    5695                 :       5028 :         return nullptr;
    5696                 :            : 
    5697      [ -  +  - ]:        368 :     switch (instruction->spill_id) {
    5698                 :          0 :         case SpillIdInvalid:
    5699                 :          0 :             zig_unreachable();
    5700                 :        368 :         case SpillIdRetErrCode: {
    5701                 :        368 :             LLVMValueRef operand = ir_llvm_value(g, instruction->operand);
    5702                 :        368 :             LLVMValueRef ptr = ir_llvm_value(g, g->cur_fn->err_code_spill);
    5703                 :        368 :             LLVMBuildStore(g->builder, operand, ptr);
    5704                 :        368 :             return nullptr;
    5705                 :            :         }
    5706                 :            : 
    5707                 :            :     }
    5708                 :          0 :     zig_unreachable();
    5709                 :            : }
    5710                 :            : 
    5711                 :       3214 : static LLVMValueRef ir_render_spill_end(CodeGen *g, IrExecutable *executable, IrInstructionSpillEnd *instruction) {
    5712         [ +  + ]:       3214 :     if (!fn_is_async(g->cur_fn))
    5713                 :       3014 :         return ir_llvm_value(g, instruction->begin->operand);
    5714                 :            : 
    5715      [ -  +  - ]:        200 :     switch (instruction->begin->spill_id) {
    5716                 :          0 :         case SpillIdInvalid:
    5717                 :          0 :             zig_unreachable();
    5718                 :        200 :         case SpillIdRetErrCode: {
    5719                 :        200 :             LLVMValueRef ptr = ir_llvm_value(g, g->cur_fn->err_code_spill);
    5720                 :        200 :             return LLVMBuildLoad(g->builder, ptr, "");
    5721                 :            :         }
    5722                 :            : 
    5723                 :            :     }
    5724                 :          0 :     zig_unreachable();
    5725                 :            : }
    5726                 :            : 
    5727                 :     575600 : static void set_debug_location(CodeGen *g, IrInstruction *instruction) {
    5728                 :     575600 :     AstNode *source_node = instruction->source_node;
    5729                 :     575600 :     Scope *scope = instruction->scope;
    5730                 :            : 
    5731                 :     575600 :     assert(source_node);
    5732                 :     575600 :     assert(scope);
    5733                 :            : 
    5734                 :     575600 :     ZigLLVMSetCurrentDebugLocation(g->builder, (int)source_node->line + 1,
    5735                 :     575600 :             (int)source_node->column + 1, get_di_scope(g, scope));
    5736                 :     575600 : }
    5737                 :            : 
    5738                 :     575600 : static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, IrInstruction *instruction) {
    5739   [ -  +  +  +  :     575600 :     switch (instruction->id) {
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
                      - ]
    5740                 :          0 :         case IrInstructionIdInvalid:
    5741                 :            :         case IrInstructionIdConst:
    5742                 :            :         case IrInstructionIdTypeOf:
    5743                 :            :         case IrInstructionIdFieldPtr:
    5744                 :            :         case IrInstructionIdSetCold:
    5745                 :            :         case IrInstructionIdSetRuntimeSafety:
    5746                 :            :         case IrInstructionIdSetFloatMode:
    5747                 :            :         case IrInstructionIdArrayType:
    5748                 :            :         case IrInstructionIdAnyFrameType:
    5749                 :            :         case IrInstructionIdSliceType:
    5750                 :            :         case IrInstructionIdSizeOf:
    5751                 :            :         case IrInstructionIdSwitchTarget:
    5752                 :            :         case IrInstructionIdContainerInitFields:
    5753                 :            :         case IrInstructionIdCompileErr:
    5754                 :            :         case IrInstructionIdCompileLog:
    5755                 :            :         case IrInstructionIdImport:
    5756                 :            :         case IrInstructionIdCImport:
    5757                 :            :         case IrInstructionIdCInclude:
    5758                 :            :         case IrInstructionIdCDefine:
    5759                 :            :         case IrInstructionIdCUndef:
    5760                 :            :         case IrInstructionIdEmbedFile:
    5761                 :            :         case IrInstructionIdIntType:
    5762                 :            :         case IrInstructionIdVectorType:
    5763                 :            :         case IrInstructionIdMemberCount:
    5764                 :            :         case IrInstructionIdMemberType:
    5765                 :            :         case IrInstructionIdMemberName:
    5766                 :            :         case IrInstructionIdAlignOf:
    5767                 :            :         case IrInstructionIdFnProto:
    5768                 :            :         case IrInstructionIdTestComptime:
    5769                 :            :         case IrInstructionIdCheckSwitchProngs:
    5770                 :            :         case IrInstructionIdCheckStatementIsVoid:
    5771                 :            :         case IrInstructionIdTypeName:
    5772                 :            :         case IrInstructionIdDeclRef:
    5773                 :            :         case IrInstructionIdSwitchVar:
    5774                 :            :         case IrInstructionIdSwitchElseVar:
    5775                 :            :         case IrInstructionIdByteOffsetOf:
    5776                 :            :         case IrInstructionIdBitOffsetOf:
    5777                 :            :         case IrInstructionIdTypeInfo:
    5778                 :            :         case IrInstructionIdType:
    5779                 :            :         case IrInstructionIdHasField:
    5780                 :            :         case IrInstructionIdTypeId:
    5781                 :            :         case IrInstructionIdSetEvalBranchQuota:
    5782                 :            :         case IrInstructionIdPtrType:
    5783                 :            :         case IrInstructionIdOpaqueType:
    5784                 :            :         case IrInstructionIdSetAlignStack:
    5785                 :            :         case IrInstructionIdArgType:
    5786                 :            :         case IrInstructionIdTagType:
    5787                 :            :         case IrInstructionIdExport:
    5788                 :            :         case IrInstructionIdErrorUnion:
    5789                 :            :         case IrInstructionIdAddImplicitReturnType:
    5790                 :            :         case IrInstructionIdIntCast:
    5791                 :            :         case IrInstructionIdFloatCast:
    5792                 :            :         case IrInstructionIdIntToFloat:
    5793                 :            :         case IrInstructionIdFloatToInt:
    5794                 :            :         case IrInstructionIdBoolToInt:
    5795                 :            :         case IrInstructionIdErrSetCast:
    5796                 :            :         case IrInstructionIdFromBytes:
    5797                 :            :         case IrInstructionIdToBytes:
    5798                 :            :         case IrInstructionIdEnumToInt:
    5799                 :            :         case IrInstructionIdCheckRuntimeScope:
    5800                 :            :         case IrInstructionIdDeclVarSrc:
    5801                 :            :         case IrInstructionIdPtrCastSrc:
    5802                 :            :         case IrInstructionIdCmpxchgSrc:
    5803                 :            :         case IrInstructionIdLoadPtr:
    5804                 :            :         case IrInstructionIdGlobalAsm:
    5805                 :            :         case IrInstructionIdHasDecl:
    5806                 :            :         case IrInstructionIdUndeclaredIdent:
    5807                 :            :         case IrInstructionIdCallSrc:
    5808                 :            :         case IrInstructionIdAllocaSrc:
    5809                 :            :         case IrInstructionIdEndExpr:
    5810                 :            :         case IrInstructionIdImplicitCast:
    5811                 :            :         case IrInstructionIdResolveResult:
    5812                 :            :         case IrInstructionIdResetResult:
    5813                 :            :         case IrInstructionIdContainerInitList:
    5814                 :            :         case IrInstructionIdSliceSrc:
    5815                 :            :         case IrInstructionIdRef:
    5816                 :            :         case IrInstructionIdBitCastSrc:
    5817                 :            :         case IrInstructionIdTestErrSrc:
    5818                 :            :         case IrInstructionIdUnionInitNamedField:
    5819                 :            :         case IrInstructionIdFrameType:
    5820                 :            :         case IrInstructionIdFrameSizeSrc:
    5821                 :            :         case IrInstructionIdAllocaGen:
    5822                 :            :         case IrInstructionIdAwaitSrc:
    5823                 :          0 :             zig_unreachable();
    5824                 :            : 
    5825                 :      25280 :         case IrInstructionIdDeclVarGen:
    5826                 :      25280 :             return ir_render_decl_var(g, executable, (IrInstructionDeclVarGen *)instruction);
    5827                 :      34141 :         case IrInstructionIdReturn:
    5828                 :      34141 :             return ir_render_return(g, executable, (IrInstructionReturn *)instruction);
    5829                 :      34164 :         case IrInstructionIdBinOp:
    5830                 :      34164 :             return ir_render_bin_op(g, executable, (IrInstructionBinOp *)instruction);
    5831                 :       6343 :         case IrInstructionIdCast:
    5832                 :       6343 :             return ir_render_cast(g, executable, (IrInstructionCast *)instruction);
    5833                 :        942 :         case IrInstructionIdUnreachable:
    5834                 :        942 :             return ir_render_unreachable(g, executable, (IrInstructionUnreachable *)instruction);
    5835                 :      20951 :         case IrInstructionIdCondBr:
    5836                 :      20951 :             return ir_render_cond_br(g, executable, (IrInstructionCondBr *)instruction);
    5837                 :      28010 :         case IrInstructionIdBr:
    5838                 :      28010 :             return ir_render_br(g, executable, (IrInstructionBr *)instruction);
    5839                 :        241 :         case IrInstructionIdUnOp:
    5840                 :        241 :             return ir_render_un_op(g, executable, (IrInstructionUnOp *)instruction);
    5841                 :     117989 :         case IrInstructionIdLoadPtrGen:
    5842                 :     117989 :             return ir_render_load_ptr(g, executable, (IrInstructionLoadPtrGen *)instruction);
    5843                 :      37122 :         case IrInstructionIdStorePtr:
    5844                 :      37122 :             return ir_render_store_ptr(g, executable, (IrInstructionStorePtr *)instruction);
    5845                 :     103697 :         case IrInstructionIdVarPtr:
    5846                 :     103697 :             return ir_render_var_ptr(g, executable, (IrInstructionVarPtr *)instruction);
    5847                 :       5391 :         case IrInstructionIdReturnPtr:
    5848                 :       5391 :             return ir_render_return_ptr(g, executable, (IrInstructionReturnPtr *)instruction);
    5849                 :       6508 :         case IrInstructionIdElemPtr:
    5850                 :       6508 :             return ir_render_elem_ptr(g, executable, (IrInstructionElemPtr *)instruction);
    5851                 :      45715 :         case IrInstructionIdCallGen:
    5852                 :      45715 :             return ir_render_call(g, executable, (IrInstructionCallGen *)instruction);
    5853                 :      22444 :         case IrInstructionIdStructFieldPtr:
    5854                 :      22444 :             return ir_render_struct_field_ptr(g, executable, (IrInstructionStructFieldPtr *)instruction);
    5855                 :       1462 :         case IrInstructionIdUnionFieldPtr:
    5856                 :       1462 :             return ir_render_union_field_ptr(g, executable, (IrInstructionUnionFieldPtr *)instruction);
    5857                 :        121 :         case IrInstructionIdAsm:
    5858                 :        121 :             return ir_render_asm(g, executable, (IrInstructionAsm *)instruction);
    5859                 :       1383 :         case IrInstructionIdTestNonNull:
    5860                 :       1383 :             return ir_render_test_non_null(g, executable, (IrInstructionTestNonNull *)instruction);
    5861                 :       1757 :         case IrInstructionIdOptionalUnwrapPtr:
    5862                 :       1757 :             return ir_render_optional_unwrap_ptr(g, executable, (IrInstructionOptionalUnwrapPtr *)instruction);
    5863                 :        182 :         case IrInstructionIdClz:
    5864                 :        182 :             return ir_render_clz(g, executable, (IrInstructionClz *)instruction);
    5865                 :         40 :         case IrInstructionIdCtz:
    5866                 :         40 :             return ir_render_ctz(g, executable, (IrInstructionCtz *)instruction);
    5867                 :         65 :         case IrInstructionIdPopCount:
    5868                 :         65 :             return ir_render_pop_count(g, executable, (IrInstructionPopCount *)instruction);
    5869                 :        898 :         case IrInstructionIdSwitchBr:
    5870                 :        898 :             return ir_render_switch_br(g, executable, (IrInstructionSwitchBr *)instruction);
    5871                 :         28 :         case IrInstructionIdBswap:
    5872                 :         28 :             return ir_render_bswap(g, executable, (IrInstructionBswap *)instruction);
    5873                 :        112 :         case IrInstructionIdBitReverse:
    5874                 :        112 :             return ir_render_bit_reverse(g, executable, (IrInstructionBitReverse *)instruction);
    5875                 :       1446 :         case IrInstructionIdPhi:
    5876                 :       1446 :             return ir_render_phi(g, executable, (IrInstructionPhi *)instruction);
    5877                 :      10685 :         case IrInstructionIdRefGen:
    5878                 :      10685 :             return ir_render_ref(g, executable, (IrInstructionRefGen *)instruction);
    5879                 :        335 :         case IrInstructionIdErrName:
    5880                 :        335 :             return ir_render_err_name(g, executable, (IrInstructionErrName *)instruction);
    5881                 :         63 :         case IrInstructionIdCmpxchgGen:
    5882                 :         63 :             return ir_render_cmpxchg(g, executable, (IrInstructionCmpxchgGen *)instruction);
    5883                 :          8 :         case IrInstructionIdFence:
    5884                 :          8 :             return ir_render_fence(g, executable, (IrInstructionFence *)instruction);
    5885                 :        346 :         case IrInstructionIdTruncate:
    5886                 :        346 :             return ir_render_truncate(g, executable, (IrInstructionTruncate *)instruction);
    5887                 :       1384 :         case IrInstructionIdBoolNot:
    5888                 :       1384 :             return ir_render_bool_not(g, executable, (IrInstructionBoolNot *)instruction);
    5889                 :        280 :         case IrInstructionIdMemset:
    5890                 :        280 :             return ir_render_memset(g, executable, (IrInstructionMemset *)instruction);
    5891                 :         61 :         case IrInstructionIdMemcpy:
    5892                 :         61 :             return ir_render_memcpy(g, executable, (IrInstructionMemcpy *)instruction);
    5893                 :       3633 :         case IrInstructionIdSliceGen:
    5894                 :       3633 :             return ir_render_slice(g, executable, (IrInstructionSliceGen *)instruction);
    5895                 :          2 :         case IrInstructionIdBreakpoint:
    5896                 :          2 :             return ir_render_breakpoint(g, executable, (IrInstructionBreakpoint *)instruction);
    5897                 :        126 :         case IrInstructionIdReturnAddress:
    5898                 :        126 :             return ir_render_return_address(g, executable, (IrInstructionReturnAddress *)instruction);
    5899                 :          7 :         case IrInstructionIdFrameAddress:
    5900                 :          7 :             return ir_render_frame_address(g, executable, (IrInstructionFrameAddress *)instruction);
    5901                 :        320 :         case IrInstructionIdFrameHandle:
    5902                 :        320 :             return ir_render_handle(g, executable, (IrInstructionFrameHandle *)instruction);
    5903                 :         83 :         case IrInstructionIdOverflowOp:
    5904                 :         83 :             return ir_render_overflow_op(g, executable, (IrInstructionOverflowOp *)instruction);
    5905                 :      10272 :         case IrInstructionIdTestErrGen:
    5906                 :      10272 :             return ir_render_test_err(g, executable, (IrInstructionTestErrGen *)instruction);
    5907                 :       8877 :         case IrInstructionIdUnwrapErrCode:
    5908                 :       8877 :             return ir_render_unwrap_err_code(g, executable, (IrInstructionUnwrapErrCode *)instruction);
    5909                 :       7193 :         case IrInstructionIdUnwrapErrPayload:
    5910                 :       7193 :             return ir_render_unwrap_err_payload(g, executable, (IrInstructionUnwrapErrPayload *)instruction);
    5911                 :        267 :         case IrInstructionIdOptionalWrap:
    5912                 :        267 :             return ir_render_optional_wrap(g, executable, (IrInstructionOptionalWrap *)instruction);
    5913                 :       3337 :         case IrInstructionIdErrWrapCode:
    5914                 :       3337 :             return ir_render_err_wrap_code(g, executable, (IrInstructionErrWrapCode *)instruction);
    5915                 :        186 :         case IrInstructionIdErrWrapPayload:
    5916                 :        186 :             return ir_render_err_wrap_payload(g, executable, (IrInstructionErrWrapPayload *)instruction);
    5917                 :        273 :         case IrInstructionIdUnionTag:
    5918                 :        273 :             return ir_render_union_tag(g, executable, (IrInstructionUnionTag *)instruction);
    5919                 :        984 :         case IrInstructionIdPtrCastGen:
    5920                 :        984 :             return ir_render_ptr_cast(g, executable, (IrInstructionPtrCastGen *)instruction);
    5921                 :       1345 :         case IrInstructionIdBitCastGen:
    5922                 :       1345 :             return ir_render_bit_cast(g, executable, (IrInstructionBitCastGen *)instruction);
    5923                 :       5231 :         case IrInstructionIdWidenOrShorten:
    5924                 :       5231 :             return ir_render_widen_or_shorten(g, executable, (IrInstructionWidenOrShorten *)instruction);
    5925                 :        700 :         case IrInstructionIdPtrToInt:
    5926                 :        700 :             return ir_render_ptr_to_int(g, executable, (IrInstructionPtrToInt *)instruction);
    5927                 :        431 :         case IrInstructionIdIntToPtr:
    5928                 :        431 :             return ir_render_int_to_ptr(g, executable, (IrInstructionIntToPtr *)instruction);
    5929                 :         10 :         case IrInstructionIdIntToEnum:
    5930                 :         10 :             return ir_render_int_to_enum(g, executable, (IrInstructionIntToEnum *)instruction);
    5931                 :          9 :         case IrInstructionIdIntToErr:
    5932                 :          9 :             return ir_render_int_to_err(g, executable, (IrInstructionIntToErr *)instruction);
    5933                 :          9 :         case IrInstructionIdErrToInt:
    5934                 :          9 :             return ir_render_err_to_int(g, executable, (IrInstructionErrToInt *)instruction);
    5935                 :        289 :         case IrInstructionIdPanic:
    5936                 :        289 :             return ir_render_panic(g, executable, (IrInstructionPanic *)instruction);
    5937                 :         36 :         case IrInstructionIdTagName:
    5938                 :         36 :             return ir_render_enum_tag_name(g, executable, (IrInstructionTagName *)instruction);
    5939                 :        107 :         case IrInstructionIdFieldParentPtr:
    5940                 :        107 :             return ir_render_field_parent_ptr(g, executable, (IrInstructionFieldParentPtr *)instruction);
    5941                 :        142 :         case IrInstructionIdAlignCast:
    5942                 :        142 :             return ir_render_align_cast(g, executable, (IrInstructionAlignCast *)instruction);
    5943                 :         17 :         case IrInstructionIdErrorReturnTrace:
    5944                 :         17 :             return ir_render_error_return_trace(g, executable, (IrInstructionErrorReturnTrace *)instruction);
    5945                 :        156 :         case IrInstructionIdAtomicRmw:
    5946                 :        156 :             return ir_render_atomic_rmw(g, executable, (IrInstructionAtomicRmw *)instruction);
    5947                 :         12 :         case IrInstructionIdAtomicLoad:
    5948                 :         12 :             return ir_render_atomic_load(g, executable, (IrInstructionAtomicLoad *)instruction);
    5949                 :       9986 :         case IrInstructionIdSaveErrRetAddr:
    5950                 :       9986 :             return ir_render_save_err_ret_addr(g, executable, (IrInstructionSaveErrRetAddr *)instruction);
    5951                 :        264 :         case IrInstructionIdFloatOp:
    5952                 :        264 :             return ir_render_float_op(g, executable, (IrInstructionFloatOp *)instruction);
    5953                 :         24 :         case IrInstructionIdMulAdd:
    5954                 :         24 :             return ir_render_mul_add(g, executable, (IrInstructionMulAdd *)instruction);
    5955                 :          8 :         case IrInstructionIdArrayToVector:
    5956                 :          8 :             return ir_render_array_to_vector(g, executable, (IrInstructionArrayToVector *)instruction);
    5957                 :        144 :         case IrInstructionIdVectorToArray:
    5958                 :        144 :             return ir_render_vector_to_array(g, executable, (IrInstructionVectorToArray *)instruction);
    5959                 :         32 :         case IrInstructionIdAssertZero:
    5960                 :         32 :             return ir_render_assert_zero(g, executable, (IrInstructionAssertZero *)instruction);
    5961                 :          8 :         case IrInstructionIdAssertNonNull:
    5962                 :          8 :             return ir_render_assert_non_null(g, executable, (IrInstructionAssertNonNull *)instruction);
    5963                 :        406 :         case IrInstructionIdResizeSlice:
    5964                 :        406 :             return ir_render_resize_slice(g, executable, (IrInstructionResizeSlice *)instruction);
    5965                 :        142 :         case IrInstructionIdPtrOfArrayToSlice:
    5966                 :        142 :             return ir_render_ptr_of_array_to_slice(g, executable, (IrInstructionPtrOfArrayToSlice *)instruction);
    5967                 :        448 :         case IrInstructionIdSuspendBegin:
    5968                 :        448 :             return ir_render_suspend_begin(g, executable, (IrInstructionSuspendBegin *)instruction);
    5969                 :        440 :         case IrInstructionIdSuspendFinish:
    5970                 :        440 :             return ir_render_suspend_finish(g, executable, (IrInstructionSuspendFinish *)instruction);
    5971                 :        432 :         case IrInstructionIdResume:
    5972                 :        432 :             return ir_render_resume(g, executable, (IrInstructionResume *)instruction);
    5973                 :         16 :         case IrInstructionIdFrameSizeGen:
    5974                 :         16 :             return ir_render_frame_size(g, executable, (IrInstructionFrameSizeGen *)instruction);
    5975                 :        992 :         case IrInstructionIdAwaitGen:
    5976                 :        992 :             return ir_render_await(g, executable, (IrInstructionAwaitGen *)instruction);
    5977                 :       5396 :         case IrInstructionIdSpillBegin:
    5978                 :       5396 :             return ir_render_spill_begin(g, executable, (IrInstructionSpillBegin *)instruction);
    5979                 :       3214 :         case IrInstructionIdSpillEnd:
    5980                 :       3214 :             return ir_render_spill_end(g, executable, (IrInstructionSpillEnd *)instruction);
    5981                 :            :     }
    5982                 :          0 :     zig_unreachable();
    5983                 :            : }
    5984                 :            : 
    5985                 :      24304 : static void ir_render(CodeGen *g, ZigFn *fn_entry) {
    5986                 :      24304 :     assert(fn_entry);
    5987                 :            : 
    5988                 :      24304 :     IrExecutable *executable = &fn_entry->analyzed_executable;
    5989                 :      24304 :     assert(executable->basic_block_list.length > 0);
    5990                 :            : 
    5991         [ +  + ]:     110543 :     for (size_t block_i = 0; block_i < executable->basic_block_list.length; block_i += 1) {
    5992                 :      86239 :         IrBasicBlock *current_block = executable->basic_block_list.at(block_i);
    5993         [ +  + ]:      86239 :         if (get_scope_typeof(current_block->scope) != nullptr) {
    5994                 :         24 :             LLVMBuildBr(g->builder, current_block->llvm_block);
    5995                 :            :         }
    5996                 :      86239 :         assert(current_block->llvm_block);
    5997                 :      86239 :         LLVMPositionBuilderAtEnd(g->builder, current_block->llvm_block);
    5998         [ +  + ]:     899146 :         for (size_t instr_i = 0; instr_i < current_block->instruction_list.length; instr_i += 1) {
    5999                 :     812907 :             IrInstruction *instruction = current_block->instruction_list.at(instr_i);
    6000 [ +  + ][ +  + ]:     812907 :             if (instruction->ref_count == 0 && !ir_has_side_effects(instruction))
                 [ +  + ]
    6001                 :     234477 :                 continue;
    6002         [ +  + ]:     578430 :             if (get_scope_typeof(instruction->scope) != nullptr)
    6003                 :       2830 :                 continue;
    6004                 :            : 
    6005         [ +  - ]:     575600 :             if (!g->strip_debug_symbols) {
    6006                 :     575600 :                 set_debug_location(g, instruction);
    6007                 :            :             }
    6008                 :     575600 :             instruction->llvm_value = ir_render_instruction(g, executable, instruction);
    6009                 :            :         }
    6010                 :      86239 :         current_block->llvm_exit_block = LLVMGetInsertBlock(g->builder);
    6011                 :            :     }
    6012                 :      24304 : }
    6013                 :            : 
    6014                 :            : static LLVMValueRef gen_const_ptr_struct_recursive(CodeGen *g, ConstExprValue *struct_const_val, size_t field_index);
    6015                 :            : static LLVMValueRef gen_const_ptr_array_recursive(CodeGen *g, ConstExprValue *array_const_val, size_t index);
    6016                 :            : static LLVMValueRef gen_const_ptr_union_recursive(CodeGen *g, ConstExprValue *union_const_val);
    6017                 :            : static LLVMValueRef gen_const_ptr_err_union_code_recursive(CodeGen *g, ConstExprValue *err_union_const_val);
    6018                 :            : static LLVMValueRef gen_const_ptr_err_union_payload_recursive(CodeGen *g, ConstExprValue *err_union_const_val);
    6019                 :            : static LLVMValueRef gen_const_ptr_optional_payload_recursive(CodeGen *g, ConstExprValue *optional_const_val);
    6020                 :            : 
    6021                 :      16312 : static LLVMValueRef gen_parent_ptr(CodeGen *g, ConstExprValue *val, ConstParent *parent) {
    6022   [ +  +  -  -  :      16312 :     switch (parent->id) {
             -  +  -  +  
                      - ]
    6023                 :      16182 :         case ConstParentIdNone:
    6024                 :      16182 :             render_const_val(g, val, "");
    6025                 :      16182 :             render_const_val_global(g, val, "");
    6026                 :      16182 :             return val->global_refs->llvm_global;
    6027                 :         16 :         case ConstParentIdStruct:
    6028                 :         16 :             return gen_const_ptr_struct_recursive(g, parent->data.p_struct.struct_val,
    6029                 :         16 :                     parent->data.p_struct.field_index);
    6030                 :          0 :         case ConstParentIdErrUnionCode:
    6031                 :          0 :             return gen_const_ptr_err_union_code_recursive(g, parent->data.p_err_union_code.err_union_val);
    6032                 :          0 :         case ConstParentIdErrUnionPayload:
    6033                 :          0 :             return gen_const_ptr_err_union_payload_recursive(g, parent->data.p_err_union_payload.err_union_val);
    6034                 :          0 :         case ConstParentIdOptionalPayload:
    6035                 :          0 :             return gen_const_ptr_optional_payload_recursive(g, parent->data.p_optional_payload.optional_val);
    6036                 :         56 :         case ConstParentIdArray:
    6037                 :         56 :             return gen_const_ptr_array_recursive(g, parent->data.p_array.array_val,
    6038                 :         56 :                     parent->data.p_array.elem_index);
    6039                 :          0 :         case ConstParentIdUnion:
    6040                 :          0 :             return gen_const_ptr_union_recursive(g, parent->data.p_union.union_val);
    6041                 :         58 :         case ConstParentIdScalar:
    6042                 :         58 :             render_const_val(g, parent->data.p_scalar.scalar_val, "");
    6043                 :         58 :             render_const_val_global(g, parent->data.p_scalar.scalar_val, "");
    6044                 :         58 :             return parent->data.p_scalar.scalar_val->global_refs->llvm_global;
    6045                 :            :     }
    6046                 :          0 :     zig_unreachable();
    6047                 :            : }
    6048                 :            : 
    6049                 :      15934 : static LLVMValueRef gen_const_ptr_array_recursive(CodeGen *g, ConstExprValue *array_const_val, size_t index) {
    6050                 :      15934 :     expand_undef_array(g, array_const_val);
    6051                 :      15934 :     ConstParent *parent = &array_const_val->parent;
    6052                 :      15934 :     LLVMValueRef base_ptr = gen_parent_ptr(g, array_const_val, parent);
    6053                 :            : 
    6054                 :      15934 :     LLVMTypeKind el_type = LLVMGetTypeKind(LLVMGetElementType(LLVMTypeOf(base_ptr)));
    6055         [ +  + ]:      15934 :     if (el_type == LLVMArrayTypeKind) {
    6056                 :      15868 :         ZigType *usize = g->builtin_types.entry_usize;
    6057                 :            :         LLVMValueRef indices[] = {
    6058                 :      15868 :             LLVMConstNull(usize->llvm_type),
    6059                 :      15868 :             LLVMConstInt(usize->llvm_type, index, false),
    6060                 :      31736 :         };
    6061                 :      15868 :         return LLVMConstInBoundsGEP(base_ptr, indices, 2);
    6062         [ +  + ]:         66 :     } else if (el_type == LLVMStructTypeKind) {
    6063                 :          8 :         ZigType *u32 = g->builtin_types.entry_u32;
    6064                 :            :         LLVMValueRef indices[] = {
    6065                 :          8 :             LLVMConstNull(get_llvm_type(g, u32)),
    6066                 :          8 :             LLVMConstInt(get_llvm_type(g, u32), index, false),
    6067                 :         16 :         };
    6068                 :          8 :         return LLVMConstInBoundsGEP(base_ptr, indices, 2);
    6069                 :            :     } else {
    6070                 :         58 :         assert(parent->id == ConstParentIdScalar);
    6071                 :         58 :         return base_ptr;
    6072                 :            :     }
    6073                 :            : }
    6074                 :            : 
    6075                 :        378 : static LLVMValueRef gen_const_ptr_struct_recursive(CodeGen *g, ConstExprValue *struct_const_val, size_t field_index) {
    6076                 :        378 :     ConstParent *parent = &struct_const_val->parent;
    6077                 :        378 :     LLVMValueRef base_ptr = gen_parent_ptr(g, struct_const_val, parent);
    6078                 :            : 
    6079                 :        378 :     ZigType *u32 = g->builtin_types.entry_u32;
    6080                 :            :     LLVMValueRef indices[] = {
    6081                 :        378 :         LLVMConstNull(get_llvm_type(g, u32)),
    6082                 :        378 :         LLVMConstInt(get_llvm_type(g, u32), field_index, false),
    6083                 :        756 :     };
    6084                 :        378 :     return LLVMConstInBoundsGEP(base_ptr, indices, 2);
    6085                 :            : }
    6086                 :            : 
    6087                 :          0 : static LLVMValueRef gen_const_ptr_err_union_code_recursive(CodeGen *g, ConstExprValue *err_union_const_val) {
    6088                 :          0 :     ConstParent *parent = &err_union_const_val->parent;
    6089                 :          0 :     LLVMValueRef base_ptr = gen_parent_ptr(g, err_union_const_val, parent);
    6090                 :            : 
    6091                 :          0 :     ZigType *u32 = g->builtin_types.entry_u32;
    6092                 :            :     LLVMValueRef indices[] = {
    6093                 :          0 :         LLVMConstNull(get_llvm_type(g, u32)),
    6094                 :          0 :         LLVMConstInt(get_llvm_type(g, u32), err_union_err_index, false),
    6095                 :          0 :     };
    6096                 :          0 :     return LLVMConstInBoundsGEP(base_ptr, indices, 2);
    6097                 :            : }
    6098                 :            : 
    6099                 :          0 : static LLVMValueRef gen_const_ptr_err_union_payload_recursive(CodeGen *g, ConstExprValue *err_union_const_val) {
    6100                 :          0 :     ConstParent *parent = &err_union_const_val->parent;
    6101                 :          0 :     LLVMValueRef base_ptr = gen_parent_ptr(g, err_union_const_val, parent);
    6102                 :            : 
    6103                 :          0 :     ZigType *u32 = g->builtin_types.entry_u32;
    6104                 :            :     LLVMValueRef indices[] = {
    6105                 :          0 :         LLVMConstNull(get_llvm_type(g, u32)),
    6106                 :          0 :         LLVMConstInt(get_llvm_type(g, u32), err_union_payload_index, false),
    6107                 :          0 :     };
    6108                 :          0 :     return LLVMConstInBoundsGEP(base_ptr, indices, 2);
    6109                 :            : }
    6110                 :            : 
    6111                 :          0 : static LLVMValueRef gen_const_ptr_optional_payload_recursive(CodeGen *g, ConstExprValue *optional_const_val) {
    6112                 :          0 :     ConstParent *parent = &optional_const_val->parent;
    6113                 :          0 :     LLVMValueRef base_ptr = gen_parent_ptr(g, optional_const_val, parent);
    6114                 :            : 
    6115                 :          0 :     ZigType *u32 = g->builtin_types.entry_u32;
    6116                 :            :     LLVMValueRef indices[] = {
    6117                 :          0 :         LLVMConstNull(get_llvm_type(g, u32)),
    6118                 :          0 :         LLVMConstInt(get_llvm_type(g, u32), maybe_child_index, false),
    6119                 :          0 :     };
    6120                 :          0 :     return LLVMConstInBoundsGEP(base_ptr, indices, 2);
    6121                 :            : }
    6122                 :            : 
    6123                 :          0 : static LLVMValueRef gen_const_ptr_union_recursive(CodeGen *g, ConstExprValue *union_const_val) {
    6124                 :          0 :     ConstParent *parent = &union_const_val->parent;
    6125                 :          0 :     LLVMValueRef base_ptr = gen_parent_ptr(g, union_const_val, parent);
    6126                 :            : 
    6127                 :          0 :     ZigType *u32 = g->builtin_types.entry_u32;
    6128                 :            :     LLVMValueRef indices[] = {
    6129                 :          0 :         LLVMConstNull(get_llvm_type(g, u32)),
    6130                 :          0 :         LLVMConstInt(get_llvm_type(g, u32), 0, false), // TODO test const union with more aligned tag type than payload
    6131                 :          0 :     };
    6132                 :          0 :     return LLVMConstInBoundsGEP(base_ptr, indices, 2);
    6133                 :            : }
    6134                 :            : 
    6135                 :        336 : static LLVMValueRef pack_const_int(CodeGen *g, LLVMTypeRef big_int_type_ref, ConstExprValue *const_val) {
    6136   [ -  -  +  - ]:        336 :     switch (const_val->special) {
    6137                 :          0 :         case ConstValSpecialLazy:
    6138                 :            :         case ConstValSpecialRuntime:
    6139                 :          0 :             zig_unreachable();
    6140                 :          0 :         case ConstValSpecialUndef:
    6141                 :          0 :             return LLVMConstInt(big_int_type_ref, 0, false);
    6142                 :        336 :         case ConstValSpecialStatic:
    6143                 :        336 :             break;
    6144                 :            :     }
    6145                 :            : 
    6146                 :        336 :     ZigType *type_entry = const_val->type;
    6147                 :        336 :     assert(type_has_bits(type_entry));
    6148   [ -  +  +  +  :        336 :     switch (type_entry->id) {
          -  -  +  -  -  
             -  -  -  - ]
    6149                 :          0 :         case ZigTypeIdInvalid:
    6150                 :            :         case ZigTypeIdMetaType:
    6151                 :            :         case ZigTypeIdUnreachable:
    6152                 :            :         case ZigTypeIdComptimeFloat:
    6153                 :            :         case ZigTypeIdComptimeInt:
    6154                 :            :         case ZigTypeIdEnumLiteral:
    6155                 :            :         case ZigTypeIdUndefined:
    6156                 :            :         case ZigTypeIdNull:
    6157                 :            :         case ZigTypeIdErrorUnion:
    6158                 :            :         case ZigTypeIdErrorSet:
    6159                 :            :         case ZigTypeIdBoundFn:
    6160                 :            :         case ZigTypeIdArgTuple:
    6161                 :            :         case ZigTypeIdVoid:
    6162                 :            :         case ZigTypeIdOpaque:
    6163                 :          0 :             zig_unreachable();
    6164                 :          8 :         case ZigTypeIdBool:
    6165         [ +  - ]:          8 :             return LLVMConstInt(big_int_type_ref, const_val->data.x_bool ? 1 : 0, false);
    6166                 :         24 :         case ZigTypeIdEnum:
    6167                 :            :             {
    6168                 :         24 :                 assert(type_entry->data.enumeration.decl_node->data.container_decl.init_arg_expr != nullptr);
    6169                 :         24 :                 LLVMValueRef int_val = gen_const_val(g, const_val, "");
    6170                 :         24 :                 return LLVMConstZExt(int_val, big_int_type_ref);
    6171                 :            :             }
    6172                 :        296 :         case ZigTypeIdInt:
    6173                 :            :             {
    6174                 :        296 :                 LLVMValueRef int_val = gen_const_val(g, const_val, "");
    6175                 :        296 :                 return LLVMConstZExt(int_val, big_int_type_ref);
    6176                 :            :             }
    6177                 :          0 :         case ZigTypeIdFloat:
    6178                 :            :             {
    6179                 :          0 :                 LLVMValueRef float_val = gen_const_val(g, const_val, "");
    6180                 :          0 :                 LLVMValueRef int_val = LLVMConstFPToUI(float_val,
    6181                 :          0 :                         LLVMIntType((unsigned)type_entry->data.floating.bit_count));
    6182                 :          0 :                 return LLVMConstZExt(int_val, big_int_type_ref);
    6183                 :            :             }
    6184                 :          0 :         case ZigTypeIdPointer:
    6185                 :            :         case ZigTypeIdFn:
    6186                 :            :         case ZigTypeIdOptional:
    6187                 :            :             {
    6188                 :          0 :                 LLVMValueRef ptr_val = gen_const_val(g, const_val, "");
    6189                 :          0 :                 LLVMValueRef ptr_size_int_val = LLVMConstPtrToInt(ptr_val, g->builtin_types.entry_usize->llvm_type);
    6190                 :          0 :                 return LLVMConstZExt(ptr_size_int_val, big_int_type_ref);
    6191                 :            :             }
    6192                 :          8 :         case ZigTypeIdArray: {
    6193                 :          8 :             LLVMValueRef val = LLVMConstInt(big_int_type_ref, 0, false);
    6194         [ -  + ]:          8 :             if (const_val->data.x_array.special == ConstArraySpecialUndef) {
    6195                 :          0 :                 return val;
    6196                 :            :             }
    6197                 :          8 :             expand_undef_array(g, const_val);
    6198                 :          8 :             bool is_big_endian = g->is_big_endian; // TODO get endianness from struct type
    6199                 :          8 :             uint32_t packed_bits_size = type_size_bits(g, type_entry->data.array.child_type);
    6200                 :          8 :             size_t used_bits = 0;
    6201         [ +  + ]:        184 :             for (size_t i = 0; i < type_entry->data.array.len; i += 1) {
    6202                 :        176 :                 ConstExprValue *elem_val = &const_val->data.x_array.data.s_none.elements[i];
    6203                 :        176 :                 LLVMValueRef child_val = pack_const_int(g, big_int_type_ref, elem_val);
    6204                 :            : 
    6205         [ -  + ]:        176 :                 if (is_big_endian) {
    6206                 :          0 :                     LLVMValueRef shift_amt = LLVMConstInt(big_int_type_ref, packed_bits_size, false);
    6207                 :          0 :                     val = LLVMConstShl(val, shift_amt);
    6208                 :          0 :                     val = LLVMConstOr(val, child_val);
    6209                 :            :                 } else {
    6210                 :        176 :                     LLVMValueRef shift_amt = LLVMConstInt(big_int_type_ref, used_bits, false);
    6211                 :        176 :                     LLVMValueRef child_val_shifted = LLVMConstShl(child_val, shift_amt);
    6212                 :        176 :                     val = LLVMConstOr(val, child_val_shifted);
    6213                 :        176 :                     used_bits += packed_bits_size;
    6214                 :            :                 }
    6215                 :            :             }
    6216                 :          8 :             return val;
    6217                 :            :         }
    6218                 :          0 :         case ZigTypeIdVector:
    6219                 :          0 :             zig_panic("TODO bit pack a vector");
    6220                 :          0 :         case ZigTypeIdUnion:
    6221                 :          0 :             zig_panic("TODO bit pack a union");
    6222                 :          0 :         case ZigTypeIdStruct:
    6223                 :            :             {
    6224                 :          0 :                 assert(type_entry->data.structure.layout == ContainerLayoutPacked);
    6225                 :          0 :                 bool is_big_endian = g->is_big_endian; // TODO get endianness from struct type
    6226                 :            : 
    6227                 :          0 :                 LLVMValueRef val = LLVMConstInt(big_int_type_ref, 0, false);
    6228                 :          0 :                 size_t used_bits = 0;
    6229         [ #  # ]:          0 :                 for (size_t i = 0; i < type_entry->data.structure.src_field_count; i += 1) {
    6230                 :          0 :                     TypeStructField *field = &type_entry->data.structure.fields[i];
    6231         [ #  # ]:          0 :                     if (field->gen_index == SIZE_MAX) {
    6232                 :          0 :                         continue;
    6233                 :            :                     }
    6234                 :          0 :                     LLVMValueRef child_val = pack_const_int(g, big_int_type_ref, &const_val->data.x_struct.fields[i]);
    6235                 :          0 :                     uint32_t packed_bits_size = type_size_bits(g, field->type_entry);
    6236         [ #  # ]:          0 :                     if (is_big_endian) {
    6237                 :          0 :                         LLVMValueRef shift_amt = LLVMConstInt(big_int_type_ref, packed_bits_size, false);
    6238                 :          0 :                         val = LLVMConstShl(val, shift_amt);
    6239                 :          0 :                         val = LLVMConstOr(val, child_val);
    6240                 :            :                     } else {
    6241                 :          0 :                         LLVMValueRef shift_amt = LLVMConstInt(big_int_type_ref, used_bits, false);
    6242                 :          0 :                         LLVMValueRef child_val_shifted = LLVMConstShl(child_val, shift_amt);
    6243                 :          0 :                         val = LLVMConstOr(val, child_val_shifted);
    6244                 :          0 :                         used_bits += packed_bits_size;
    6245                 :            :                     }
    6246                 :            :                 }
    6247                 :          0 :                 return val;
    6248                 :            :             }
    6249                 :          0 :         case ZigTypeIdFnFrame:
    6250                 :          0 :             zig_panic("TODO bit pack an async function frame");
    6251                 :          0 :         case ZigTypeIdAnyFrame:
    6252                 :          0 :             zig_panic("TODO bit pack an anyframe");
    6253                 :            :     }
    6254                 :          0 :     zig_unreachable();
    6255                 :            : }
    6256                 :            : 
    6257                 :            : // We have this because union constants can't be represented by the official union type,
    6258                 :            : // and this property bubbles up in whatever aggregate type contains a union constant
    6259                 :     862273 : static bool is_llvm_value_unnamed_type(CodeGen *g, ZigType *type_entry, LLVMValueRef val) {
    6260                 :     862273 :     return LLVMTypeOf(val) != get_llvm_type(g, type_entry);
    6261                 :            : }
    6262                 :            : 
    6263                 :      23455 : static LLVMValueRef gen_const_val_ptr(CodeGen *g, ConstExprValue *const_val, const char *name) {
    6264   [ -  +  +  +  :      23455 :     switch (const_val->data.x_ptr.special) {
          -  -  -  +  +  
                   +  - ]
    6265                 :          0 :         case ConstPtrSpecialInvalid:
    6266                 :            :         case ConstPtrSpecialDiscard:
    6267                 :          0 :             zig_unreachable();
    6268                 :       5703 :         case ConstPtrSpecialRef:
    6269                 :            :             {
    6270                 :       5703 :                 assert(const_val->global_refs != nullptr);
    6271                 :       5703 :                 ConstExprValue *pointee = const_val->data.x_ptr.data.ref.pointee;
    6272                 :       5703 :                 render_const_val(g, pointee, "");
    6273                 :       5703 :                 render_const_val_global(g, pointee, "");
    6274                 :       5703 :                 const_val->global_refs->llvm_value = LLVMConstBitCast(pointee->global_refs->llvm_global,
    6275                 :            :                         get_llvm_type(g, const_val->type));
    6276                 :       5703 :                 return const_val->global_refs->llvm_value;
    6277                 :            :             }
    6278                 :      16175 :         case ConstPtrSpecialBaseArray:
    6279                 :            :             {
    6280                 :      16175 :                 assert(const_val->global_refs != nullptr);
    6281                 :      16175 :                 ConstExprValue *array_const_val = const_val->data.x_ptr.data.base_array.array_val;
    6282                 :      16175 :                 assert(array_const_val->type->id == ZigTypeIdArray);
    6283         [ +  + ]:      16175 :                 if (!type_has_bits(array_const_val->type)) {
    6284                 :            :                     // make this a null pointer
    6285                 :        297 :                     ZigType *usize = g->builtin_types.entry_usize;
    6286                 :        297 :                     const_val->global_refs->llvm_value = LLVMConstIntToPtr(LLVMConstNull(usize->llvm_type),
    6287                 :            :                             get_llvm_type(g, const_val->type));
    6288                 :        297 :                     return const_val->global_refs->llvm_value;
    6289                 :            :                 }
    6290                 :      15878 :                 size_t elem_index = const_val->data.x_ptr.data.base_array.elem_index;
    6291                 :      15878 :                 LLVMValueRef uncasted_ptr_val = gen_const_ptr_array_recursive(g, array_const_val, elem_index);
    6292                 :      15878 :                 LLVMValueRef ptr_val = LLVMConstBitCast(uncasted_ptr_val, get_llvm_type(g, const_val->type));
    6293                 :      15878 :                 const_val->global_refs->llvm_value = ptr_val;
    6294                 :      15878 :                 return ptr_val;
    6295                 :            :             }
    6296                 :        362 :         case ConstPtrSpecialBaseStruct:
    6297                 :            :             {
    6298                 :        362 :                 assert(const_val->global_refs != nullptr);
    6299                 :        362 :                 ConstExprValue *struct_const_val = const_val->data.x_ptr.data.base_struct.struct_val;
    6300                 :        362 :                 assert(struct_const_val->type->id == ZigTypeIdStruct);
    6301         [ -  + ]:        362 :                 if (!type_has_bits(struct_const_val->type)) {
    6302                 :            :                     // make this a null pointer
    6303                 :          0 :                     ZigType *usize = g->builtin_types.entry_usize;
    6304                 :          0 :                     const_val->global_refs->llvm_value = LLVMConstIntToPtr(LLVMConstNull(usize->llvm_type),
    6305                 :            :                             get_llvm_type(g, const_val->type));
    6306                 :          0 :                     return const_val->global_refs->llvm_value;
    6307                 :            :                 }
    6308                 :        362 :                 size_t src_field_index = const_val->data.x_ptr.data.base_struct.field_index;
    6309                 :        362 :                 size_t gen_field_index = struct_const_val->type->data.structure.fields[src_field_index].gen_index;
    6310                 :            :                 LLVMValueRef uncasted_ptr_val = gen_const_ptr_struct_recursive(g, struct_const_val,
    6311                 :        362 :                         gen_field_index);
    6312                 :        362 :                 LLVMValueRef ptr_val = LLVMConstBitCast(uncasted_ptr_val, get_llvm_type(g, const_val->type));
    6313                 :        362 :                 const_val->global_refs->llvm_value = ptr_val;
    6314                 :        362 :                 return ptr_val;
    6315                 :            :             }
    6316                 :          0 :         case ConstPtrSpecialBaseErrorUnionCode:
    6317                 :            :             {
    6318                 :          0 :                 assert(const_val->global_refs != nullptr);
    6319                 :          0 :                 ConstExprValue *err_union_const_val = const_val->data.x_ptr.data.base_err_union_code.err_union_val;
    6320                 :          0 :                 assert(err_union_const_val->type->id == ZigTypeIdErrorUnion);
    6321         [ #  # ]:          0 :                 if (!type_has_bits(err_union_const_val->type)) {
    6322                 :            :                     // make this a null pointer
    6323                 :          0 :                     ZigType *usize = g->builtin_types.entry_usize;
    6324                 :          0 :                     const_val->global_refs->llvm_value = LLVMConstIntToPtr(LLVMConstNull(usize->llvm_type),
    6325                 :            :                             get_llvm_type(g, const_val->type));
    6326                 :          0 :                     return const_val->global_refs->llvm_value;
    6327                 :            :                 }
    6328                 :          0 :                 LLVMValueRef uncasted_ptr_val = gen_const_ptr_err_union_code_recursive(g, err_union_const_val);
    6329                 :          0 :                 LLVMValueRef ptr_val = LLVMConstBitCast(uncasted_ptr_val, get_llvm_type(g, const_val->type));
    6330                 :          0 :                 const_val->global_refs->llvm_value = ptr_val;
    6331                 :          0 :                 return ptr_val;
    6332                 :            :             }
    6333                 :          0 :         case ConstPtrSpecialBaseErrorUnionPayload:
    6334                 :            :             {
    6335                 :          0 :                 assert(const_val->global_refs != nullptr);
    6336                 :          0 :                 ConstExprValue *err_union_const_val = const_val->data.x_ptr.data.base_err_union_payload.err_union_val;
    6337                 :          0 :                 assert(err_union_const_val->type->id == ZigTypeIdErrorUnion);
    6338         [ #  # ]:          0 :                 if (!type_has_bits(err_union_const_val->type)) {
    6339                 :            :                     // make this a null pointer
    6340                 :          0 :                     ZigType *usize = g->builtin_types.entry_usize;
    6341                 :          0 :                     const_val->global_refs->llvm_value = LLVMConstIntToPtr(LLVMConstNull(usize->llvm_type),
    6342                 :            :                             get_llvm_type(g, const_val->type));
    6343                 :          0 :                     return const_val->global_refs->llvm_value;
    6344                 :            :                 }
    6345                 :          0 :                 LLVMValueRef uncasted_ptr_val = gen_const_ptr_err_union_payload_recursive(g, err_union_const_val);
    6346                 :          0 :                 LLVMValueRef ptr_val = LLVMConstBitCast(uncasted_ptr_val, get_llvm_type(g, const_val->type));
    6347                 :          0 :                 const_val->global_refs->llvm_value = ptr_val;
    6348                 :          0 :                 return ptr_val;
    6349                 :            :             }
    6350                 :          0 :         case ConstPtrSpecialBaseOptionalPayload:
    6351                 :            :             {
    6352                 :          0 :                 assert(const_val->global_refs != nullptr);
    6353                 :          0 :                 ConstExprValue *optional_const_val = const_val->data.x_ptr.data.base_optional_payload.optional_val;
    6354                 :          0 :                 assert(optional_const_val->type->id == ZigTypeIdOptional);
    6355         [ #  # ]:          0 :                 if (!type_has_bits(optional_const_val->type)) {
    6356                 :            :                     // make this a null pointer
    6357                 :          0 :                     ZigType *usize = g->builtin_types.entry_usize;
    6358                 :          0 :                     const_val->global_refs->llvm_value = LLVMConstIntToPtr(LLVMConstNull(usize->llvm_type),
    6359                 :            :                             get_llvm_type(g, const_val->type));
    6360                 :          0 :                     return const_val->global_refs->llvm_value;
    6361                 :            :                 }
    6362                 :          0 :                 LLVMValueRef uncasted_ptr_val = gen_const_ptr_optional_payload_recursive(g, optional_const_val);
    6363                 :          0 :                 LLVMValueRef ptr_val = LLVMConstBitCast(uncasted_ptr_val, get_llvm_type(g, const_val->type));
    6364                 :          0 :                 const_val->global_refs->llvm_value = ptr_val;
    6365                 :          0 :                 return ptr_val;
    6366                 :            :             }
    6367                 :        176 :         case ConstPtrSpecialHardCodedAddr:
    6368                 :            :             {
    6369                 :        176 :                 assert(const_val->global_refs != nullptr);
    6370                 :        176 :                 uint64_t addr_value = const_val->data.x_ptr.data.hard_coded_addr.addr;
    6371                 :        176 :                 ZigType *usize = g->builtin_types.entry_usize;
    6372                 :        176 :                 const_val->global_refs->llvm_value = LLVMConstIntToPtr(
    6373                 :            :                         LLVMConstInt(usize->llvm_type, addr_value, false), get_llvm_type(g, const_val->type));
    6374                 :        176 :                 return const_val->global_refs->llvm_value;
    6375                 :            :             }
    6376                 :         18 :         case ConstPtrSpecialFunction:
    6377                 :         18 :             return LLVMConstBitCast(fn_llvm_value(g, const_val->data.x_ptr.data.fn.fn_entry),
    6378                 :         18 :                     get_llvm_type(g, const_val->type));
    6379                 :       1021 :         case ConstPtrSpecialNull:
    6380                 :       1021 :             return LLVMConstNull(get_llvm_type(g, const_val->type));
    6381                 :            :     }
    6382                 :          0 :     zig_unreachable();
    6383                 :            : }
    6384                 :            : 
    6385                 :        954 : static LLVMValueRef gen_const_val_err_set(CodeGen *g, ConstExprValue *const_val, const char *name) {
    6386         [ +  + ]:        954 :     uint64_t value = (const_val->data.x_err_set == nullptr) ? 0 : const_val->data.x_err_set->value;
    6387                 :        954 :     return LLVMConstInt(get_llvm_type(g, g->builtin_types.entry_global_error_set), value, false);
    6388                 :            : }
    6389                 :            : 
    6390                 :     960874 : static LLVMValueRef gen_const_val(CodeGen *g, ConstExprValue *const_val, const char *name) {
    6391                 :            :     Error err;
    6392                 :            : 
    6393                 :     960874 :     ZigType *type_entry = const_val->type;
    6394                 :     960874 :     assert(type_has_bits(type_entry));
    6395                 :            : 
    6396   [ +  -  +  +  :     961449 : check: switch (const_val->special) {
                      - ]
    6397                 :        575 :         case ConstValSpecialLazy:
    6398         [ -  + ]:        575 :             if ((err = ir_resolve_lazy(g, nullptr, const_val))) {
    6399                 :          0 :                 report_errors_and_exit(g);
    6400                 :            :             }
    6401                 :        575 :             goto check;
    6402                 :          0 :         case ConstValSpecialRuntime:
    6403                 :          0 :             zig_unreachable();
    6404                 :       1344 :         case ConstValSpecialUndef:
    6405                 :       1344 :             return LLVMGetUndef(get_llvm_type(g, type_entry));
    6406                 :     959530 :         case ConstValSpecialStatic:
    6407                 :     959530 :             break;
    6408                 :            :     }
    6409                 :            : 
    6410         [ -  + ]:     959530 :     if ((err = type_resolve(g, type_entry, ResolveStatusLLVMFull)))
    6411                 :          0 :         zig_unreachable();
    6412                 :            : 
    6413   [ +  +  +  +  :     959530 :     switch (type_entry->id) {
          +  +  +  +  +  
          +  +  +  +  -  
             -  -  -  - ]
    6414                 :     838833 :         case ZigTypeIdInt:
    6415                 :     838833 :             return bigint_to_llvm_const(get_llvm_type(g, type_entry), &const_val->data.x_bigint);
    6416                 :        938 :         case ZigTypeIdErrorSet:
    6417                 :        938 :             return gen_const_val_err_set(g, const_val, name);
    6418                 :      18710 :         case ZigTypeIdFloat:
    6419   [ +  +  +  +  :      18710 :             switch (type_entry->data.floating.bit_count) {
                      - ]
    6420                 :        288 :                 case 16:
    6421                 :        288 :                     return LLVMConstReal(get_llvm_type(g, type_entry), zig_f16_to_double(const_val->data.x_f16));
    6422                 :       1410 :                 case 32:
    6423                 :       1410 :                     return LLVMConstReal(get_llvm_type(g, type_entry), const_val->data.x_f32);
    6424                 :      16698 :                 case 64:
    6425                 :      16698 :                     return LLVMConstReal(get_llvm_type(g, type_entry), const_val->data.x_f64);
    6426                 :        314 :                 case 128:
    6427                 :            :                     {
    6428                 :            :                         // TODO make sure this is correct on big endian targets too
    6429                 :            :                         uint8_t buf[16];
    6430                 :        314 :                         memcpy(buf, &const_val->data.x_f128, 16);
    6431                 :        314 :                         LLVMValueRef as_int = LLVMConstIntOfArbitraryPrecision(LLVMInt128Type(), 2,
    6432                 :        314 :                                 (uint64_t*)buf);
    6433                 :        314 :                         return LLVMConstBitCast(as_int, get_llvm_type(g, type_entry));
    6434                 :            :                     }
    6435                 :          0 :                 default:
    6436                 :          0 :                     zig_unreachable();
    6437                 :            :             }
    6438                 :       9264 :         case ZigTypeIdBool:
    6439         [ +  + ]:       9264 :             if (const_val->data.x_bool) {
    6440                 :       6196 :                 return LLVMConstAllOnes(LLVMInt1Type());
    6441                 :            :             } else {
    6442                 :       3068 :                 return LLVMConstNull(LLVMInt1Type());
    6443                 :            :             }
    6444                 :       4128 :         case ZigTypeIdOptional:
    6445                 :            :             {
    6446                 :       4128 :                 ZigType *child_type = type_entry->data.maybe.child_type;
    6447         [ +  + ]:       4128 :                 if (!type_has_bits(child_type)) {
    6448         [ +  + ]:         64 :                     return LLVMConstInt(LLVMInt1Type(), const_val->data.x_optional ? 1 : 0, false);
    6449         [ +  + ]:       4064 :                 } else if (get_codegen_ptr_type(type_entry) != nullptr) {
    6450                 :       1057 :                     return gen_const_val_ptr(g, const_val, name);
    6451         [ +  + ]:       3007 :                 } else if (child_type->id == ZigTypeIdErrorSet) {
    6452                 :         16 :                     return gen_const_val_err_set(g, const_val, name);
    6453                 :            :                 } else {
    6454                 :            :                     LLVMValueRef child_val;
    6455                 :            :                     LLVMValueRef maybe_val;
    6456                 :            :                     bool make_unnamed_struct;
    6457         [ +  + ]:       2991 :                     if (const_val->data.x_optional) {
    6458                 :        164 :                         child_val = gen_const_val(g, const_val->data.x_optional, "");
    6459                 :        164 :                         maybe_val = LLVMConstAllOnes(LLVMInt1Type());
    6460                 :            : 
    6461                 :        164 :                         make_unnamed_struct = is_llvm_value_unnamed_type(g, const_val->type, child_val);
    6462                 :            :                     } else {
    6463                 :       2827 :                         child_val = LLVMGetUndef(get_llvm_type(g, child_type));
    6464                 :       2827 :                         maybe_val = LLVMConstNull(LLVMInt1Type());
    6465                 :            : 
    6466                 :       2827 :                         make_unnamed_struct = false;
    6467                 :            :                     }
    6468                 :            :                     LLVMValueRef fields[] = {
    6469                 :            :                         child_val,
    6470                 :            :                         maybe_val,
    6471                 :       2991 :                     };
    6472         [ +  + ]:       2991 :                     if (make_unnamed_struct) {
    6473                 :        164 :                         return LLVMConstStruct(fields, 2, false);
    6474                 :            :                     } else {
    6475                 :       2991 :                         return LLVMConstNamedStruct(get_llvm_type(g, type_entry), fields, 2);
    6476                 :            :                     }
    6477                 :            :                 }
    6478                 :            :             }
    6479                 :      32251 :         case ZigTypeIdStruct:
    6480                 :            :             {
    6481                 :      32251 :                 LLVMValueRef *fields = allocate<LLVMValueRef>(type_entry->data.structure.gen_field_count);
    6482                 :      32251 :                 size_t src_field_count = type_entry->data.structure.src_field_count;
    6483                 :      32251 :                 bool make_unnamed_struct = false;
    6484                 :      32251 :                 assert(type_entry->data.structure.resolve_status == ResolveStatusLLVMFull);
    6485         [ +  + ]:      32251 :                 if (type_entry->data.structure.layout == ContainerLayoutPacked) {
    6486                 :         88 :                     size_t src_field_index = 0;
    6487         [ +  + ]:        200 :                     while (src_field_index < src_field_count) {
    6488                 :        112 :                         TypeStructField *type_struct_field = &type_entry->data.structure.fields[src_field_index];
    6489         [ -  + ]:        112 :                         if (type_struct_field->gen_index == SIZE_MAX) {
    6490                 :          0 :                             src_field_index += 1;
    6491                 :          0 :                             continue;
    6492                 :            :                         }
    6493                 :            : 
    6494                 :        112 :                         size_t src_field_index_end = src_field_index + 1;
    6495         [ +  + ]:        208 :                         for (; src_field_index_end < src_field_count; src_field_index_end += 1) {
    6496                 :        120 :                             TypeStructField *it_field = &type_entry->data.structure.fields[src_field_index_end];
    6497         [ +  + ]:        120 :                             if (it_field->gen_index != type_struct_field->gen_index)
    6498                 :         24 :                                 break;
    6499                 :            :                         }
    6500                 :            : 
    6501         [ +  + ]:        112 :                         if (src_field_index + 1 == src_field_index_end) {
    6502                 :         48 :                             ConstExprValue *field_val = &const_val->data.x_struct.fields[src_field_index];
    6503                 :         48 :                             LLVMValueRef val = gen_const_val(g, field_val, "");
    6504                 :         48 :                             fields[type_struct_field->gen_index] = val;
    6505 [ -  + ][ +  - ]:         48 :                             make_unnamed_struct = make_unnamed_struct || is_llvm_value_unnamed_type(g, field_val->type, val);
    6506                 :            :                         } else {
    6507                 :         64 :                             bool is_big_endian = g->is_big_endian; // TODO get endianness from struct type
    6508                 :         64 :                             LLVMTypeRef big_int_type_ref = LLVMStructGetTypeAtIndex(get_llvm_type(g, type_entry),
    6509                 :         64 :                                     (unsigned)type_struct_field->gen_index);
    6510                 :         64 :                             LLVMValueRef val = LLVMConstInt(big_int_type_ref, 0, false);
    6511                 :         64 :                             size_t used_bits = 0;
    6512         [ +  + ]:        224 :                             for (size_t i = src_field_index; i < src_field_index_end; i += 1) {
    6513                 :        160 :                                 TypeStructField *it_field = &type_entry->data.structure.fields[i];
    6514         [ -  + ]:        160 :                                 if (it_field->gen_index == SIZE_MAX) {
    6515                 :          0 :                                     continue;
    6516                 :            :                                 }
    6517                 :        160 :                                 LLVMValueRef child_val = pack_const_int(g, big_int_type_ref,
    6518                 :        160 :                                         &const_val->data.x_struct.fields[i]);
    6519                 :        160 :                                 uint32_t packed_bits_size = type_size_bits(g, it_field->type_entry);
    6520         [ -  + ]:        160 :                                 if (is_big_endian) {
    6521                 :          0 :                                     LLVMValueRef shift_amt = LLVMConstInt(big_int_type_ref,
    6522                 :          0 :                                             packed_bits_size, false);
    6523                 :          0 :                                     val = LLVMConstShl(val, shift_amt);
    6524                 :          0 :                                     val = LLVMConstOr(val, child_val);
    6525                 :            :                                 } else {
    6526                 :        160 :                                     LLVMValueRef shift_amt = LLVMConstInt(big_int_type_ref, used_bits, false);
    6527                 :        160 :                                     LLVMValueRef child_val_shifted = LLVMConstShl(child_val, shift_amt);
    6528                 :        160 :                                     val = LLVMConstOr(val, child_val_shifted);
    6529                 :        160 :                                     used_bits += packed_bits_size;
    6530                 :            :                                 }
    6531                 :            :                             }
    6532                 :         64 :                             fields[type_struct_field->gen_index] = val;
    6533                 :            :                         }
    6534                 :            : 
    6535                 :        112 :                         src_field_index = src_field_index_end;
    6536                 :            :                     }
    6537                 :            :                 } else {
    6538         [ +  + ]:      97932 :                     for (uint32_t i = 0; i < src_field_count; i += 1) {
    6539                 :      65769 :                         TypeStructField *type_struct_field = &type_entry->data.structure.fields[i];
    6540         [ +  + ]:      65769 :                         if (type_struct_field->gen_index == SIZE_MAX) {
    6541                 :         32 :                             continue;
    6542                 :            :                         }
    6543                 :      65737 :                         ConstExprValue *field_val = &const_val->data.x_struct.fields[i];
    6544                 :      65737 :                         assert(field_val->type != nullptr);
    6545         [ -  + ]:      65737 :                         if ((err = ensure_const_val_repr(nullptr, g, nullptr, field_val,
    6546                 :      65737 :                                         type_struct_field->type_entry)))
    6547                 :            :                         {
    6548                 :          0 :                             zig_unreachable();
    6549                 :            :                         }
    6550                 :            : 
    6551                 :      65737 :                         LLVMValueRef val = gen_const_val(g, field_val, "");
    6552                 :      65737 :                         fields[type_struct_field->gen_index] = val;
    6553 [ +  + ][ +  + ]:      65737 :                         make_unnamed_struct = make_unnamed_struct || is_llvm_value_unnamed_type(g, field_val->type, val);
    6554                 :            : 
    6555         [ +  + ]:      65737 :                         size_t end_pad_gen_index = (i + 1 < src_field_count) ?
    6556                 :      33590 :                             type_entry->data.structure.fields[i + 1].gen_index :
    6557                 :      32147 :                             type_entry->data.structure.gen_field_count;
    6558         [ +  + ]:      65737 :                         size_t next_offset = (i + 1 < src_field_count) ?
    6559                 :      33590 :                             type_entry->data.structure.fields[i + 1].offset : type_entry->abi_size;
    6560         [ +  + ]:      65737 :                         if (end_pad_gen_index != SIZE_MAX) {
    6561         [ +  + ]:      65737 :                             for (size_t gen_i = type_struct_field->gen_index + 1; gen_i < end_pad_gen_index;
    6562                 :         16 :                                     gen_i += 1)
    6563                 :            :                             {
    6564                 :         16 :                                 size_t pad_bytes = next_offset -
    6565                 :         16 :                                     (type_struct_field->offset + type_struct_field->type_entry->abi_size);
    6566                 :         16 :                                 LLVMTypeRef llvm_array_type = LLVMArrayType(LLVMInt8Type(), pad_bytes);
    6567                 :         16 :                                 fields[gen_i] = LLVMGetUndef(llvm_array_type);
    6568                 :            :                             }
    6569                 :            :                         }
    6570                 :            :                     }
    6571                 :            :                 }
    6572         [ +  + ]:      32251 :                 if (make_unnamed_struct) {
    6573                 :         59 :                     return LLVMConstStruct(fields, type_entry->data.structure.gen_field_count,
    6574                 :         59 :                         type_entry->data.structure.layout == ContainerLayoutPacked);
    6575                 :            :                 } else {
    6576                 :      32192 :                     return LLVMConstNamedStruct(get_llvm_type(g, type_entry), fields, type_entry->data.structure.gen_field_count);
    6577                 :            :                 }
    6578                 :            :             }
    6579                 :      14469 :         case ZigTypeIdArray:
    6580                 :            :             {
    6581                 :      14469 :                 uint64_t len = type_entry->data.array.len;
    6582   [ -  +  +  - ]:      14469 :                 switch (const_val->data.x_array.special) {
    6583                 :          0 :                     case ConstArraySpecialUndef:
    6584                 :          0 :                         return LLVMGetUndef(get_llvm_type(g, type_entry));
    6585                 :      13608 :                     case ConstArraySpecialNone: {
    6586                 :      13608 :                         LLVMValueRef *values = allocate<LLVMValueRef>(len);
    6587                 :      13608 :                         LLVMTypeRef element_type_ref = get_llvm_type(g, type_entry->data.array.child_type);
    6588                 :      13608 :                         bool make_unnamed_struct = false;
    6589         [ +  + ]:     809092 :                         for (uint64_t i = 0; i < len; i += 1) {
    6590                 :     795484 :                             ConstExprValue *elem_value = &const_val->data.x_array.data.s_none.elements[i];
    6591                 :     795484 :                             LLVMValueRef val = gen_const_val(g, elem_value, "");
    6592                 :     795484 :                             values[i] = val;
    6593 [ +  + ][ +  + ]:     795484 :                             make_unnamed_struct = make_unnamed_struct || is_llvm_value_unnamed_type(g, elem_value->type, val);
    6594                 :            :                         }
    6595         [ +  + ]:      13608 :                         if (make_unnamed_struct) {
    6596                 :         24 :                             return LLVMConstStruct(values, len, true);
    6597                 :            :                         } else {
    6598                 :      13584 :                             return LLVMConstArray(element_type_ref, values, (unsigned)len);
    6599                 :            :                         }
    6600                 :            :                     }
    6601                 :        861 :                     case ConstArraySpecialBuf: {
    6602                 :        861 :                         Buf *buf = const_val->data.x_array.data.s_buf;
    6603                 :        861 :                         return LLVMConstString(buf_ptr(buf), (unsigned)buf_len(buf), true);
    6604                 :            :                     }
    6605                 :            :                 }
    6606                 :          0 :                 zig_unreachable();
    6607                 :            :             }
    6608                 :         96 :         case ZigTypeIdVector: {
    6609                 :         96 :             uint32_t len = type_entry->data.vector.len;
    6610   [ -  +  -  - ]:         96 :             switch (const_val->data.x_array.special) {
    6611                 :          0 :                 case ConstArraySpecialUndef:
    6612                 :          0 :                     return LLVMGetUndef(get_llvm_type(g, type_entry));
    6613                 :         96 :                 case ConstArraySpecialNone: {
    6614                 :         96 :                     LLVMValueRef *values = allocate<LLVMValueRef>(len);
    6615         [ +  + ]:        480 :                     for (uint64_t i = 0; i < len; i += 1) {
    6616                 :        384 :                         ConstExprValue *elem_value = &const_val->data.x_array.data.s_none.elements[i];
    6617                 :        384 :                         values[i] = gen_const_val(g, elem_value, "");
    6618                 :            :                     }
    6619                 :         96 :                     return LLVMConstVector(values, len);
    6620                 :            :                 }
    6621                 :          0 :                 case ConstArraySpecialBuf: {
    6622                 :          0 :                     Buf *buf = const_val->data.x_array.data.s_buf;
    6623                 :          0 :                     assert(buf_len(buf) == len);
    6624                 :          0 :                     LLVMValueRef *values = allocate<LLVMValueRef>(len);
    6625         [ #  # ]:          0 :                     for (uint64_t i = 0; i < len; i += 1) {
    6626                 :          0 :                         values[i] = LLVMConstInt(g->builtin_types.entry_u8->llvm_type, buf_ptr(buf)[i], false);
    6627                 :            :                     }
    6628                 :          0 :                     return LLVMConstVector(values, len);
    6629                 :            :                 }
    6630                 :            :             }
    6631                 :          0 :             zig_unreachable();
    6632                 :            :         }
    6633                 :        426 :         case ZigTypeIdUnion:
    6634                 :            :             {
    6635                 :            :                 // Force type_entry->data.unionation.union_llvm_type to get resolved
    6636                 :        426 :                 (void)get_llvm_type(g, type_entry);
    6637                 :            : 
    6638         [ +  + ]:        426 :                 if (type_entry->data.unionation.gen_field_count == 0) {
    6639         [ -  + ]:         24 :                     if (type_entry->data.unionation.tag_type == nullptr) {
    6640                 :          0 :                         return nullptr;
    6641                 :            :                     } else {
    6642                 :         24 :                         return bigint_to_llvm_const(get_llvm_type(g, type_entry->data.unionation.tag_type),
    6643                 :         24 :                             &const_val->data.x_union.tag);
    6644                 :            :                     }
    6645                 :            :                 }
    6646                 :            : 
    6647                 :        402 :                 LLVMTypeRef union_type_ref = type_entry->data.unionation.union_llvm_type;
    6648                 :        402 :                 assert(union_type_ref != nullptr);
    6649                 :            : 
    6650                 :            :                 LLVMValueRef union_value_ref;
    6651                 :            :                 bool make_unnamed_struct;
    6652                 :        402 :                 ConstExprValue *payload_value = const_val->data.x_union.payload;
    6653 [ +  + ][ +  + ]:        402 :                 if (payload_value == nullptr || !type_has_bits(payload_value->type)) {
                 [ +  - ]
    6654         [ -  + ]:         65 :                     if (type_entry->data.unionation.gen_tag_index == SIZE_MAX)
    6655                 :          0 :                         return LLVMGetUndef(get_llvm_type(g, type_entry));
    6656                 :            : 
    6657                 :         65 :                     union_value_ref = LLVMGetUndef(union_type_ref);
    6658                 :         65 :                     make_unnamed_struct = false;
    6659                 :            :                 } else {
    6660                 :        337 :                     uint64_t field_type_bytes = LLVMStoreSizeOfType(g->target_data_ref,
    6661                 :        337 :                             get_llvm_type(g, payload_value->type));
    6662                 :        337 :                     uint64_t pad_bytes = type_entry->data.unionation.union_abi_size - field_type_bytes;
    6663                 :        337 :                     LLVMValueRef correctly_typed_value = gen_const_val(g, payload_value, "");
    6664 [ +  + ][ +  + ]:        337 :                     make_unnamed_struct = is_llvm_value_unnamed_type(g, payload_value->type, correctly_typed_value) ||
    6665                 :        297 :                         payload_value->type != type_entry->data.unionation.most_aligned_union_member->type_entry;
    6666                 :            : 
    6667                 :            :                     {
    6668         [ +  + ]:        337 :                         if (pad_bytes == 0) {
    6669                 :        161 :                             union_value_ref = correctly_typed_value;
    6670                 :            :                         } else {
    6671                 :            :                             LLVMValueRef fields[2];
    6672                 :        176 :                             fields[0] = correctly_typed_value;
    6673                 :        176 :                             fields[1] = LLVMGetUndef(LLVMArrayType(LLVMInt8Type(), (unsigned)pad_bytes));
    6674 [ +  + ][ +  + ]:        176 :                             if (make_unnamed_struct || type_entry->data.unionation.gen_tag_index != SIZE_MAX) {
    6675                 :        168 :                                 union_value_ref = LLVMConstStruct(fields, 2, false);
    6676                 :            :                             } else {
    6677                 :        176 :                                 union_value_ref = LLVMConstNamedStruct(union_type_ref, fields, 2);
    6678                 :            :                             }
    6679                 :            :                         }
    6680                 :            :                     }
    6681                 :            : 
    6682         [ +  + ]:        337 :                     if (type_entry->data.unionation.gen_tag_index == SIZE_MAX) {
    6683                 :         40 :                         return union_value_ref;
    6684                 :            :                     }
    6685                 :            :                 }
    6686                 :            : 
    6687                 :        362 :                 LLVMValueRef tag_value = bigint_to_llvm_const(
    6688                 :            :                         get_llvm_type(g, type_entry->data.unionation.tag_type),
    6689                 :        362 :                         &const_val->data.x_union.tag);
    6690                 :            : 
    6691                 :            :                 LLVMValueRef fields[3];
    6692                 :        362 :                 fields[type_entry->data.unionation.gen_union_index] = union_value_ref;
    6693                 :        362 :                 fields[type_entry->data.unionation.gen_tag_index] = tag_value;
    6694                 :            : 
    6695         [ +  + ]:        362 :                 if (make_unnamed_struct) {
    6696                 :        184 :                     LLVMValueRef result = LLVMConstStruct(fields, 2, false);
    6697                 :        184 :                     uint64_t last_field_offset = LLVMOffsetOfElement(g->target_data_ref, LLVMTypeOf(result), 1);
    6698                 :            :                     uint64_t end_offset = last_field_offset +
    6699                 :        184 :                         LLVMStoreSizeOfType(g->target_data_ref, LLVMTypeOf(fields[1]));
    6700                 :        184 :                     uint64_t expected_sz = LLVMStoreSizeOfType(g->target_data_ref, get_llvm_type(g, type_entry));
    6701                 :        184 :                     unsigned pad_sz = expected_sz - end_offset;
    6702         [ +  + ]:        184 :                     if (pad_sz != 0) {
    6703                 :        160 :                         fields[2] = LLVMGetUndef(LLVMArrayType(LLVMInt8Type(), pad_sz));
    6704                 :        160 :                         result = LLVMConstStruct(fields, 3, false);
    6705                 :            :                     }
    6706                 :        184 :                     uint64_t actual_sz = LLVMStoreSizeOfType(g->target_data_ref, LLVMTypeOf(result));
    6707                 :        184 :                     assert(actual_sz == expected_sz);
    6708                 :        184 :                     return result;
    6709                 :            :                 } else {
    6710                 :        426 :                     return LLVMConstNamedStruct(get_llvm_type(g, type_entry), fields, 2);
    6711                 :            :                 }
    6712                 :            : 
    6713                 :            :             }
    6714                 :            : 
    6715                 :       1485 :         case ZigTypeIdEnum:
    6716                 :       1485 :             return bigint_to_llvm_const(get_llvm_type(g, type_entry), &const_val->data.x_enum_tag);
    6717                 :       7236 :         case ZigTypeIdFn:
    6718         [ +  + ]:       7236 :             if (const_val->data.x_ptr.special == ConstPtrSpecialFunction) {
    6719                 :       7228 :                 assert(const_val->data.x_ptr.mut == ConstPtrMutComptimeConst);
    6720                 :       7228 :                 return fn_llvm_value(g, const_val->data.x_ptr.data.fn.fn_entry);
    6721         [ +  - ]:          8 :             } else if (const_val->data.x_ptr.special == ConstPtrSpecialHardCodedAddr) {
    6722                 :          8 :                 LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    6723                 :          8 :                 uint64_t addr = const_val->data.x_ptr.data.hard_coded_addr.addr;
    6724                 :          8 :                 return LLVMConstIntToPtr(LLVMConstInt(usize_type_ref, addr, false), get_llvm_type(g, type_entry));
    6725                 :            :             } else {
    6726                 :          0 :                 zig_unreachable();
    6727                 :            :             }
    6728                 :      22398 :         case ZigTypeIdPointer:
    6729                 :      22398 :             return gen_const_val_ptr(g, const_val, name);
    6730                 :       9296 :         case ZigTypeIdErrorUnion:
    6731                 :            :             {
    6732                 :       9296 :                 ZigType *payload_type = type_entry->data.error_union.payload_type;
    6733                 :       9296 :                 ZigType *err_set_type = type_entry->data.error_union.err_set_type;
    6734         [ +  + ]:       9296 :                 if (!type_has_bits(payload_type)) {
    6735                 :       7440 :                     assert(type_has_bits(err_set_type));
    6736                 :       7440 :                     ErrorTableEntry *err_set = const_val->data.x_err_union.error_set->data.x_err_set;
    6737         [ +  + ]:       7440 :                     uint64_t value = (err_set == nullptr) ? 0 : err_set->value;
    6738                 :       7440 :                     return LLVMConstInt(get_llvm_type(g, g->err_tag_type), value, false);
    6739         [ -  + ]:       1856 :                 } else if (!type_has_bits(err_set_type)) {
    6740                 :          0 :                     assert(type_has_bits(payload_type));
    6741                 :          0 :                     return gen_const_val(g, const_val->data.x_err_union.payload, "");
    6742                 :            :                 } else {
    6743                 :            :                     LLVMValueRef err_tag_value;
    6744                 :            :                     LLVMValueRef err_payload_value;
    6745                 :            :                     bool make_unnamed_struct;
    6746                 :       1856 :                     ErrorTableEntry *err_set = const_val->data.x_err_union.error_set->data.x_err_set;
    6747         [ +  + ]:       1856 :                     if (err_set != nullptr) {
    6748                 :       1293 :                         err_tag_value = LLVMConstInt(get_llvm_type(g, g->err_tag_type), err_set->value, false);
    6749                 :       1293 :                         err_payload_value = LLVMConstNull(get_llvm_type(g, payload_type));
    6750                 :       1293 :                         make_unnamed_struct = false;
    6751                 :            :                     } else {
    6752                 :        563 :                         err_tag_value = LLVMConstNull(get_llvm_type(g, g->err_tag_type));
    6753                 :        563 :                         ConstExprValue *payload_val = const_val->data.x_err_union.payload;
    6754                 :        563 :                         err_payload_value = gen_const_val(g, payload_val, "");
    6755                 :        563 :                         make_unnamed_struct = is_llvm_value_unnamed_type(g, payload_val->type, err_payload_value);
    6756                 :            :                     }
    6757                 :            :                     LLVMValueRef fields[3];
    6758                 :       1856 :                     fields[err_union_err_index] = err_tag_value;
    6759                 :       1856 :                     fields[err_union_payload_index] = err_payload_value;
    6760                 :       1856 :                     size_t field_count = 2;
    6761         [ +  + ]:       1856 :                     if (type_entry->data.error_union.pad_llvm_type != nullptr) {
    6762                 :          8 :                         fields[2] = LLVMGetUndef(type_entry->data.error_union.pad_llvm_type);
    6763                 :          8 :                         field_count = 3;
    6764                 :            :                     }
    6765         [ +  + ]:       1856 :                     if (make_unnamed_struct) {
    6766                 :         48 :                         return LLVMConstStruct(fields, field_count, false);
    6767                 :            :                     } else {
    6768                 :       1856 :                         return LLVMConstNamedStruct(get_llvm_type(g, type_entry), fields, field_count);
    6769                 :            :                     }
    6770                 :            :                 }
    6771                 :            :             }
    6772                 :          0 :         case ZigTypeIdVoid:
    6773                 :          0 :             return nullptr;
    6774                 :          0 :         case ZigTypeIdInvalid:
    6775                 :            :         case ZigTypeIdMetaType:
    6776                 :            :         case ZigTypeIdUnreachable:
    6777                 :            :         case ZigTypeIdComptimeFloat:
    6778                 :            :         case ZigTypeIdComptimeInt:
    6779                 :            :         case ZigTypeIdEnumLiteral:
    6780                 :            :         case ZigTypeIdUndefined:
    6781                 :            :         case ZigTypeIdNull:
    6782                 :            :         case ZigTypeIdBoundFn:
    6783                 :            :         case ZigTypeIdArgTuple:
    6784                 :            :         case ZigTypeIdOpaque:
    6785                 :          0 :             zig_unreachable();
    6786                 :          0 :         case ZigTypeIdFnFrame:
    6787                 :          0 :             zig_panic("TODO");
    6788                 :          0 :         case ZigTypeIdAnyFrame:
    6789                 :          0 :             zig_panic("TODO");
    6790                 :            :     }
    6791                 :          0 :     zig_unreachable();
    6792                 :            : }
    6793                 :            : 
    6794                 :     108648 : static void render_const_val(CodeGen *g, ConstExprValue *const_val, const char *name) {
    6795         [ -  + ]:     108648 :     if (!const_val->global_refs)
    6796                 :          0 :         const_val->global_refs = allocate<ConstGlobalRefs>(1);
    6797         [ +  + ]:     108648 :     if (!const_val->global_refs->llvm_value)
    6798                 :      97715 :         const_val->global_refs->llvm_value = gen_const_val(g, const_val, name);
    6799                 :            : 
    6800         [ +  + ]:     108648 :     if (const_val->global_refs->llvm_global)
    6801                 :      10589 :         LLVMSetInitializer(const_val->global_refs->llvm_global, const_val->global_refs->llvm_value);
    6802                 :     108648 : }
    6803                 :            : 
    6804                 :      36283 : static void render_const_val_global(CodeGen *g, ConstExprValue *const_val, const char *name) {
    6805         [ -  + ]:      36283 :     if (!const_val->global_refs)
    6806                 :          0 :         const_val->global_refs = allocate<ConstGlobalRefs>(1);
    6807                 :            : 
    6808         [ +  + ]:      36283 :     if (!const_val->global_refs->llvm_global) {
    6809         [ +  - ]:      29010 :         LLVMTypeRef type_ref = const_val->global_refs->llvm_value ?
    6810                 :      58020 :             LLVMTypeOf(const_val->global_refs->llvm_value) : get_llvm_type(g, const_val->type);
    6811                 :      29010 :         LLVMValueRef global_value = LLVMAddGlobal(g->module, type_ref, name);
    6812                 :      29010 :         LLVMSetLinkage(global_value, LLVMInternalLinkage);
    6813                 :      29010 :         LLVMSetGlobalConstant(global_value, true);
    6814                 :      29010 :         LLVMSetUnnamedAddr(global_value, true);
    6815         [ +  + ]:      29010 :         LLVMSetAlignment(global_value, (const_val->global_refs->align == 0) ?
    6816                 :      29010 :                 get_abi_alignment(g, const_val->type) : const_val->global_refs->align);
    6817                 :            : 
    6818                 :      29010 :         const_val->global_refs->llvm_global = global_value;
    6819                 :            :     }
    6820                 :            : 
    6821         [ +  - ]:      36283 :     if (const_val->global_refs->llvm_value)
    6822                 :      36283 :         LLVMSetInitializer(const_val->global_refs->llvm_global, const_val->global_refs->llvm_value);
    6823                 :      36283 : }
    6824                 :            : 
    6825                 :         29 : static void generate_error_name_table(CodeGen *g) {
    6826 [ +  + ][ +  + ]:         29 :     if (g->err_name_table != nullptr || !g->generate_error_name_table || g->errors_by_index.length == 1) {
                 [ -  + ]
    6827                 :         20 :         return;
    6828                 :            :     }
    6829                 :            : 
    6830                 :          9 :     assert(g->errors_by_index.length > 0);
    6831                 :            : 
    6832                 :          9 :     ZigType *u8_ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false,
    6833                 :          9 :             PtrLenUnknown, get_abi_alignment(g, g->builtin_types.entry_u8), 0, 0, false);
    6834                 :          9 :     ZigType *str_type = get_slice_type(g, u8_ptr_type);
    6835                 :            : 
    6836                 :          9 :     LLVMValueRef *values = allocate<LLVMValueRef>(g->errors_by_index.length);
    6837                 :          9 :     values[0] = LLVMGetUndef(get_llvm_type(g, str_type));
    6838         [ +  + ]:        698 :     for (size_t i = 1; i < g->errors_by_index.length; i += 1) {
    6839                 :        689 :         ErrorTableEntry *err_entry = g->errors_by_index.at(i);
    6840                 :        689 :         Buf *name = &err_entry->name;
    6841                 :            : 
    6842                 :        689 :         g->largest_err_name_len = max(g->largest_err_name_len, buf_len(name));
    6843                 :            : 
    6844                 :        689 :         LLVMValueRef str_init = LLVMConstString(buf_ptr(name), (unsigned)buf_len(name), true);
    6845                 :        689 :         LLVMValueRef str_global = LLVMAddGlobal(g->module, LLVMTypeOf(str_init), "");
    6846                 :        689 :         LLVMSetInitializer(str_global, str_init);
    6847                 :        689 :         LLVMSetLinkage(str_global, LLVMPrivateLinkage);
    6848                 :        689 :         LLVMSetGlobalConstant(str_global, true);
    6849                 :        689 :         LLVMSetUnnamedAddr(str_global, true);
    6850                 :        689 :         LLVMSetAlignment(str_global, LLVMABIAlignmentOfType(g->target_data_ref, LLVMTypeOf(str_init)));
    6851                 :            : 
    6852                 :            :         LLVMValueRef fields[] = {
    6853                 :        689 :             LLVMConstBitCast(str_global, get_llvm_type(g, u8_ptr_type)),
    6854                 :        689 :             LLVMConstInt(g->builtin_types.entry_usize->llvm_type, buf_len(name), false),
    6855                 :       1378 :         };
    6856                 :        689 :         values[i] = LLVMConstNamedStruct(get_llvm_type(g, str_type), fields, 2);
    6857                 :            :     }
    6858                 :            : 
    6859                 :          9 :     LLVMValueRef err_name_table_init = LLVMConstArray(get_llvm_type(g, str_type), values, (unsigned)g->errors_by_index.length);
    6860                 :            : 
    6861                 :          9 :     g->err_name_table = LLVMAddGlobal(g->module, LLVMTypeOf(err_name_table_init),
    6862                 :          9 :             buf_ptr(get_mangled_name(g, buf_create_from_str("__zig_err_name_table"), false)));
    6863                 :          9 :     LLVMSetInitializer(g->err_name_table, err_name_table_init);
    6864                 :          9 :     LLVMSetLinkage(g->err_name_table, LLVMPrivateLinkage);
    6865                 :          9 :     LLVMSetGlobalConstant(g->err_name_table, true);
    6866                 :          9 :     LLVMSetUnnamedAddr(g->err_name_table, true);
    6867                 :          9 :     LLVMSetAlignment(g->err_name_table, LLVMABIAlignmentOfType(g->target_data_ref, LLVMTypeOf(err_name_table_init)));
    6868                 :            : }
    6869                 :            : 
    6870                 :      24304 : static void build_all_basic_blocks(CodeGen *g, ZigFn *fn) {
    6871                 :      24304 :     IrExecutable *executable = &fn->analyzed_executable;
    6872                 :      24304 :     assert(executable->basic_block_list.length > 0);
    6873                 :      24304 :     LLVMValueRef fn_val = fn_llvm_value(g, fn);
    6874                 :      24304 :     LLVMBasicBlockRef first_bb = nullptr;
    6875         [ +  + ]:      24304 :     if (fn_is_async(fn)) {
    6876                 :        824 :         first_bb = LLVMAppendBasicBlock(fn_val, "AsyncSwitch");
    6877                 :        824 :         g->cur_preamble_llvm_block = first_bb;
    6878                 :            :     }
    6879         [ +  + ]:     110543 :     for (size_t block_i = 0; block_i < executable->basic_block_list.length; block_i += 1) {
    6880                 :      86239 :         IrBasicBlock *bb = executable->basic_block_list.at(block_i);
    6881                 :      86239 :         bb->llvm_block = LLVMAppendBasicBlock(fn_val, bb->name_hint);
    6882                 :            :     }
    6883         [ +  + ]:      24304 :     if (first_bb == nullptr) {
    6884                 :      23480 :         first_bb = executable->basic_block_list.at(0)->llvm_block;
    6885                 :            :     }
    6886                 :      24304 :     LLVMPositionBuilderAtEnd(g->builder, first_bb);
    6887                 :      24304 : }
    6888                 :            : 
    6889                 :       2331 : static void gen_global_var(CodeGen *g, ZigVar *var, LLVMValueRef init_val,
    6890                 :            :     ZigType *type_entry)
    6891                 :            : {
    6892         [ -  + ]:       2331 :     if (g->strip_debug_symbols) {
    6893                 :          0 :         return;
    6894                 :            :     }
    6895                 :            : 
    6896                 :       2331 :     assert(var->gen_is_const);
    6897                 :       2331 :     assert(type_entry);
    6898                 :            : 
    6899                 :       2331 :     ZigType *import = get_scope_import(var->parent_scope);
    6900                 :       2331 :     assert(import);
    6901                 :            : 
    6902                 :       2331 :     bool is_local_to_unit = true;
    6903                 :       4662 :     ZigLLVMCreateGlobalVariable(g->dbuilder, get_di_scope(g, var->parent_scope), buf_ptr(&var->name),
    6904                 :       2331 :         buf_ptr(&var->name), import->data.structure.root_struct->di_file,
    6905                 :       2331 :         (unsigned)(var->decl_node->line + 1),
    6906                 :            :         get_llvm_di_type(g, type_entry), is_local_to_unit);
    6907                 :            : 
    6908                 :            :     // TODO ^^ make an actual global variable
    6909                 :            : }
    6910                 :            : 
    6911                 :         20 : static void validate_inline_fns(CodeGen *g) {
    6912         [ +  + ]:         66 :     for (size_t i = 0; i < g->inline_fns.length; i += 1) {
    6913                 :         46 :         ZigFn *fn_entry = g->inline_fns.at(i);
    6914                 :         46 :         LLVMValueRef fn_val = LLVMGetNamedFunction(g->module, fn_entry->llvm_name);
    6915         [ -  + ]:         46 :         if (fn_val != nullptr) {
    6916                 :          0 :             add_node_error(g, fn_entry->proto_node, buf_sprintf("unable to inline function"));
    6917                 :            :         }
    6918                 :            :     }
    6919                 :         20 :     report_errors_and_maybe_exit(g);
    6920                 :         20 : }
    6921                 :            : 
    6922                 :       2939 : static void set_global_tls(CodeGen *g, ZigVar *var, LLVMValueRef global_value) {
    6923                 :       2939 :     bool is_extern = var->decl_node->data.variable_declaration.is_extern;
    6924                 :       2939 :     bool is_export = var->decl_node->data.variable_declaration.is_export;
    6925 [ +  + ][ +  + ]:       2939 :     bool is_internal_linkage = !is_extern && !is_export;
    6926 [ +  + ][ +  + ]:       2939 :     if (var->is_thread_local && (!g->is_single_threaded || !is_internal_linkage)) {
                 [ +  + ]
    6927                 :         12 :         LLVMSetThreadLocalMode(global_value, LLVMGeneralDynamicTLSModel);
    6928                 :            :     }
    6929                 :       2939 : }
    6930                 :            : 
    6931                 :         20 : static void do_code_gen(CodeGen *g) {
    6932                 :            :     Error err;
    6933                 :         20 :     assert(!g->errors.length);
    6934                 :            : 
    6935                 :         20 :     generate_error_name_table(g);
    6936                 :            : 
    6937                 :            :     // Generate module level variables
    6938         [ +  + ]:      11916 :     for (size_t i = 0; i < g->global_vars.length; i += 1) {
    6939                 :      11896 :         TldVar *tld_var = g->global_vars.at(i);
    6940                 :      11896 :         ZigVar *var = tld_var->var;
    6941                 :            : 
    6942         [ +  + ]:      11896 :         if (var->var_type->id == ZigTypeIdComptimeFloat) {
    6943                 :            :             // Generate debug info for it but that's it.
    6944                 :        122 :             ConstExprValue *const_val = var->const_value;
    6945                 :        122 :             assert(const_val->special != ConstValSpecialRuntime);
    6946         [ -  + ]:        122 :             if ((err = ir_resolve_lazy(g, var->decl_node, const_val)))
    6947                 :          0 :                 zig_unreachable();
    6948         [ -  + ]:        122 :             if (const_val->type != var->var_type) {
    6949                 :          0 :                 zig_panic("TODO debug info for var with ptr casted value");
    6950                 :            :             }
    6951                 :        122 :             ZigType *var_type = g->builtin_types.entry_f128;
    6952                 :        122 :             ConstExprValue coerced_value = {};
    6953                 :        122 :             coerced_value.special = ConstValSpecialStatic;
    6954                 :        122 :             coerced_value.type = var_type;
    6955                 :        122 :             coerced_value.data.x_f128 = bigfloat_to_f128(&const_val->data.x_bigfloat);
    6956                 :        122 :             LLVMValueRef init_val = gen_const_val(g, &coerced_value, "");
    6957                 :        122 :             gen_global_var(g, var, init_val, var_type);
    6958                 :        122 :             continue;
    6959                 :            :         }
    6960                 :            : 
    6961         [ +  + ]:      11774 :         if (var->var_type->id == ZigTypeIdComptimeInt) {
    6962                 :            :             // Generate debug info for it but that's it.
    6963                 :       1051 :             ConstExprValue *const_val = var->const_value;
    6964                 :       1051 :             assert(const_val->special != ConstValSpecialRuntime);
    6965         [ -  + ]:       1051 :             if ((err = ir_resolve_lazy(g, var->decl_node, const_val)))
    6966                 :          0 :                 zig_unreachable();
    6967         [ -  + ]:       1051 :             if (const_val->type != var->var_type) {
    6968                 :          0 :                 zig_panic("TODO debug info for var with ptr casted value");
    6969                 :            :             }
    6970                 :       1051 :             size_t bits_needed = bigint_bits_needed(&const_val->data.x_bigint);
    6971         [ +  + ]:       1051 :             if (bits_needed < 8) {
    6972                 :        897 :                 bits_needed = 8;
    6973                 :            :             }
    6974                 :       1051 :             ZigType *var_type = get_int_type(g, const_val->data.x_bigint.is_negative, bits_needed);
    6975                 :       1051 :             LLVMValueRef init_val = bigint_to_llvm_const(get_llvm_type(g, var_type), &const_val->data.x_bigint);
    6976                 :       1051 :             gen_global_var(g, var, init_val, var_type);
    6977                 :       1051 :             continue;
    6978                 :            :         }
    6979                 :            : 
    6980         [ +  + ]:      10723 :         if (!type_has_bits(var->var_type))
    6981                 :       7784 :             continue;
    6982                 :            : 
    6983                 :       2939 :         assert(var->decl_node);
    6984                 :            : 
    6985                 :            :         GlobalLinkageId linkage;
    6986                 :       2939 :         Buf *unmangled_name = &var->name;
    6987                 :            :         Buf *symbol_name;
    6988         [ +  + ]:       2939 :         if (var->export_list.length == 0) {
    6989         [ -  + ]:       2915 :             if (var->decl_node->data.variable_declaration.is_extern) {
    6990                 :          0 :                 symbol_name = unmangled_name;
    6991                 :          0 :                 linkage = GlobalLinkageIdStrong;
    6992                 :            :             } else {
    6993                 :       2915 :                 symbol_name = get_mangled_name(g, unmangled_name, false);
    6994                 :       2915 :                 linkage = GlobalLinkageIdInternal;
    6995                 :            :             }
    6996                 :            :         } else {
    6997                 :         24 :             GlobalExport *global_export = &var->export_list.items[0];
    6998                 :         24 :             symbol_name = &global_export->name;
    6999                 :         24 :             linkage = global_export->linkage;
    7000                 :            :         }
    7001                 :            : 
    7002                 :            :         LLVMValueRef global_value;
    7003                 :       2939 :         bool externally_initialized = var->decl_node->data.variable_declaration.expr == nullptr;
    7004         [ -  + ]:       2939 :         if (externally_initialized) {
    7005                 :          0 :             LLVMValueRef existing_llvm_var = LLVMGetNamedGlobal(g->module, buf_ptr(symbol_name));
    7006         [ #  # ]:          0 :             if (existing_llvm_var) {
    7007                 :          0 :                 global_value = LLVMConstBitCast(existing_llvm_var,
    7008                 :            :                         LLVMPointerType(get_llvm_type(g, var->var_type), 0));
    7009                 :            :             } else {
    7010                 :          0 :                 global_value = LLVMAddGlobal(g->module, get_llvm_type(g, var->var_type), buf_ptr(symbol_name));
    7011                 :            :                 // TODO debug info for the extern variable
    7012                 :            : 
    7013                 :          0 :                 LLVMSetLinkage(global_value, to_llvm_linkage(linkage));
    7014                 :          0 :                 maybe_import_dll(g, global_value, GlobalLinkageIdStrong);
    7015                 :          0 :                 LLVMSetAlignment(global_value, var->align_bytes);
    7016                 :          0 :                 LLVMSetGlobalConstant(global_value, var->gen_is_const);
    7017                 :          0 :                 set_global_tls(g, var, global_value);
    7018                 :            :             }
    7019                 :            :         } else {
    7020                 :       2939 :             bool exported = (linkage != GlobalLinkageIdInternal);
    7021                 :       2939 :             render_const_val(g, var->const_value, buf_ptr(symbol_name));
    7022                 :       2939 :             render_const_val_global(g, var->const_value, buf_ptr(symbol_name));
    7023                 :       2939 :             global_value = var->const_value->global_refs->llvm_global;
    7024                 :            : 
    7025         [ +  + ]:       2939 :             if (exported) {
    7026                 :         24 :                 LLVMSetLinkage(global_value, to_llvm_linkage(linkage));
    7027                 :         24 :                 maybe_export_dll(g, global_value, GlobalLinkageIdStrong);
    7028                 :            :             }
    7029         [ +  + ]:       2939 :             if (tld_var->section_name) {
    7030                 :          5 :                 LLVMSetSection(global_value, buf_ptr(tld_var->section_name));
    7031                 :            :             }
    7032                 :       2939 :             LLVMSetAlignment(global_value, var->align_bytes);
    7033                 :            : 
    7034                 :            :             // TODO debug info for function pointers
    7035                 :            :             // Here we use const_value->type because that's the type of the llvm global,
    7036                 :            :             // which we const ptr cast upon use to whatever it needs to be.
    7037 [ +  + ][ +  + ]:       2939 :             if (var->gen_is_const && var->const_value->type->id != ZigTypeIdFn) {
    7038                 :       1158 :                 gen_global_var(g, var, var->const_value->global_refs->llvm_value, var->const_value->type);
    7039                 :            :             }
    7040                 :            : 
    7041                 :       2939 :             LLVMSetGlobalConstant(global_value, var->gen_is_const);
    7042                 :       2939 :             set_global_tls(g, var, global_value);
    7043                 :            :         }
    7044                 :            : 
    7045                 :       2939 :         var->value_ref = global_value;
    7046                 :            : 
    7047         [ -  + ]:       2939 :         for (size_t export_i = 1; export_i < var->export_list.length; export_i += 1) {
    7048                 :          0 :             GlobalExport *global_export = &var->export_list.items[export_i];
    7049                 :          0 :             LLVMAddAlias(g->module, LLVMTypeOf(var->value_ref), var->value_ref, buf_ptr(&global_export->name));
    7050                 :            :         }
    7051                 :            :     }
    7052                 :            : 
    7053                 :            :     // Generate function definitions.
    7054         [ +  + ]:      24324 :     for (size_t fn_i = 0; fn_i < g->fn_defs.length; fn_i += 1) {
    7055                 :      24304 :         ZigFn *fn_table_entry = g->fn_defs.at(fn_i);
    7056                 :      24304 :         FnTypeId *fn_type_id = &fn_table_entry->type_entry->data.fn.fn_type_id;
    7057                 :      24304 :         CallingConvention cc = fn_type_id->cc;
    7058                 :      24304 :         bool is_c_abi = cc == CallingConventionC;
    7059                 :      24304 :         bool want_sret = want_first_arg_sret(g, fn_type_id);
    7060                 :            : 
    7061                 :      24304 :         LLVMValueRef fn = fn_llvm_value(g, fn_table_entry);
    7062                 :      24304 :         g->cur_fn = fn_table_entry;
    7063                 :      24304 :         g->cur_fn_val = fn;
    7064                 :            : 
    7065                 :      24304 :         build_all_basic_blocks(g, fn_table_entry);
    7066                 :      24304 :         clear_debug_source_node(g);
    7067                 :            : 
    7068                 :      24304 :         bool is_async = fn_is_async(fn_table_entry);
    7069                 :            : 
    7070         [ +  + ]:      24304 :         if (is_async) {
    7071                 :        824 :             g->cur_frame_ptr = LLVMGetParam(fn, 0);
    7072                 :            :         } else {
    7073         [ +  + ]:      23480 :             if (want_sret) {
    7074                 :       2937 :                 g->cur_ret_ptr = LLVMGetParam(fn, 0);
    7075         [ +  + ]:      20543 :             } else if (handle_is_ptr(fn_type_id->return_type)) {
    7076                 :          8 :                 g->cur_ret_ptr = build_alloca(g, fn_type_id->return_type, "result", 0);
    7077                 :            :                 // TODO add debug info variable for this
    7078                 :            :             } else {
    7079                 :      20535 :                 g->cur_ret_ptr = nullptr;
    7080                 :            :             }
    7081                 :            :         }
    7082                 :            : 
    7083                 :      24304 :         uint32_t err_ret_trace_arg_index = get_err_ret_trace_arg_index(g, fn_table_entry);
    7084                 :      24304 :         bool have_err_ret_trace_arg = err_ret_trace_arg_index != UINT32_MAX;
    7085         [ +  + ]:      24304 :         if (have_err_ret_trace_arg) {
    7086                 :      10851 :             g->cur_err_ret_trace_val_arg = LLVMGetParam(fn, err_ret_trace_arg_index);
    7087                 :            :         } else {
    7088                 :      13453 :             g->cur_err_ret_trace_val_arg = nullptr;
    7089                 :            :         }
    7090                 :            : 
    7091                 :            :         // error return tracing setup
    7092 [ +  + ][ +  + ]:      24304 :         bool have_err_ret_trace_stack = g->have_err_ret_tracing && fn_table_entry->calls_or_awaits_errorable_fn &&
    7093 [ +  - ][ +  + ]:      48608 :             !is_async && !have_err_ret_trace_arg;
    7094                 :      24304 :         LLVMValueRef err_ret_array_val = nullptr;
    7095         [ +  + ]:      24304 :         if (have_err_ret_trace_stack) {
    7096                 :        902 :             ZigType *array_type = get_array_type(g, g->builtin_types.entry_usize, stack_trace_ptr_count);
    7097                 :        902 :             err_ret_array_val = build_alloca(g, array_type, "error_return_trace_addresses", get_abi_alignment(g, array_type));
    7098                 :            : 
    7099                 :        902 :             (void)get_llvm_type(g, get_stack_trace_type(g));
    7100                 :        902 :             g->cur_err_ret_trace_val_stack = build_alloca(g, get_stack_trace_type(g), "error_return_trace",
    7101                 :            :                     get_abi_alignment(g, g->stack_trace_type));
    7102                 :            :         } else {
    7103                 :      23402 :             g->cur_err_ret_trace_val_stack = nullptr;
    7104                 :            :         }
    7105                 :            : 
    7106         [ +  + ]:      24304 :         if (!is_async) {
    7107                 :            :             // allocate temporary stack data
    7108         [ +  + ]:      65668 :             for (size_t alloca_i = 0; alloca_i < fn_table_entry->alloca_gen_list.length; alloca_i += 1) {
    7109                 :      42188 :                 IrInstructionAllocaGen *instruction = fn_table_entry->alloca_gen_list.at(alloca_i);
    7110                 :      42188 :                 ZigType *ptr_type = instruction->base.value.type;
    7111                 :      42188 :                 assert(ptr_type->id == ZigTypeIdPointer);
    7112                 :      42188 :                 ZigType *child_type = ptr_type->data.pointer.child_type;
    7113         [ -  + ]:      42188 :                 if (type_resolve(g, child_type, ResolveStatusSizeKnown))
    7114                 :          0 :                     zig_unreachable();
    7115         [ +  + ]:      42188 :                 if (!type_has_bits(child_type))
    7116                 :       7261 :                     continue;
    7117         [ +  + ]:      34927 :                 if (instruction->base.ref_count == 0)
    7118                 :       2698 :                     continue;
    7119         [ +  + ]:      32229 :                 if (instruction->base.value.special != ConstValSpecialRuntime) {
    7120         [ +  - ]:       1547 :                     if (const_ptr_pointee(nullptr, g, &instruction->base.value, nullptr)->special !=
    7121                 :            :                             ConstValSpecialRuntime)
    7122                 :            :                     {
    7123                 :       1547 :                         continue;
    7124                 :            :                     }
    7125                 :            :                 }
    7126         [ -  + ]:      30682 :                 if (type_resolve(g, child_type, ResolveStatusLLVMFull))
    7127                 :          0 :                     zig_unreachable();
    7128                 :      30682 :                 instruction->base.llvm_value = build_alloca(g, child_type, instruction->name_hint,
    7129                 :            :                         get_ptr_align(g, ptr_type));
    7130                 :            :             }
    7131                 :            :         }
    7132                 :            : 
    7133                 :      24304 :         ZigType *import = get_scope_import(&fn_table_entry->fndef_scope->base);
    7134         [ +  + ]:      24304 :         unsigned gen_i_init = want_sret ? 1 : 0;
    7135                 :            : 
    7136                 :            :         // create debug variable declarations for variables and allocate all local variables
    7137                 :      24304 :         FnWalk fn_walk_var = {};
    7138                 :      24304 :         fn_walk_var.id = FnWalkIdVars;
    7139                 :      24304 :         fn_walk_var.data.vars.import = import;
    7140                 :      24304 :         fn_walk_var.data.vars.fn = fn_table_entry;
    7141                 :      24304 :         fn_walk_var.data.vars.llvm_fn = fn;
    7142                 :      24304 :         fn_walk_var.data.vars.gen_i = gen_i_init;
    7143         [ +  + ]:      76638 :         for (size_t var_i = 0; var_i < fn_table_entry->variable_list.length; var_i += 1) {
    7144                 :      52334 :             ZigVar *var = fn_table_entry->variable_list.at(var_i);
    7145                 :            : 
    7146         [ +  + ]:      52334 :             if (!type_has_bits(var->var_type)) {
    7147                 :        569 :                 continue;
    7148                 :            :             }
    7149         [ -  + ]:      51765 :             if (ir_get_var_is_comptime(var))
    7150                 :          0 :                 continue;
    7151   [ -  -  +  - ]:      51765 :             switch (type_requires_comptime(g, var->var_type)) {
    7152                 :          0 :                 case ReqCompTimeInvalid:
    7153                 :          0 :                     zig_unreachable();
    7154                 :          0 :                 case ReqCompTimeYes:
    7155                 :          0 :                     continue;
    7156                 :      51765 :                 case ReqCompTimeNo:
    7157                 :      51765 :                     break;
    7158                 :            :             }
    7159                 :            : 
    7160         [ +  + ]:      51765 :             if (var->src_arg_index == SIZE_MAX) {
    7161                 :      49422 :                 var->di_loc_var = ZigLLVMCreateAutoVariable(g->dbuilder, get_di_scope(g, var->parent_scope),
    7162                 :      24711 :                         buf_ptr(&var->name), import->data.structure.root_struct->di_file, (unsigned)(var->decl_node->line + 1),
    7163                 :      24711 :                         get_llvm_di_type(g, var->var_type), !g->strip_debug_symbols, 0);
    7164                 :            : 
    7165         [ +  + ]:      27054 :             } else if (is_c_abi) {
    7166                 :        819 :                 fn_walk_var.data.vars.var = var;
    7167                 :        819 :                 iter_function_params_c_abi(g, fn_table_entry->type_entry, &fn_walk_var, var->src_arg_index);
    7168         [ +  + ]:      26235 :             } else if (!is_async) {
    7169                 :            :                 ZigType *gen_type;
    7170                 :      25763 :                 FnGenParamInfo *gen_info = &fn_table_entry->type_entry->data.fn.gen_param_info[var->src_arg_index];
    7171                 :      25763 :                 assert(gen_info->gen_index != SIZE_MAX);
    7172                 :            : 
    7173         [ +  + ]:      25763 :                 if (handle_is_ptr(var->var_type)) {
    7174         [ +  - ]:       8363 :                     if (gen_info->is_byval) {
    7175                 :       8363 :                         gen_type = var->var_type;
    7176                 :            :                     } else {
    7177                 :          0 :                         gen_type = gen_info->type;
    7178                 :            :                     }
    7179                 :       8363 :                     var->value_ref = LLVMGetParam(fn, gen_info->gen_index);
    7180                 :            :                 } else {
    7181                 :      17400 :                     gen_type = var->var_type;
    7182                 :      17400 :                     var->value_ref = build_alloca(g, var->var_type, buf_ptr(&var->name), var->align_bytes);
    7183                 :            :                 }
    7184         [ +  - ]:      25763 :                 if (var->decl_node) {
    7185                 :      51526 :                     var->di_loc_var = ZigLLVMCreateParameterVariable(g->dbuilder, get_di_scope(g, var->parent_scope),
    7186                 :      25763 :                         buf_ptr(&var->name), import->data.structure.root_struct->di_file,
    7187                 :      25763 :                         (unsigned)(var->decl_node->line + 1),
    7188                 :      51526 :                         get_llvm_di_type(g, gen_type), !g->strip_debug_symbols, 0, (unsigned)(gen_info->gen_index+1));
    7189                 :            :                 }
    7190                 :            : 
    7191                 :            :             }
    7192                 :            :         }
    7193                 :            : 
    7194                 :            :         // finishing error return trace setup. we have to do this after all the allocas.
    7195         [ +  + ]:      24304 :         if (have_err_ret_trace_stack) {
    7196                 :        902 :             ZigType *usize = g->builtin_types.entry_usize;
    7197                 :        902 :             size_t index_field_index = g->stack_trace_type->data.structure.fields[0].gen_index;
    7198                 :        902 :             LLVMValueRef index_field_ptr = LLVMBuildStructGEP(g->builder, g->cur_err_ret_trace_val_stack, (unsigned)index_field_index, "");
    7199                 :        902 :             gen_store_untyped(g, LLVMConstNull(usize->llvm_type), index_field_ptr, 0, false);
    7200                 :            : 
    7201                 :        902 :             size_t addresses_field_index = g->stack_trace_type->data.structure.fields[1].gen_index;
    7202                 :        902 :             LLVMValueRef addresses_field_ptr = LLVMBuildStructGEP(g->builder, g->cur_err_ret_trace_val_stack, (unsigned)addresses_field_index, "");
    7203                 :            : 
    7204                 :        902 :             ZigType *slice_type = g->stack_trace_type->data.structure.fields[1].type_entry;
    7205                 :        902 :             size_t ptr_field_index = slice_type->data.structure.fields[slice_ptr_index].gen_index;
    7206                 :        902 :             LLVMValueRef ptr_field_ptr = LLVMBuildStructGEP(g->builder, addresses_field_ptr, (unsigned)ptr_field_index, "");
    7207                 :        902 :             LLVMValueRef zero = LLVMConstNull(usize->llvm_type);
    7208                 :        902 :             LLVMValueRef indices[] = {zero, zero};
    7209                 :        902 :             LLVMValueRef err_ret_array_val_elem0_ptr = LLVMBuildInBoundsGEP(g->builder, err_ret_array_val,
    7210                 :        902 :                     indices, 2, "");
    7211                 :        902 :             ZigType *ptr_ptr_usize_type = get_pointer_to_type(g, get_pointer_to_type(g, usize, false), false);
    7212                 :        902 :             gen_store(g, err_ret_array_val_elem0_ptr, ptr_field_ptr, ptr_ptr_usize_type);
    7213                 :            : 
    7214                 :        902 :             size_t len_field_index = slice_type->data.structure.fields[slice_len_index].gen_index;
    7215                 :        902 :             LLVMValueRef len_field_ptr = LLVMBuildStructGEP(g->builder, addresses_field_ptr, (unsigned)len_field_index, "");
    7216                 :        902 :             gen_store(g, LLVMConstInt(usize->llvm_type, stack_trace_ptr_count, false), len_field_ptr, get_pointer_to_type(g, usize, false));
    7217                 :            :         }
    7218                 :            : 
    7219         [ +  + ]:      24304 :         if (is_async) {
    7220                 :        824 :             (void)get_llvm_type(g, fn_table_entry->frame_type);
    7221                 :        824 :             g->cur_resume_block_count = 0;
    7222                 :            : 
    7223                 :        824 :             LLVMTypeRef usize_type_ref = g->builtin_types.entry_usize->llvm_type;
    7224                 :        824 :             LLVMValueRef size_val = LLVMConstInt(usize_type_ref, fn_table_entry->frame_type->abi_size, false);
    7225         [ +  - ]:        824 :             if (g->need_frame_size_prefix_data) {
    7226                 :        824 :                 ZigLLVMFunctionSetPrefixData(fn_table_entry->llvm_value, size_val);
    7227                 :            :             }
    7228                 :            : 
    7229         [ +  - ]:        824 :             if (!g->strip_debug_symbols) {
    7230                 :        824 :                 AstNode *source_node = fn_table_entry->proto_node;
    7231                 :        824 :                 ZigLLVMSetCurrentDebugLocation(g->builder, (int)source_node->line + 1,
    7232                 :        824 :                         (int)source_node->column + 1, get_di_scope(g, fn_table_entry->child_scope));
    7233                 :            :             }
    7234                 :        824 :             IrExecutable *executable = &fn_table_entry->analyzed_executable;
    7235                 :        824 :             LLVMBasicBlockRef bad_resume_block = LLVMAppendBasicBlock(g->cur_fn_val, "BadResume");
    7236                 :        824 :             LLVMPositionBuilderAtEnd(g->builder, bad_resume_block);
    7237                 :        824 :             gen_assertion_scope(g, PanicMsgIdBadResume, fn_table_entry->child_scope);
    7238                 :            : 
    7239                 :        824 :             LLVMPositionBuilderAtEnd(g->builder, g->cur_preamble_llvm_block);
    7240                 :        824 :             render_async_spills(g);
    7241                 :        824 :             g->cur_async_awaiter_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr, frame_awaiter_index, "");
    7242                 :        824 :             LLVMValueRef resume_index_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr, frame_resume_index, "");
    7243                 :        824 :             g->cur_async_resume_index_ptr = resume_index_ptr;
    7244                 :            : 
    7245         [ +  + ]:        824 :             if (type_has_bits(fn_type_id->return_type)) {
    7246                 :        448 :                 LLVMValueRef cur_ret_ptr_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr, frame_ret_start, "");
    7247                 :        448 :                 g->cur_ret_ptr = LLVMBuildLoad(g->builder, cur_ret_ptr_ptr, "");
    7248                 :            :             }
    7249                 :        824 :             uint32_t trace_field_index_stack = UINT32_MAX;
    7250         [ +  + ]:        824 :             if (codegen_fn_has_err_ret_tracing_stack(g, fn_table_entry, true)) {
    7251                 :        448 :                 trace_field_index_stack = frame_index_trace_stack(g, fn_type_id);
    7252                 :        448 :                 g->cur_err_ret_trace_val_stack = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr,
    7253                 :            :                         trace_field_index_stack, "");
    7254                 :            :             }
    7255                 :            : 
    7256                 :        824 :             LLVMValueRef resume_index = LLVMBuildLoad(g->builder, resume_index_ptr, "");
    7257                 :        824 :             LLVMValueRef switch_instr = LLVMBuildSwitch(g->builder, resume_index, bad_resume_block, 4);
    7258                 :        824 :             g->cur_async_switch_instr = switch_instr;
    7259                 :            : 
    7260                 :        824 :             LLVMValueRef zero = LLVMConstNull(usize_type_ref);
    7261                 :        824 :             IrBasicBlock *entry_block = executable->basic_block_list.at(0);
    7262                 :        824 :             LLVMAddCase(switch_instr, zero, entry_block->llvm_block);
    7263                 :        824 :             g->cur_resume_block_count += 1;
    7264                 :        824 :             LLVMPositionBuilderAtEnd(g->builder, entry_block->llvm_block);
    7265         [ +  + ]:        824 :             if (trace_field_index_stack != UINT32_MAX) {
    7266         [ +  + ]:        448 :                 if (codegen_fn_has_err_ret_tracing_arg(g, fn_type_id->return_type)) {
    7267                 :        328 :                     LLVMValueRef trace_ptr_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr,
    7268                 :        328 :                             frame_index_trace_arg(g, fn_type_id->return_type), "");
    7269                 :        328 :                     LLVMValueRef zero_ptr = LLVMConstNull(LLVMGetElementType(LLVMTypeOf(trace_ptr_ptr)));
    7270                 :        328 :                     LLVMBuildStore(g->builder, zero_ptr, trace_ptr_ptr);
    7271                 :            :                 }
    7272                 :            : 
    7273                 :        448 :                 LLVMValueRef trace_field_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr,
    7274                 :        448 :                         trace_field_index_stack, "");
    7275                 :        448 :                 LLVMValueRef addrs_field_ptr = LLVMBuildStructGEP(g->builder, g->cur_frame_ptr,
    7276                 :        448 :                         trace_field_index_stack + 1, "");
    7277                 :            : 
    7278                 :        448 :                 gen_init_stack_trace(g, trace_field_ptr, addrs_field_ptr);
    7279                 :            :             }
    7280                 :        824 :             render_async_var_decls(g, entry_block->instruction_list.at(0)->scope);
    7281                 :            :         } else {
    7282                 :            :             // create debug variable declarations for parameters
    7283                 :            :             // rely on the first variables in the variable_list being parameters.
    7284                 :      23480 :             FnWalk fn_walk_init = {};
    7285                 :      23480 :             fn_walk_init.id = FnWalkIdInits;
    7286                 :      23480 :             fn_walk_init.data.inits.fn = fn_table_entry;
    7287                 :      23480 :             fn_walk_init.data.inits.llvm_fn = fn;
    7288                 :      23480 :             fn_walk_init.data.inits.gen_i = gen_i_init;
    7289                 :      23480 :             walk_function_params(g, fn_table_entry->type_entry, &fn_walk_init);
    7290                 :            :         }
    7291                 :            : 
    7292                 :      24304 :         ir_render(g, fn_table_entry);
    7293                 :            : 
    7294                 :            :     }
    7295                 :            : 
    7296                 :         20 :     assert(!g->errors.length);
    7297                 :            : 
    7298         [ +  + ]:         20 :     if (buf_len(&g->global_asm) != 0) {
    7299                 :          9 :         LLVMSetModuleInlineAsm(g->module, buf_ptr(&g->global_asm));
    7300                 :            :     }
    7301                 :            : 
    7302         [ +  + ]:         28 :     while (g->type_resolve_stack.length != 0) {
    7303                 :          8 :         ZigType *ty = g->type_resolve_stack.last();
    7304         [ -  + ]:          8 :         if (type_resolve(g, ty, ResolveStatusLLVMFull))
    7305                 :          0 :             zig_unreachable();
    7306                 :            :     }
    7307                 :            : 
    7308                 :         20 :     ZigLLVMDIBuilderFinalize(g->dbuilder);
    7309                 :            : 
    7310         [ -  + ]:         20 :     if (g->verbose_llvm_ir) {
    7311                 :          0 :         fflush(stderr);
    7312                 :          0 :         LLVMDumpModule(g->module);
    7313                 :            :     }
    7314                 :            : 
    7315                 :            : #ifndef NDEBUG
    7316                 :         20 :     char *error = nullptr;
    7317                 :         20 :     LLVMVerifyModule(g->module, LLVMAbortProcessAction, &error);
    7318                 :            : #endif
    7319                 :         20 : }
    7320                 :            : 
    7321                 :         20 : static void zig_llvm_emit_output(CodeGen *g) {
    7322                 :         20 :     bool is_small = g->build_mode == BuildModeSmallRelease;
    7323                 :            : 
    7324                 :         20 :     Buf *output_path = &g->o_file_output_path;
    7325                 :         20 :     char *err_msg = nullptr;
    7326   [ +  -  -  - ]:         20 :     switch (g->emit_file_type) {
    7327                 :         20 :         case EmitFileTypeBinary:
    7328         [ -  + ]:         20 :             if (ZigLLVMTargetMachineEmitToFile(g->target_machine, g->module, buf_ptr(output_path),
    7329                 :         20 :                         ZigLLVM_EmitBinary, &err_msg, g->build_mode == BuildModeDebug, is_small,
    7330                 :         20 :                         g->enable_time_report))
    7331                 :            :             {
    7332                 :          0 :                 zig_panic("unable to write object file %s: %s", buf_ptr(output_path), err_msg);
    7333                 :            :             }
    7334                 :         20 :             validate_inline_fns(g);
    7335                 :         20 :             g->link_objects.append(output_path);
    7336 [ #  # ][ #  # ]:         20 :             if (g->bundle_compiler_rt && (g->out_type == OutTypeObj ||
                 [ -  + ]
    7337         [ #  # ]:          0 :                 (g->out_type == OutTypeLib && !g->is_dynamic)))
    7338                 :            :             {
    7339                 :          0 :                 zig_link_add_compiler_rt(g);
    7340                 :            :             }
    7341                 :         20 :             break;
    7342                 :            : 
    7343                 :          0 :         case EmitFileTypeAssembly:
    7344         [ #  # ]:          0 :             if (ZigLLVMTargetMachineEmitToFile(g->target_machine, g->module, buf_ptr(output_path),
    7345                 :          0 :                         ZigLLVM_EmitAssembly, &err_msg, g->build_mode == BuildModeDebug, is_small,
    7346                 :          0 :                         g->enable_time_report))
    7347                 :            :             {
    7348                 :          0 :                 zig_panic("unable to write assembly file %s: %s", buf_ptr(output_path), err_msg);
    7349                 :            :             }
    7350                 :          0 :             validate_inline_fns(g);
    7351                 :          0 :             break;
    7352                 :            : 
    7353                 :          0 :         case EmitFileTypeLLVMIr:
    7354         [ #  # ]:          0 :             if (ZigLLVMTargetMachineEmitToFile(g->target_machine, g->module, buf_ptr(output_path),
    7355                 :          0 :                         ZigLLVM_EmitLLVMIr, &err_msg, g->build_mode == BuildModeDebug, is_small,
    7356                 :          0 :                         g->enable_time_report))
    7357                 :            :             {
    7358                 :          0 :                 zig_panic("unable to write llvm-ir file %s: %s", buf_ptr(output_path), err_msg);
    7359                 :            :             }
    7360                 :          0 :             validate_inline_fns(g);
    7361                 :          0 :             break;
    7362                 :            : 
    7363                 :          0 :         default:
    7364                 :          0 :             zig_unreachable();
    7365                 :            :     }
    7366                 :         20 : }
    7367                 :            : 
    7368                 :            : struct CIntTypeInfo {
    7369                 :            :     CIntType id;
    7370                 :            :     const char *name;
    7371                 :            :     bool is_signed;
    7372                 :            : };
    7373                 :            : 
    7374                 :            : static const CIntTypeInfo c_int_type_infos[] = {
    7375                 :            :     {CIntTypeShort, "c_short", true},
    7376                 :            :     {CIntTypeUShort, "c_ushort", false},
    7377                 :            :     {CIntTypeInt, "c_int", true},
    7378                 :            :     {CIntTypeUInt, "c_uint", false},
    7379                 :            :     {CIntTypeLong, "c_long", true},
    7380                 :            :     {CIntTypeULong, "c_ulong", false},
    7381                 :            :     {CIntTypeLongLong, "c_longlong", true},
    7382                 :            :     {CIntTypeULongLong, "c_ulonglong", false},
    7383                 :            : };
    7384                 :            : 
    7385                 :            : static const bool is_signed_list[] = { false, true, };
    7386                 :            : 
    7387                 :            : struct GlobalLinkageValue {
    7388                 :            :     GlobalLinkageId id;
    7389                 :            :     const char *name;
    7390                 :            : };
    7391                 :            : 
    7392                 :            : static const GlobalLinkageValue global_linkage_values[] = {
    7393                 :            :     {GlobalLinkageIdInternal, "Internal"},
    7394                 :            :     {GlobalLinkageIdStrong, "Strong"},
    7395                 :            :     {GlobalLinkageIdWeak, "Weak"},
    7396                 :            :     {GlobalLinkageIdLinkOnce, "LinkOnce"},
    7397                 :            : };
    7398                 :            : 
    7399                 :        105 : static void add_fp_entry(CodeGen *g, const char *name, uint32_t bit_count, LLVMTypeRef type_ref,
    7400                 :            :         ZigType **field)
    7401                 :            : {
    7402                 :        105 :     ZigType *entry = new_type_table_entry(ZigTypeIdFloat);
    7403                 :        105 :     entry->llvm_type = type_ref;
    7404                 :        105 :     entry->size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, entry->llvm_type);
    7405                 :        105 :     entry->abi_size = LLVMABISizeOfType(g->target_data_ref, entry->llvm_type);
    7406                 :        105 :     entry->abi_align = LLVMABIAlignmentOfType(g->target_data_ref, entry->llvm_type);
    7407                 :        105 :     buf_init_from_str(&entry->name, name);
    7408                 :        105 :     entry->data.floating.bit_count = bit_count;
    7409                 :            : 
    7410                 :        105 :     entry->llvm_di_type = ZigLLVMCreateDebugBasicType(g->dbuilder, buf_ptr(&entry->name),
    7411                 :            :             entry->size_in_bits, ZigLLVMEncoding_DW_ATE_float());
    7412                 :        105 :     *field = entry;
    7413                 :        105 :     g->primitive_type_table.put(&entry->name, entry);
    7414                 :        105 : }
    7415                 :            : 
    7416                 :         21 : static void define_builtin_types(CodeGen *g) {
    7417                 :            :     {
    7418                 :            :         // if this type is anywhere in the AST, we should never hit codegen.
    7419                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdInvalid);
    7420                 :         21 :         buf_init_from_str(&entry->name, "(invalid)");
    7421                 :         21 :         g->builtin_types.entry_invalid = entry;
    7422                 :            :     }
    7423                 :            :     {
    7424                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdComptimeFloat);
    7425                 :         21 :         buf_init_from_str(&entry->name, "comptime_float");
    7426                 :         21 :         g->builtin_types.entry_num_lit_float = entry;
    7427                 :         21 :         g->primitive_type_table.put(&entry->name, entry);
    7428                 :            :     }
    7429                 :            :     {
    7430                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdComptimeInt);
    7431                 :         21 :         buf_init_from_str(&entry->name, "comptime_int");
    7432                 :         21 :         g->builtin_types.entry_num_lit_int = entry;
    7433                 :         21 :         g->primitive_type_table.put(&entry->name, entry);
    7434                 :            :     }
    7435                 :            :     {
    7436                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdEnumLiteral);
    7437                 :         21 :         buf_init_from_str(&entry->name, "(enum literal)");
    7438                 :         21 :         g->builtin_types.entry_enum_literal = entry;
    7439                 :            :     }
    7440                 :            :     {
    7441                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdUndefined);
    7442                 :         21 :         buf_init_from_str(&entry->name, "(undefined)");
    7443                 :         21 :         g->builtin_types.entry_undef = entry;
    7444                 :            :     }
    7445                 :            :     {
    7446                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdNull);
    7447                 :         21 :         buf_init_from_str(&entry->name, "(null)");
    7448                 :         21 :         g->builtin_types.entry_null = entry;
    7449                 :            :     }
    7450                 :            :     {
    7451                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdArgTuple);
    7452                 :         21 :         buf_init_from_str(&entry->name, "(args)");
    7453                 :         21 :         g->builtin_types.entry_arg_tuple = entry;
    7454                 :            :     }
    7455                 :            : 
    7456         [ +  + ]:        189 :     for (size_t i = 0; i < array_length(c_int_type_infos); i += 1) {
    7457                 :        168 :         const CIntTypeInfo *info = &c_int_type_infos[i];
    7458                 :        168 :         uint32_t size_in_bits = target_c_type_size_in_bits(g->zig_target, info->id);
    7459                 :        168 :         bool is_signed = info->is_signed;
    7460                 :            : 
    7461                 :        168 :         ZigType *entry = new_type_table_entry(ZigTypeIdInt);
    7462                 :        168 :         entry->llvm_type = LLVMIntType(size_in_bits);
    7463                 :        168 :         entry->size_in_bits = size_in_bits;
    7464                 :        168 :         entry->abi_size = LLVMABISizeOfType(g->target_data_ref, entry->llvm_type);
    7465                 :        168 :         entry->abi_align = LLVMABIAlignmentOfType(g->target_data_ref, entry->llvm_type);
    7466                 :            : 
    7467                 :        168 :         buf_init_from_str(&entry->name, info->name);
    7468                 :            : 
    7469         [ +  + ]:        168 :         entry->llvm_di_type = ZigLLVMCreateDebugBasicType(g->dbuilder, buf_ptr(&entry->name),
    7470                 :            :                 size_in_bits, is_signed ? ZigLLVMEncoding_DW_ATE_signed() : ZigLLVMEncoding_DW_ATE_unsigned());
    7471                 :        168 :         entry->data.integral.is_signed = is_signed;
    7472                 :        168 :         entry->data.integral.bit_count = size_in_bits;
    7473                 :        168 :         g->primitive_type_table.put(&entry->name, entry);
    7474                 :            : 
    7475                 :        168 :         get_c_int_type_ptr(g, info->id)[0] = entry;
    7476                 :            :     }
    7477                 :            : 
    7478                 :            :     {
    7479                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdBool);
    7480                 :         21 :         entry->llvm_type = LLVMInt1Type();
    7481                 :         21 :         entry->size_in_bits = 1;
    7482                 :         21 :         entry->abi_size = LLVMABISizeOfType(g->target_data_ref, entry->llvm_type);
    7483                 :         21 :         entry->abi_align = LLVMABIAlignmentOfType(g->target_data_ref, entry->llvm_type);
    7484                 :         21 :         buf_init_from_str(&entry->name, "bool");
    7485                 :         21 :         entry->llvm_di_type = ZigLLVMCreateDebugBasicType(g->dbuilder, buf_ptr(&entry->name),
    7486                 :            :                 entry->size_in_bits, ZigLLVMEncoding_DW_ATE_boolean());
    7487                 :         21 :         g->builtin_types.entry_bool = entry;
    7488                 :         21 :         g->primitive_type_table.put(&entry->name, entry);
    7489                 :            :     }
    7490                 :            : 
    7491         [ +  + ]:         63 :     for (size_t sign_i = 0; sign_i < array_length(is_signed_list); sign_i += 1) {
    7492                 :         42 :         bool is_signed = is_signed_list[sign_i];
    7493                 :            : 
    7494                 :         42 :         ZigType *entry = new_type_table_entry(ZigTypeIdInt);
    7495                 :         42 :         entry->llvm_type = LLVMIntType(g->pointer_size_bytes * 8);
    7496                 :         42 :         entry->size_in_bits = g->pointer_size_bytes * 8;
    7497                 :         42 :         entry->abi_size = LLVMABISizeOfType(g->target_data_ref, entry->llvm_type);
    7498                 :         42 :         entry->abi_align = LLVMABIAlignmentOfType(g->target_data_ref, entry->llvm_type);
    7499                 :            : 
    7500         [ +  + ]:         42 :         const char u_or_i = is_signed ? 'i' : 'u';
    7501                 :         42 :         buf_resize(&entry->name, 0);
    7502                 :         42 :         buf_appendf(&entry->name, "%csize", u_or_i);
    7503                 :            : 
    7504                 :         42 :         entry->data.integral.is_signed = is_signed;
    7505                 :         42 :         entry->data.integral.bit_count = g->pointer_size_bytes * 8;
    7506                 :            : 
    7507         [ +  + ]:         42 :         entry->llvm_di_type = ZigLLVMCreateDebugBasicType(g->dbuilder, buf_ptr(&entry->name),
    7508                 :            :                 entry->size_in_bits,
    7509                 :            :                 is_signed ? ZigLLVMEncoding_DW_ATE_signed() : ZigLLVMEncoding_DW_ATE_unsigned());
    7510                 :         42 :         g->primitive_type_table.put(&entry->name, entry);
    7511                 :            : 
    7512         [ +  + ]:         42 :         if (is_signed) {
    7513                 :         21 :             g->builtin_types.entry_isize = entry;
    7514                 :            :         } else {
    7515                 :         21 :             g->builtin_types.entry_usize = entry;
    7516                 :            :         }
    7517                 :            :     }
    7518                 :            : 
    7519                 :         21 :     add_fp_entry(g, "f16", 16, LLVMHalfType(), &g->builtin_types.entry_f16);
    7520                 :         21 :     add_fp_entry(g, "f32", 32, LLVMFloatType(), &g->builtin_types.entry_f32);
    7521                 :         21 :     add_fp_entry(g, "f64", 64, LLVMDoubleType(), &g->builtin_types.entry_f64);
    7522                 :         21 :     add_fp_entry(g, "f128", 128, LLVMFP128Type(), &g->builtin_types.entry_f128);
    7523                 :         21 :     add_fp_entry(g, "c_longdouble", 80, LLVMX86FP80Type(), &g->builtin_types.entry_c_longdouble);
    7524                 :            : 
    7525                 :            :     {
    7526                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdVoid);
    7527                 :         21 :         entry->llvm_type = LLVMVoidType();
    7528                 :         21 :         buf_init_from_str(&entry->name, "void");
    7529                 :         21 :         entry->llvm_di_type = ZigLLVMCreateDebugBasicType(g->dbuilder, buf_ptr(&entry->name),
    7530                 :            :                 0,
    7531                 :            :                 ZigLLVMEncoding_DW_ATE_signed());
    7532                 :         21 :         g->builtin_types.entry_void = entry;
    7533                 :         21 :         g->primitive_type_table.put(&entry->name, entry);
    7534                 :            :     }
    7535                 :            :     {
    7536                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdUnreachable);
    7537                 :         21 :         entry->llvm_type = LLVMVoidType();
    7538                 :         21 :         buf_init_from_str(&entry->name, "noreturn");
    7539                 :         21 :         entry->llvm_di_type = g->builtin_types.entry_void->llvm_di_type;
    7540                 :         21 :         g->builtin_types.entry_unreachable = entry;
    7541                 :         21 :         g->primitive_type_table.put(&entry->name, entry);
    7542                 :            :     }
    7543                 :            :     {
    7544                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdMetaType);
    7545                 :         21 :         buf_init_from_str(&entry->name, "type");
    7546                 :         21 :         g->builtin_types.entry_type = entry;
    7547                 :         21 :         g->primitive_type_table.put(&entry->name, entry);
    7548                 :            :     }
    7549                 :            : 
    7550                 :         21 :     g->builtin_types.entry_u8 = get_int_type(g, false, 8);
    7551                 :         21 :     g->builtin_types.entry_u16 = get_int_type(g, false, 16);
    7552                 :         21 :     g->builtin_types.entry_u29 = get_int_type(g, false, 29);
    7553                 :         21 :     g->builtin_types.entry_u32 = get_int_type(g, false, 32);
    7554                 :         21 :     g->builtin_types.entry_u64 = get_int_type(g, false, 64);
    7555                 :         21 :     g->builtin_types.entry_i8 = get_int_type(g, true, 8);
    7556                 :         21 :     g->builtin_types.entry_i32 = get_int_type(g, true, 32);
    7557                 :         21 :     g->builtin_types.entry_i64 = get_int_type(g, true, 64);
    7558                 :            : 
    7559                 :            :     {
    7560                 :         21 :         g->builtin_types.entry_c_void = get_opaque_type(g, nullptr, nullptr, "c_void",
    7561                 :            :                 buf_create_from_str("c_void"));
    7562                 :         21 :         g->primitive_type_table.put(&g->builtin_types.entry_c_void->name, g->builtin_types.entry_c_void);
    7563                 :            :     }
    7564                 :            : 
    7565                 :            :     {
    7566                 :         21 :         ZigType *entry = new_type_table_entry(ZigTypeIdErrorSet);
    7567                 :         21 :         buf_init_from_str(&entry->name, "anyerror");
    7568                 :         21 :         entry->data.error_set.err_count = UINT32_MAX;
    7569                 :            : 
    7570                 :            :         // TODO https://github.com/ziglang/zig/issues/786
    7571                 :         21 :         g->err_tag_type = g->builtin_types.entry_u16;
    7572                 :            : 
    7573                 :         21 :         entry->size_in_bits = g->err_tag_type->size_in_bits;
    7574                 :         21 :         entry->abi_align = g->err_tag_type->abi_align;
    7575                 :         21 :         entry->abi_size = g->err_tag_type->abi_size;
    7576                 :            : 
    7577                 :         21 :         g->builtin_types.entry_global_error_set = entry;
    7578                 :            : 
    7579                 :         21 :         g->errors_by_index.append(nullptr);
    7580                 :            : 
    7581                 :         21 :         g->primitive_type_table.put(&entry->name, entry);
    7582                 :            :     }
    7583                 :         21 : }
    7584                 :            : 
    7585                 :       2247 : static BuiltinFnEntry *create_builtin_fn(CodeGen *g, BuiltinFnId id, const char *name, size_t count) {
    7586                 :       2247 :     BuiltinFnEntry *builtin_fn = allocate<BuiltinFnEntry>(1);
    7587                 :       2247 :     buf_init_from_str(&builtin_fn->name, name);
    7588                 :       2247 :     builtin_fn->id = id;
    7589                 :       2247 :     builtin_fn->param_count = count;
    7590                 :       2247 :     g->builtin_fn_table.put(&builtin_fn->name, builtin_fn);
    7591                 :       2247 :     return builtin_fn;
    7592                 :            : }
    7593                 :            : 
    7594                 :         21 : static void define_builtin_fns(CodeGen *g) {
    7595                 :         21 :     create_builtin_fn(g, BuiltinFnIdBreakpoint, "breakpoint", 0);
    7596                 :         21 :     create_builtin_fn(g, BuiltinFnIdReturnAddress, "returnAddress", 0);
    7597                 :         21 :     create_builtin_fn(g, BuiltinFnIdMemcpy, "memcpy", 3);
    7598                 :         21 :     create_builtin_fn(g, BuiltinFnIdMemset, "memset", 3);
    7599                 :         21 :     create_builtin_fn(g, BuiltinFnIdSizeof, "sizeOf", 1);
    7600                 :         21 :     create_builtin_fn(g, BuiltinFnIdAlignOf, "alignOf", 1);
    7601                 :         21 :     create_builtin_fn(g, BuiltinFnIdMemberCount, "memberCount", 1);
    7602                 :         21 :     create_builtin_fn(g, BuiltinFnIdMemberType, "memberType", 2);
    7603                 :         21 :     create_builtin_fn(g, BuiltinFnIdMemberName, "memberName", 2);
    7604                 :         21 :     create_builtin_fn(g, BuiltinFnIdField, "field", 2);
    7605                 :         21 :     create_builtin_fn(g, BuiltinFnIdTypeInfo, "typeInfo", 1);
    7606                 :         21 :     create_builtin_fn(g, BuiltinFnIdType, "Type", 1);
    7607                 :         21 :     create_builtin_fn(g, BuiltinFnIdHasField, "hasField", 2);
    7608                 :         21 :     create_builtin_fn(g, BuiltinFnIdTypeof, "typeOf", 1); // TODO rename to TypeOf
    7609                 :         21 :     create_builtin_fn(g, BuiltinFnIdAddWithOverflow, "addWithOverflow", 4);
    7610                 :         21 :     create_builtin_fn(g, BuiltinFnIdSubWithOverflow, "subWithOverflow", 4);
    7611                 :         21 :     create_builtin_fn(g, BuiltinFnIdMulWithOverflow, "mulWithOverflow", 4);
    7612                 :         21 :     create_builtin_fn(g, BuiltinFnIdShlWithOverflow, "shlWithOverflow", 4);
    7613                 :         21 :     create_builtin_fn(g, BuiltinFnIdCInclude, "cInclude", 1);
    7614                 :         21 :     create_builtin_fn(g, BuiltinFnIdCDefine, "cDefine", 2);
    7615                 :         21 :     create_builtin_fn(g, BuiltinFnIdCUndef, "cUndef", 1);
    7616                 :         21 :     create_builtin_fn(g, BuiltinFnIdCtz, "ctz", 2);
    7617                 :         21 :     create_builtin_fn(g, BuiltinFnIdClz, "clz", 2);
    7618                 :         21 :     create_builtin_fn(g, BuiltinFnIdPopCount, "popCount", 2);
    7619                 :         21 :     create_builtin_fn(g, BuiltinFnIdBswap, "byteSwap", 2);
    7620                 :         21 :     create_builtin_fn(g, BuiltinFnIdBitReverse, "bitReverse", 2);
    7621                 :         21 :     create_builtin_fn(g, BuiltinFnIdImport, "import", 1);
    7622                 :         21 :     create_builtin_fn(g, BuiltinFnIdCImport, "cImport", 1);
    7623                 :         21 :     create_builtin_fn(g, BuiltinFnIdErrName, "errorName", 1);
    7624                 :         21 :     create_builtin_fn(g, BuiltinFnIdTypeName, "typeName", 1);
    7625                 :         21 :     create_builtin_fn(g, BuiltinFnIdEmbedFile, "embedFile", 1);
    7626                 :         21 :     create_builtin_fn(g, BuiltinFnIdCmpxchgWeak, "cmpxchgWeak", 6);
    7627                 :         21 :     create_builtin_fn(g, BuiltinFnIdCmpxchgStrong, "cmpxchgStrong", 6);
    7628                 :         21 :     create_builtin_fn(g, BuiltinFnIdFence, "fence", 1);
    7629                 :         21 :     create_builtin_fn(g, BuiltinFnIdTruncate, "truncate", 2);
    7630                 :         21 :     create_builtin_fn(g, BuiltinFnIdIntCast, "intCast", 2);
    7631                 :         21 :     create_builtin_fn(g, BuiltinFnIdFloatCast, "floatCast", 2);
    7632                 :         21 :     create_builtin_fn(g, BuiltinFnIdIntToFloat, "intToFloat", 2);
    7633                 :         21 :     create_builtin_fn(g, BuiltinFnIdFloatToInt, "floatToInt", 2);
    7634                 :         21 :     create_builtin_fn(g, BuiltinFnIdBoolToInt, "boolToInt", 1);
    7635                 :         21 :     create_builtin_fn(g, BuiltinFnIdErrToInt, "errorToInt", 1);
    7636                 :         21 :     create_builtin_fn(g, BuiltinFnIdIntToErr, "intToError", 1);
    7637                 :         21 :     create_builtin_fn(g, BuiltinFnIdEnumToInt, "enumToInt", 1);
    7638                 :         21 :     create_builtin_fn(g, BuiltinFnIdIntToEnum, "intToEnum", 2);
    7639                 :         21 :     create_builtin_fn(g, BuiltinFnIdCompileErr, "compileError", 1);
    7640                 :         21 :     create_builtin_fn(g, BuiltinFnIdCompileLog, "compileLog", SIZE_MAX);
    7641                 :         21 :     create_builtin_fn(g, BuiltinFnIdIntType, "IntType", 2); // TODO rename to Int
    7642                 :         21 :     create_builtin_fn(g, BuiltinFnIdVectorType, "Vector", 2);
    7643                 :         21 :     create_builtin_fn(g, BuiltinFnIdSetCold, "setCold", 1);
    7644                 :         21 :     create_builtin_fn(g, BuiltinFnIdSetRuntimeSafety, "setRuntimeSafety", 1);
    7645                 :         21 :     create_builtin_fn(g, BuiltinFnIdSetFloatMode, "setFloatMode", 1);
    7646                 :         21 :     create_builtin_fn(g, BuiltinFnIdPanic, "panic", 1);
    7647                 :         21 :     create_builtin_fn(g, BuiltinFnIdPtrCast, "ptrCast", 2);
    7648                 :         21 :     create_builtin_fn(g, BuiltinFnIdBitCast, "bitCast", 2);
    7649                 :         21 :     create_builtin_fn(g, BuiltinFnIdIntToPtr, "intToPtr", 2);
    7650                 :         21 :     create_builtin_fn(g, BuiltinFnIdPtrToInt, "ptrToInt", 1);
    7651                 :         21 :     create_builtin_fn(g, BuiltinFnIdTagName, "tagName", 1);
    7652                 :         21 :     create_builtin_fn(g, BuiltinFnIdTagType, "TagType", 1);
    7653                 :         21 :     create_builtin_fn(g, BuiltinFnIdFieldParentPtr, "fieldParentPtr", 3);
    7654                 :         21 :     create_builtin_fn(g, BuiltinFnIdByteOffsetOf, "byteOffsetOf", 2);
    7655                 :         21 :     create_builtin_fn(g, BuiltinFnIdBitOffsetOf, "bitOffsetOf", 2);
    7656                 :         21 :     create_builtin_fn(g, BuiltinFnIdDivExact, "divExact", 2);
    7657                 :         21 :     create_builtin_fn(g, BuiltinFnIdDivTrunc, "divTrunc", 2);
    7658                 :         21 :     create_builtin_fn(g, BuiltinFnIdDivFloor, "divFloor", 2);
    7659                 :         21 :     create_builtin_fn(g, BuiltinFnIdRem, "rem", 2);
    7660                 :         21 :     create_builtin_fn(g, BuiltinFnIdMod, "mod", 2);
    7661                 :         21 :     create_builtin_fn(g, BuiltinFnIdSqrt, "sqrt", 2);
    7662                 :         21 :     create_builtin_fn(g, BuiltinFnIdSin, "sin", 2);
    7663                 :         21 :     create_builtin_fn(g, BuiltinFnIdCos, "cos", 2);
    7664                 :         21 :     create_builtin_fn(g, BuiltinFnIdExp, "exp", 2);
    7665                 :         21 :     create_builtin_fn(g, BuiltinFnIdExp2, "exp2", 2);
    7666                 :         21 :     create_builtin_fn(g, BuiltinFnIdLn, "ln", 2);
    7667                 :         21 :     create_builtin_fn(g, BuiltinFnIdLog2, "log2", 2);
    7668                 :         21 :     create_builtin_fn(g, BuiltinFnIdLog10, "log10", 2);
    7669                 :         21 :     create_builtin_fn(g, BuiltinFnIdFabs, "fabs", 2);
    7670                 :         21 :     create_builtin_fn(g, BuiltinFnIdFloor, "floor", 2);
    7671                 :         21 :     create_builtin_fn(g, BuiltinFnIdCeil, "ceil", 2);
    7672                 :         21 :     create_builtin_fn(g, BuiltinFnIdTrunc, "trunc", 2);
    7673                 :         21 :     create_builtin_fn(g, BuiltinFnIdNearbyInt, "nearbyInt", 2);
    7674                 :         21 :     create_builtin_fn(g, BuiltinFnIdRound, "round", 2);
    7675                 :         21 :     create_builtin_fn(g, BuiltinFnIdMulAdd, "mulAdd", 4);
    7676                 :         21 :     create_builtin_fn(g, BuiltinFnIdInlineCall, "inlineCall", SIZE_MAX);
    7677                 :         21 :     create_builtin_fn(g, BuiltinFnIdNoInlineCall, "noInlineCall", SIZE_MAX);
    7678                 :         21 :     create_builtin_fn(g, BuiltinFnIdNewStackCall, "newStackCall", SIZE_MAX);
    7679                 :         21 :     create_builtin_fn(g, BuiltinFnIdAsyncCall, "asyncCall", SIZE_MAX);
    7680                 :         21 :     create_builtin_fn(g, BuiltinFnIdTypeId, "typeId", 1);
    7681                 :         21 :     create_builtin_fn(g, BuiltinFnIdShlExact, "shlExact", 2);
    7682                 :         21 :     create_builtin_fn(g, BuiltinFnIdShrExact, "shrExact", 2);
    7683                 :         21 :     create_builtin_fn(g, BuiltinFnIdSetEvalBranchQuota, "setEvalBranchQuota", 1);
    7684                 :         21 :     create_builtin_fn(g, BuiltinFnIdAlignCast, "alignCast", 2);
    7685                 :         21 :     create_builtin_fn(g, BuiltinFnIdOpaqueType, "OpaqueType", 0);
    7686                 :         21 :     create_builtin_fn(g, BuiltinFnIdSetAlignStack, "setAlignStack", 1);
    7687                 :         21 :     create_builtin_fn(g, BuiltinFnIdArgType, "ArgType", 2);
    7688                 :         21 :     create_builtin_fn(g, BuiltinFnIdExport, "export", 3);
    7689                 :         21 :     create_builtin_fn(g, BuiltinFnIdErrorReturnTrace, "errorReturnTrace", 0);
    7690                 :         21 :     create_builtin_fn(g, BuiltinFnIdAtomicRmw, "atomicRmw", 5);
    7691                 :         21 :     create_builtin_fn(g, BuiltinFnIdAtomicLoad, "atomicLoad", 3);
    7692                 :         21 :     create_builtin_fn(g, BuiltinFnIdErrSetCast, "errSetCast", 2);
    7693                 :         21 :     create_builtin_fn(g, BuiltinFnIdToBytes, "sliceToBytes", 1);
    7694                 :         21 :     create_builtin_fn(g, BuiltinFnIdFromBytes, "bytesToSlice", 2);
    7695                 :         21 :     create_builtin_fn(g, BuiltinFnIdThis, "This", 0);
    7696                 :         21 :     create_builtin_fn(g, BuiltinFnIdHasDecl, "hasDecl", 2);
    7697                 :         21 :     create_builtin_fn(g, BuiltinFnIdUnionInit, "unionInit", 3);
    7698                 :         21 :     create_builtin_fn(g, BuiltinFnIdFrameHandle, "frame", 0);
    7699                 :         21 :     create_builtin_fn(g, BuiltinFnIdFrameType, "Frame", 1);
    7700                 :         21 :     create_builtin_fn(g, BuiltinFnIdFrameAddress, "frameAddress", 0);
    7701                 :         21 :     create_builtin_fn(g, BuiltinFnIdFrameSize, "frameSize", 1);
    7702                 :         21 : }
    7703                 :            : 
    7704                 :         91 : static const char *bool_to_str(bool b) {
    7705         [ +  + ]:         91 :     return b ? "true" : "false";
    7706                 :            : }
    7707                 :            : 
    7708                 :         13 : static const char *build_mode_to_str(BuildMode build_mode) {
    7709   [ +  -  -  -  :         13 :     switch (build_mode) {
                      - ]
    7710                 :         13 :         case BuildModeDebug: return "Mode.Debug";
    7711                 :          0 :         case BuildModeSafeRelease: return "Mode.ReleaseSafe";
    7712                 :          0 :         case BuildModeFastRelease: return "Mode.ReleaseFast";
    7713                 :          0 :         case BuildModeSmallRelease: return "Mode.ReleaseSmall";
    7714                 :            :     }
    7715                 :          0 :     zig_unreachable();
    7716                 :            : }
    7717                 :            : 
    7718                 :          2 : static const char *subsystem_to_str(TargetSubsystem subsystem) {
    7719   [ +  -  -  -  :          2 :     switch (subsystem) {
          -  -  -  -  -  
                      - ]
    7720                 :          2 :         case TargetSubsystemConsole: return "Console";
    7721                 :          0 :         case TargetSubsystemWindows: return "Windows";
    7722                 :          0 :         case TargetSubsystemPosix: return "Posix";
    7723                 :          0 :         case TargetSubsystemNative: return "Native";
    7724                 :          0 :         case TargetSubsystemEfiApplication: return "EfiApplication";
    7725                 :          0 :         case TargetSubsystemEfiBootServiceDriver: return "EfiBootServiceDriver";
    7726                 :          0 :         case TargetSubsystemEfiRom: return "EfiRom";
    7727                 :          0 :         case TargetSubsystemEfiRuntimeDriver: return "EfiRuntimeDriver";
    7728                 :          0 :         case TargetSubsystemAuto: zig_unreachable();
    7729                 :            :     }
    7730                 :          0 :     zig_unreachable();
    7731                 :            : }
    7732                 :            : 
    7733                 :        115 : static bool detect_dynamic_link(CodeGen *g) {
    7734         [ +  + ]:        115 :     if (g->is_dynamic)
    7735                 :         10 :         return true;
    7736         [ -  + ]:        105 :     if (g->zig_target->os == OsFreestanding)
    7737                 :          0 :         return false;
    7738         [ +  + ]:        105 :     if (target_requires_pic(g->zig_target, g->libc_link_lib != nullptr))
    7739                 :         41 :         return true;
    7740                 :            :     // If there are no dynamic libraries then we can disable PIC
    7741         [ -  + ]:         64 :     for (size_t i = 0; i < g->link_libs_list.length; i += 1) {
    7742                 :          0 :         LinkLib *link_lib = g->link_libs_list.at(i);
    7743         [ #  # ]:          0 :         if (target_is_libc_lib_name(g->zig_target, buf_ptr(link_lib->name)))
    7744                 :          0 :             continue;
    7745                 :          0 :         return true;
    7746                 :            :     }
    7747                 :         64 :     return false;
    7748                 :            : }
    7749                 :            : 
    7750                 :        115 : static bool detect_pic(CodeGen *g) {
    7751         [ +  + ]:        115 :     if (target_requires_pic(g->zig_target, g->libc_link_lib != nullptr))
    7752                 :         41 :         return true;
    7753   [ +  +  +  - ]:         74 :     switch (g->want_pic) {
    7754                 :          9 :         case WantPICDisabled:
    7755                 :          9 :             return false;
    7756                 :         52 :         case WantPICEnabled:
    7757                 :         52 :             return true;
    7758                 :         13 :         case WantPICAuto:
    7759                 :         13 :             return g->have_dynamic_link;
    7760                 :            :     }
    7761                 :          0 :     zig_unreachable();
    7762                 :            : }
    7763                 :            : 
    7764                 :         34 : static bool detect_stack_probing(CodeGen *g) {
    7765         [ +  + ]:         34 :     if (!target_supports_stack_probing(g->zig_target))
    7766                 :          7 :         return false;
    7767   [ +  -  +  - ]:         27 :     switch (g->want_stack_check) {
    7768                 :         12 :         case WantStackCheckDisabled:
    7769                 :         12 :             return false;
    7770                 :          0 :         case WantStackCheckEnabled:
    7771                 :          0 :             return true;
    7772                 :         15 :         case WantStackCheckAuto:
    7773 [ +  - ][ +  - ]:         15 :             return g->build_mode == BuildModeSafeRelease || g->build_mode == BuildModeDebug;
    7774                 :            :     }
    7775                 :          0 :     zig_unreachable();
    7776                 :            : }
    7777                 :            : 
    7778                 :            : // Returns TargetSubsystemAuto to mean "no subsystem"
    7779                 :        112 : TargetSubsystem detect_subsystem(CodeGen *g) {
    7780         [ -  + ]:        112 :     if (g->subsystem != TargetSubsystemAuto)
    7781                 :          0 :         return g->subsystem;
    7782         [ +  + ]:        112 :     if (g->zig_target->os == OsWindows) {
    7783 [ +  - ][ +  + ]:         17 :         if (g->have_dllmain_crt_startup || (g->out_type == OutTypeLib && g->is_dynamic))
                 [ -  + ]
    7784                 :          0 :             return TargetSubsystemAuto;
    7785 [ +  - ][ +  - ]:         17 :         if (g->have_c_main || g->have_pub_main || g->is_test_build)
                 [ +  + ]
    7786                 :         10 :             return TargetSubsystemConsole;
    7787 [ +  - ][ -  + ]:          7 :         if (g->have_winmain || g->have_winmain_crt_startup)
    7788                 :          0 :             return TargetSubsystemWindows;
    7789         [ -  + ]:         95 :     } else if (g->zig_target->os == OsUefi) {
    7790                 :          0 :         return TargetSubsystemEfiApplication;
    7791                 :            :     }
    7792                 :        102 :     return TargetSubsystemAuto;
    7793                 :            : }
    7794                 :            : 
    7795                 :        115 : static bool detect_single_threaded(CodeGen *g) {
    7796         [ +  + ]:        115 :     if (g->want_single_threaded)
    7797                 :         16 :         return true;
    7798         [ -  + ]:         99 :     if (target_is_single_threaded(g->zig_target)) {
    7799                 :          0 :         return true;
    7800                 :            :     }
    7801                 :         99 :     return false;
    7802                 :            : }
    7803                 :            : 
    7804                 :        115 : static bool detect_err_ret_tracing(CodeGen *g) {
    7805         [ +  - ]:        115 :     return !g->strip_debug_symbols &&
    7806 [ +  - ][ +  - ]:        230 :         g->build_mode != BuildModeFastRelease &&
    7807                 :        115 :         g->build_mode != BuildModeSmallRelease;
    7808                 :            : }
    7809                 :            : 
    7810                 :         13 : Buf *codegen_generate_builtin_source(CodeGen *g) {
    7811                 :         13 :     g->have_dynamic_link = detect_dynamic_link(g);
    7812                 :         13 :     g->have_pic = detect_pic(g);
    7813                 :         13 :     g->have_stack_probing = detect_stack_probing(g);
    7814                 :         13 :     g->is_single_threaded = detect_single_threaded(g);
    7815                 :         13 :     g->have_err_ret_tracing = detect_err_ret_tracing(g);
    7816                 :            : 
    7817                 :         13 :     Buf *contents = buf_alloc();
    7818                 :            : 
    7819                 :            :     // NOTE: when editing this file, you may need to make modifications to the
    7820                 :            :     // cache input parameters in define_builtin_compile_vars
    7821                 :            : 
    7822                 :            :     // Modifications to this struct must be coordinated with code that does anything with
    7823                 :            :     // g->stack_trace_type. There are hard-coded references to the field indexes.
    7824                 :         13 :     buf_append_str(contents,
    7825                 :            :         "pub const StackTrace = struct {\n"
    7826                 :            :         "    index: usize,\n"
    7827                 :            :         "    instruction_addresses: []usize,\n"
    7828                 :            :         "};\n\n");
    7829                 :            : 
    7830                 :         13 :     buf_append_str(contents, "pub const PanicFn = fn([]const u8, ?*StackTrace) noreturn;\n\n");
    7831                 :            : 
    7832                 :         13 :     const char *cur_os = nullptr;
    7833                 :            :     {
    7834                 :         13 :         buf_appendf(contents, "pub const Os = enum {\n");
    7835                 :         13 :         uint32_t field_count = (uint32_t)target_os_count();
    7836         [ +  + ]:        481 :         for (uint32_t i = 0; i < field_count; i += 1) {
    7837                 :        468 :             Os os_type = target_os_enum(i);
    7838                 :        468 :             const char *name = target_os_name(os_type);
    7839                 :        468 :             buf_appendf(contents, "    %s,\n", name);
    7840                 :            : 
    7841         [ +  + ]:        468 :             if (os_type == g->zig_target->os) {
    7842                 :         13 :                 g->target_os_index = i;
    7843                 :         13 :                 cur_os = name;
    7844                 :            :             }
    7845                 :            :         }
    7846                 :         13 :         buf_appendf(contents, "};\n\n");
    7847                 :            :     }
    7848                 :         13 :     assert(cur_os != nullptr);
    7849                 :            : 
    7850                 :         13 :     const char *cur_arch = nullptr;
    7851                 :            :     {
    7852                 :         13 :         buf_appendf(contents, "pub const Arch = union(enum) {\n");
    7853                 :         13 :         uint32_t field_count = (uint32_t)target_arch_count();
    7854         [ +  + ]:        650 :         for (uint32_t arch_i = 0; arch_i < field_count; arch_i += 1) {
    7855                 :        637 :             ZigLLVM_ArchType arch = target_arch_enum(arch_i);
    7856                 :        637 :             const char *arch_name = target_arch_name(arch);
    7857                 :        637 :             SubArchList sub_arch_list = target_subarch_list(arch);
    7858         [ +  + ]:        637 :             if (sub_arch_list == SubArchListNone) {
    7859                 :        546 :                 buf_appendf(contents, "    %s,\n", arch_name);
    7860         [ +  + ]:        546 :                 if (arch == g->zig_target->arch) {
    7861                 :         13 :                     g->target_arch_index = arch_i;
    7862                 :         13 :                     cur_arch = buf_ptr(buf_sprintf("Arch.%s", arch_name));
    7863                 :            :                 }
    7864                 :            :             } else {
    7865                 :         91 :                 const char *sub_arch_list_name = target_subarch_list_name(sub_arch_list);
    7866                 :         91 :                 buf_appendf(contents, "    %s: %s,\n", arch_name, sub_arch_list_name);
    7867         [ -  + ]:         91 :                 if (arch == g->zig_target->arch) {
    7868                 :          0 :                     size_t sub_count = target_subarch_count(sub_arch_list);
    7869         [ #  # ]:          0 :                     for (size_t sub_i = 0; sub_i < sub_count; sub_i += 1) {
    7870                 :          0 :                         ZigLLVM_SubArchType sub = target_subarch_enum(sub_arch_list, sub_i);
    7871         [ #  # ]:          0 :                         if (sub == g->zig_target->sub_arch) {
    7872                 :          0 :                             g->target_sub_arch_index = sub_i;
    7873                 :          0 :                             cur_arch = buf_ptr(buf_sprintf("Arch{ .%s = Arch.%s.%s }",
    7874                 :            :                                         arch_name, sub_arch_list_name, target_subarch_name(sub)));
    7875                 :            :                         }
    7876                 :            :                     }
    7877                 :            :                 }
    7878                 :            :             }
    7879                 :            :         }
    7880                 :            : 
    7881                 :         13 :         uint32_t list_count = target_subarch_list_count();
    7882                 :            :         // start at index 1 to skip None
    7883         [ +  + ]:         65 :         for (uint32_t list_i = 1; list_i < list_count; list_i += 1) {
    7884                 :         52 :             SubArchList sub_arch_list = target_subarch_list_enum(list_i);
    7885                 :         52 :             const char *subarch_list_name = target_subarch_list_name(sub_arch_list);
    7886                 :         52 :             buf_appendf(contents, "    pub const %s = enum {\n", subarch_list_name);
    7887                 :         52 :             size_t sub_count = target_subarch_count(sub_arch_list);
    7888         [ +  + ]:        507 :             for (size_t sub_i = 0; sub_i < sub_count; sub_i += 1) {
    7889                 :        455 :                 ZigLLVM_SubArchType sub = target_subarch_enum(sub_arch_list, sub_i);
    7890                 :        455 :                 buf_appendf(contents, "        %s,\n", target_subarch_name(sub));
    7891                 :            :             }
    7892                 :         52 :             buf_appendf(contents, "    };\n");
    7893                 :            :         }
    7894                 :         13 :         buf_appendf(contents, "};\n\n");
    7895                 :            :     }
    7896                 :         13 :     assert(cur_arch != nullptr);
    7897                 :            : 
    7898                 :         13 :     const char *cur_abi = nullptr;
    7899                 :            :     {
    7900                 :         13 :         buf_appendf(contents, "pub const Abi = enum {\n");
    7901                 :         13 :         uint32_t field_count = (uint32_t)target_abi_count();
    7902         [ +  + ]:        260 :         for (uint32_t i = 0; i < field_count; i += 1) {
    7903                 :        247 :             ZigLLVM_EnvironmentType abi = target_abi_enum(i);
    7904                 :        247 :             const char *name = target_abi_name(abi);
    7905                 :        247 :             buf_appendf(contents, "    %s,\n", name);
    7906                 :            : 
    7907         [ +  + ]:        247 :             if (abi == g->zig_target->abi) {
    7908                 :         13 :                 g->target_abi_index = i;
    7909                 :         13 :                 cur_abi = name;
    7910                 :            :             }
    7911                 :            :         }
    7912                 :         13 :         buf_appendf(contents, "};\n\n");
    7913                 :            :     }
    7914                 :         13 :     assert(cur_abi != nullptr);
    7915                 :            : 
    7916                 :         13 :     const char *cur_obj_fmt = nullptr;
    7917                 :            :     {
    7918                 :         13 :         buf_appendf(contents, "pub const ObjectFormat = enum {\n");
    7919                 :         13 :         uint32_t field_count = (uint32_t)target_oformat_count();
    7920         [ +  + ]:         78 :         for (uint32_t i = 0; i < field_count; i += 1) {
    7921                 :         65 :             ZigLLVM_ObjectFormatType oformat = target_oformat_enum(i);
    7922                 :         65 :             const char *name = target_oformat_name(oformat);
    7923                 :         65 :             buf_appendf(contents, "    %s,\n", name);
    7924                 :            : 
    7925                 :         65 :             ZigLLVM_ObjectFormatType target_oformat = target_object_format(g->zig_target);
    7926         [ +  + ]:         65 :             if (oformat == target_oformat) {
    7927                 :         13 :                 g->target_oformat_index = i;
    7928                 :         13 :                 cur_obj_fmt = name;
    7929                 :            :             }
    7930                 :            :         }
    7931                 :            : 
    7932                 :         13 :         buf_appendf(contents, "};\n\n");
    7933                 :            :     }
    7934                 :         13 :     assert(cur_obj_fmt != nullptr);
    7935                 :            : 
    7936                 :            :     {
    7937                 :         13 :         buf_appendf(contents, "pub const GlobalLinkage = enum {\n");
    7938                 :         13 :         uint32_t field_count = array_length(global_linkage_values);
    7939         [ +  + ]:         65 :         for (uint32_t i = 0; i < field_count; i += 1) {
    7940                 :         52 :             const GlobalLinkageValue *value = &global_linkage_values[i];
    7941                 :         52 :             buf_appendf(contents, "    %s,\n", value->name);
    7942                 :            :         }
    7943                 :         13 :         buf_appendf(contents, "};\n\n");
    7944                 :            :     }
    7945                 :            :     {
    7946                 :         13 :         buf_appendf(contents,
    7947                 :            :             "pub const AtomicOrder = enum {\n"
    7948                 :            :             "    Unordered,\n"
    7949                 :            :             "    Monotonic,\n"
    7950                 :            :             "    Acquire,\n"
    7951                 :            :             "    Release,\n"
    7952                 :            :             "    AcqRel,\n"
    7953                 :            :             "    SeqCst,\n"
    7954                 :            :             "};\n\n");
    7955                 :            :     }
    7956                 :            :     {
    7957                 :         13 :         buf_appendf(contents,
    7958                 :            :             "pub const AtomicRmwOp = enum {\n"
    7959                 :            :             "    Xchg,\n"
    7960                 :            :             "    Add,\n"
    7961                 :            :             "    Sub,\n"
    7962                 :            :             "    And,\n"
    7963                 :            :             "    Nand,\n"
    7964                 :            :             "    Or,\n"
    7965                 :            :             "    Xor,\n"
    7966                 :            :             "    Max,\n"
    7967                 :            :             "    Min,\n"
    7968                 :            :             "};\n\n");
    7969                 :            :     }
    7970                 :            :     {
    7971                 :         13 :         buf_appendf(contents,
    7972                 :            :             "pub const Mode = enum {\n"
    7973                 :            :             "    Debug,\n"
    7974                 :            :             "    ReleaseSafe,\n"
    7975                 :            :             "    ReleaseFast,\n"
    7976                 :            :             "    ReleaseSmall,\n"
    7977                 :            :             "};\n\n");
    7978                 :            :     }
    7979                 :            :     {
    7980                 :         13 :         buf_appendf(contents, "pub const TypeId = enum {\n");
    7981                 :         13 :         size_t field_count = type_id_len();
    7982         [ +  + ]:        351 :         for (size_t i = 0; i < field_count; i += 1) {
    7983                 :        338 :             const ZigTypeId id = type_id_at_index(i);
    7984                 :        338 :             buf_appendf(contents, "    %s,\n", type_id_name(id));
    7985                 :            :         }
    7986                 :         13 :         buf_appendf(contents, "};\n\n");
    7987                 :            :     }
    7988                 :            :     {
    7989                 :         13 :         buf_appendf(contents,
    7990                 :            :             "pub const TypeInfo = union(TypeId) {\n"
    7991                 :            :             "    Type: void,\n"
    7992                 :            :             "    Void: void,\n"
    7993                 :            :             "    Bool: void,\n"
    7994                 :            :             "    NoReturn: void,\n"
    7995                 :            :             "    Int: Int,\n"
    7996                 :            :             "    Float: Float,\n"
    7997                 :            :             "    Pointer: Pointer,\n"
    7998                 :            :             "    Array: Array,\n"
    7999                 :            :             "    Struct: Struct,\n"
    8000                 :            :             "    ComptimeFloat: void,\n"
    8001                 :            :             "    ComptimeInt: void,\n"
    8002                 :            :             "    Undefined: void,\n"
    8003                 :            :             "    Null: void,\n"
    8004                 :            :             "    Optional: Optional,\n"
    8005                 :            :             "    ErrorUnion: ErrorUnion,\n"
    8006                 :            :             "    ErrorSet: ErrorSet,\n"
    8007                 :            :             "    Enum: Enum,\n"
    8008                 :            :             "    Union: Union,\n"
    8009                 :            :             "    Fn: Fn,\n"
    8010                 :            :             "    BoundFn: Fn,\n"
    8011                 :            :             "    ArgTuple: void,\n"
    8012                 :            :             "    Opaque: void,\n"
    8013                 :            :             "    Frame: void,\n"
    8014                 :            :             "    AnyFrame: AnyFrame,\n"
    8015                 :            :             "    Vector: Vector,\n"
    8016                 :            :             "    EnumLiteral: void,\n"
    8017                 :            :             "\n\n"
    8018                 :            :             "    pub const Int = struct {\n"
    8019                 :            :             "        is_signed: bool,\n"
    8020                 :            :             "        bits: comptime_int,\n"
    8021                 :            :             "    };\n"
    8022                 :            :             "\n"
    8023                 :            :             "    pub const Float = struct {\n"
    8024                 :            :             "        bits: comptime_int,\n"
    8025                 :            :             "    };\n"
    8026                 :            :             "\n"
    8027                 :            :             "    pub const Pointer = struct {\n"
    8028                 :            :             "        size: Size,\n"
    8029                 :            :             "        is_const: bool,\n"
    8030                 :            :             "        is_volatile: bool,\n"
    8031                 :            :             "        alignment: comptime_int,\n"
    8032                 :            :             "        child: type,\n"
    8033                 :            :             "        is_allowzero: bool,\n"
    8034                 :            :             "\n"
    8035                 :            :             "        pub const Size = enum {\n"
    8036                 :            :             "            One,\n"
    8037                 :            :             "            Many,\n"
    8038                 :            :             "            Slice,\n"
    8039                 :            :             "            C,\n"
    8040                 :            :             "        };\n"
    8041                 :            :             "    };\n"
    8042                 :            :             "\n"
    8043                 :            :             "    pub const Array = struct {\n"
    8044                 :            :             "        len: comptime_int,\n"
    8045                 :            :             "        child: type,\n"
    8046                 :            :             "    };\n"
    8047                 :            :             "\n"
    8048                 :            :             "    pub const ContainerLayout = enum {\n"
    8049                 :            :             "        Auto,\n"
    8050                 :            :             "        Extern,\n"
    8051                 :            :             "        Packed,\n"
    8052                 :            :             "    };\n"
    8053                 :            :             "\n"
    8054                 :            :             "    pub const StructField = struct {\n"
    8055                 :            :             "        name: []const u8,\n"
    8056                 :            :             "        offset: ?comptime_int,\n"
    8057                 :            :             "        field_type: type,\n"
    8058                 :            :             "    };\n"
    8059                 :            :             "\n"
    8060                 :            :             "    pub const Struct = struct {\n"
    8061                 :            :             "        layout: ContainerLayout,\n"
    8062                 :            :             "        fields: []StructField,\n"
    8063                 :            :             "        decls: []Declaration,\n"
    8064                 :            :             "    };\n"
    8065                 :            :             "\n"
    8066                 :            :             "    pub const Optional = struct {\n"
    8067                 :            :             "        child: type,\n"
    8068                 :            :             "    };\n"
    8069                 :            :             "\n"
    8070                 :            :             "    pub const ErrorUnion = struct {\n"
    8071                 :            :             "        error_set: type,\n"
    8072                 :            :             "        payload: type,\n"
    8073                 :            :             "    };\n"
    8074                 :            :             "\n"
    8075                 :            :             "    pub const Error = struct {\n"
    8076                 :            :             "        name: []const u8,\n"
    8077                 :            :             "        value: comptime_int,\n"
    8078                 :            :             "    };\n"
    8079                 :            :             "\n"
    8080                 :            :             "    pub const ErrorSet = ?[]Error;\n"
    8081                 :            :             "\n"
    8082                 :            :             "    pub const EnumField = struct {\n"
    8083                 :            :             "        name: []const u8,\n"
    8084                 :            :             "        value: comptime_int,\n"
    8085                 :            :             "    };\n"
    8086                 :            :             "\n"
    8087                 :            :             "    pub const Enum = struct {\n"
    8088                 :            :             "        layout: ContainerLayout,\n"
    8089                 :            :             "        tag_type: type,\n"
    8090                 :            :             "        fields: []EnumField,\n"
    8091                 :            :             "        decls: []Declaration,\n"
    8092                 :            :             "    };\n"
    8093                 :            :             "\n"
    8094                 :            :             "    pub const UnionField = struct {\n"
    8095                 :            :             "        name: []const u8,\n"
    8096                 :            :             "        enum_field: ?EnumField,\n"
    8097                 :            :             "        field_type: type,\n"
    8098                 :            :             "    };\n"
    8099                 :            :             "\n"
    8100                 :            :             "    pub const Union = struct {\n"
    8101                 :            :             "        layout: ContainerLayout,\n"
    8102                 :            :             "        tag_type: ?type,\n"
    8103                 :            :             "        fields: []UnionField,\n"
    8104                 :            :             "        decls: []Declaration,\n"
    8105                 :            :             "    };\n"
    8106                 :            :             "\n"
    8107                 :            :             "    pub const CallingConvention = enum {\n"
    8108                 :            :             "        Unspecified,\n"
    8109                 :            :             "        C,\n"
    8110                 :            :             "        Cold,\n"
    8111                 :            :             "        Naked,\n"
    8112                 :            :             "        Stdcall,\n"
    8113                 :            :             "        Async,\n"
    8114                 :            :             "    };\n"
    8115                 :            :             "\n"
    8116                 :            :             "    pub const FnArg = struct {\n"
    8117                 :            :             "        is_generic: bool,\n"
    8118                 :            :             "        is_noalias: bool,\n"
    8119                 :            :             "        arg_type: ?type,\n"
    8120                 :            :             "    };\n"
    8121                 :            :             "\n"
    8122                 :            :             "    pub const Fn = struct {\n"
    8123                 :            :             "        calling_convention: CallingConvention,\n"
    8124                 :            :             "        is_generic: bool,\n"
    8125                 :            :             "        is_var_args: bool,\n"
    8126                 :            :             "        return_type: ?type,\n"
    8127                 :            :             "        args: []FnArg,\n"
    8128                 :            :             "    };\n"
    8129                 :            :             "\n"
    8130                 :            :             "    pub const AnyFrame = struct {\n"
    8131                 :            :             "        child: ?type,\n"
    8132                 :            :             "    };\n"
    8133                 :            :             "\n"
    8134                 :            :             "    pub const Vector = struct {\n"
    8135                 :            :             "        len: comptime_int,\n"
    8136                 :            :             "        child: type,\n"
    8137                 :            :             "    };\n"
    8138                 :            :             "\n"
    8139                 :            :             "    pub const Declaration = struct {\n"
    8140                 :            :             "        name: []const u8,\n"
    8141                 :            :             "        is_pub: bool,\n"
    8142                 :            :             "        data: Data,\n"
    8143                 :            :             "\n"
    8144                 :            :             "        pub const Data = union(enum) {\n"
    8145                 :            :             "            Type: type,\n"
    8146                 :            :             "            Var: type,\n"
    8147                 :            :             "            Fn: FnDecl,\n"
    8148                 :            :             "\n"
    8149                 :            :             "            pub const FnDecl = struct {\n"
    8150                 :            :             "                fn_type: type,\n"
    8151                 :            :             "                inline_type: Inline,\n"
    8152                 :            :             "                calling_convention: CallingConvention,\n"
    8153                 :            :             "                is_var_args: bool,\n"
    8154                 :            :             "                is_extern: bool,\n"
    8155                 :            :             "                is_export: bool,\n"
    8156                 :            :             "                lib_name: ?[]const u8,\n"
    8157                 :            :             "                return_type: type,\n"
    8158                 :            :             "                arg_names: [][] const u8,\n"
    8159                 :            :             "\n"
    8160                 :            :             "                pub const Inline = enum {\n"
    8161                 :            :             "                    Auto,\n"
    8162                 :            :             "                    Always,\n"
    8163                 :            :             "                    Never,\n"
    8164                 :            :             "                };\n"
    8165                 :            :             "            };\n"
    8166                 :            :             "        };\n"
    8167                 :            :             "    };\n"
    8168                 :            :             "};\n\n");
    8169                 :            :         static_assert(ContainerLayoutAuto == 0, "");
    8170                 :            :         static_assert(ContainerLayoutExtern == 1, "");
    8171                 :            :         static_assert(ContainerLayoutPacked == 2, "");
    8172                 :            : 
    8173                 :            :         static_assert(CallingConventionUnspecified == 0, "");
    8174                 :            :         static_assert(CallingConventionC == 1, "");
    8175                 :            :         static_assert(CallingConventionCold == 2, "");
    8176                 :            :         static_assert(CallingConventionNaked == 3, "");
    8177                 :            :         static_assert(CallingConventionStdcall == 4, "");
    8178                 :            :         static_assert(CallingConventionAsync == 5, "");
    8179                 :            : 
    8180                 :            :         static_assert(FnInlineAuto == 0, "");
    8181                 :            :         static_assert(FnInlineAlways == 1, "");
    8182                 :            :         static_assert(FnInlineNever == 2, "");
    8183                 :            : 
    8184                 :            :         static_assert(BuiltinPtrSizeOne == 0, "");
    8185                 :            :         static_assert(BuiltinPtrSizeMany == 1, "");
    8186                 :            :         static_assert(BuiltinPtrSizeSlice == 2, "");
    8187                 :            :         static_assert(BuiltinPtrSizeC == 3, "");
    8188                 :            :     }
    8189                 :            :     {
    8190                 :         13 :         buf_appendf(contents,
    8191                 :            :             "pub const FloatMode = enum {\n"
    8192                 :            :             "    Strict,\n"
    8193                 :            :             "    Optimized,\n"
    8194                 :            :             "};\n\n");
    8195                 :         13 :         assert(FloatModeStrict == 0);
    8196                 :         13 :         assert(FloatModeOptimized == 1);
    8197                 :            :     }
    8198                 :            :     {
    8199                 :         13 :         buf_appendf(contents,
    8200                 :            :             "pub const Endian = enum {\n"
    8201                 :            :             "    Big,\n"
    8202                 :            :             "    Little,\n"
    8203                 :            :             "};\n\n");
    8204                 :            :         //assert(EndianBig == 0);
    8205                 :            :         //assert(EndianLittle == 1);
    8206                 :            :     }
    8207                 :            :     {
    8208                 :         13 :         buf_appendf(contents,
    8209                 :            :             "pub const Version = struct {\n"
    8210                 :            :             "    major: u32,\n"
    8211                 :            :             "    minor: u32,\n"
    8212                 :            :             "    patch: u32,\n"
    8213                 :            :             "};\n\n");
    8214                 :            :     }
    8215                 :            :     {
    8216                 :         13 :         buf_appendf(contents,
    8217                 :            :         "pub const SubSystem = enum {\n"
    8218                 :            :         "    Console,\n"
    8219                 :            :         "    Windows,\n"
    8220                 :            :         "    Posix,\n"
    8221                 :            :         "    Native,\n"
    8222                 :            :         "    EfiApplication,\n"
    8223                 :            :         "    EfiBootServiceDriver,\n"
    8224                 :            :         "    EfiRom,\n"
    8225                 :            :         "    EfiRuntimeDriver,\n"
    8226                 :            :         "};\n\n");
    8227                 :            : 
    8228                 :         13 :         assert(TargetSubsystemConsole == 0);
    8229                 :         13 :         assert(TargetSubsystemWindows == 1);
    8230                 :         13 :         assert(TargetSubsystemPosix == 2);
    8231                 :         13 :         assert(TargetSubsystemNative == 3);
    8232                 :         13 :         assert(TargetSubsystemEfiApplication == 4);
    8233                 :         13 :         assert(TargetSubsystemEfiBootServiceDriver == 5);
    8234                 :         13 :         assert(TargetSubsystemEfiRom == 6);
    8235                 :         13 :         assert(TargetSubsystemEfiRuntimeDriver == 7);
    8236                 :            :     }
    8237                 :            :     {
    8238         [ -  + ]:         13 :         const char *endian_str = g->is_big_endian ? "Endian.Big" : "Endian.Little";
    8239                 :         13 :         buf_appendf(contents, "pub const endian = %s;\n", endian_str);
    8240                 :            :     }
    8241                 :         13 :     buf_appendf(contents, "pub const is_test = %s;\n", bool_to_str(g->is_test_build));
    8242                 :         13 :     buf_appendf(contents, "pub const single_threaded = %s;\n", bool_to_str(g->is_single_threaded));
    8243                 :         13 :     buf_appendf(contents, "pub const os = Os.%s;\n", cur_os);
    8244                 :         13 :     buf_appendf(contents, "pub const arch = %s;\n", cur_arch);
    8245                 :         13 :     buf_appendf(contents, "pub const abi = Abi.%s;\n", cur_abi);
    8246 [ +  + ][ +  + ]:         13 :     if (g->libc_link_lib != nullptr && g->zig_target->glibc_version != nullptr) {
    8247                 :          3 :         buf_appendf(contents,
    8248                 :            :             "pub const glibc_version: ?Version = Version{.major = %d, .minor = %d, .patch = %d};\n",
    8249                 :          3 :                 g->zig_target->glibc_version->major,
    8250                 :          3 :                 g->zig_target->glibc_version->minor,
    8251                 :          3 :                 g->zig_target->glibc_version->patch);
    8252                 :            :     } else {
    8253                 :         10 :         buf_appendf(contents, "pub const glibc_version: ?Version = null;\n");
    8254                 :            :     }
    8255                 :         13 :     buf_appendf(contents, "pub const object_format = ObjectFormat.%s;\n", cur_obj_fmt);
    8256                 :         13 :     buf_appendf(contents, "pub const mode = %s;\n", build_mode_to_str(g->build_mode));
    8257                 :         13 :     buf_appendf(contents, "pub const link_libc = %s;\n", bool_to_str(g->libc_link_lib != nullptr));
    8258                 :         13 :     buf_appendf(contents, "pub const have_error_return_tracing = %s;\n", bool_to_str(g->have_err_ret_tracing));
    8259                 :         13 :     buf_appendf(contents, "pub const valgrind_support = %s;\n", bool_to_str(want_valgrind_support(g)));
    8260                 :         13 :     buf_appendf(contents, "pub const position_independent_code = %s;\n", bool_to_str(g->have_pic));
    8261                 :         13 :     buf_appendf(contents, "pub const strip_debug_info = %s;\n", bool_to_str(g->strip_debug_symbols));
    8262                 :            : 
    8263                 :            :     {
    8264                 :         13 :         TargetSubsystem detected_subsystem = detect_subsystem(g);
    8265         [ +  + ]:         13 :         if (detected_subsystem != TargetSubsystemAuto) {
    8266                 :          2 :             buf_appendf(contents, "pub const subsystem = SubSystem.%s;\n", subsystem_to_str(detected_subsystem));
    8267                 :            :         }
    8268                 :            :     }
    8269                 :            : 
    8270         [ +  + ]:         13 :     if (g->is_test_build) {
    8271                 :          8 :         buf_appendf(contents,
    8272                 :            :             "const TestFn = struct {\n"
    8273                 :            :                 "name: []const u8,\n"
    8274                 :            :                 "func: fn()anyerror!void,\n"
    8275                 :            :             "};\n"
    8276                 :            :             "pub const test_functions = {}; // overwritten later\n"
    8277                 :            :         );
    8278                 :            :     }
    8279                 :            : 
    8280                 :         13 :     return contents;
    8281                 :            : }
    8282                 :            : 
    8283                 :          8 : static ZigPackage *create_test_runner_pkg(CodeGen *g) {
    8284                 :          8 :     return codegen_create_package(g, buf_ptr(g->zig_std_special_dir), "test_runner.zig", "std.special");
    8285                 :            : }
    8286                 :            : 
    8287                 :          9 : static ZigPackage *create_panic_pkg(CodeGen *g) {
    8288                 :          9 :     return codegen_create_package(g, buf_ptr(g->zig_std_special_dir), "panic.zig", "std.special");
    8289                 :            : }
    8290                 :            : 
    8291                 :         21 : static Error define_builtin_compile_vars(CodeGen *g) {
    8292         [ -  + ]:         21 :     if (g->std_package == nullptr)
    8293                 :          0 :         return ErrorNone;
    8294                 :            : 
    8295                 :            :     Error err;
    8296                 :            : 
    8297                 :         21 :     Buf *manifest_dir = buf_alloc();
    8298                 :         21 :     os_path_join(get_stage1_cache_path(), buf_create_from_str("builtin"), manifest_dir);
    8299                 :            : 
    8300                 :            :     CacheHash cache_hash;
    8301                 :         21 :     cache_init(&cache_hash, manifest_dir);
    8302                 :            : 
    8303                 :            :     Buf *compiler_id;
    8304         [ -  + ]:         21 :     if ((err = get_compiler_id(&compiler_id)))
    8305                 :          0 :         return err;
    8306                 :            : 
    8307                 :            :     // Only a few things affect builtin.zig
    8308                 :         21 :     cache_buf(&cache_hash, compiler_id);
    8309                 :         21 :     cache_int(&cache_hash, g->build_mode);
    8310                 :         21 :     cache_bool(&cache_hash, g->strip_debug_symbols);
    8311                 :         21 :     cache_bool(&cache_hash, g->is_test_build);
    8312                 :         21 :     cache_bool(&cache_hash, g->is_single_threaded);
    8313                 :         21 :     cache_int(&cache_hash, g->zig_target->is_native);
    8314                 :         21 :     cache_int(&cache_hash, g->zig_target->arch);
    8315                 :         21 :     cache_int(&cache_hash, g->zig_target->sub_arch);
    8316                 :         21 :     cache_int(&cache_hash, g->zig_target->vendor);
    8317                 :         21 :     cache_int(&cache_hash, g->zig_target->os);
    8318                 :         21 :     cache_int(&cache_hash, g->zig_target->abi);
    8319         [ +  + ]:         21 :     if (g->zig_target->glibc_version != nullptr) {
    8320                 :         14 :         cache_int(&cache_hash, g->zig_target->glibc_version->major);
    8321                 :         14 :         cache_int(&cache_hash, g->zig_target->glibc_version->minor);
    8322                 :         14 :         cache_int(&cache_hash, g->zig_target->glibc_version->patch);
    8323                 :            :     }
    8324                 :         21 :     cache_bool(&cache_hash, g->have_err_ret_tracing);
    8325                 :         21 :     cache_bool(&cache_hash, g->libc_link_lib != nullptr);
    8326                 :         21 :     cache_bool(&cache_hash, g->valgrind_support);
    8327                 :         21 :     cache_int(&cache_hash, detect_subsystem(g));
    8328                 :            : 
    8329                 :         21 :     Buf digest = BUF_INIT;
    8330                 :         21 :     buf_resize(&digest, 0);
    8331         [ -  + ]:         21 :     if ((err = cache_hit(&cache_hash, &digest))) {
    8332                 :            :         // Treat an invalid format error as a cache miss.
    8333         [ #  # ]:          0 :         if (err != ErrorInvalidFormat)
    8334                 :          0 :             return err;
    8335                 :            :     }
    8336                 :            : 
    8337                 :            :     // We should always get a cache hit because there are no
    8338                 :            :     // files in the input hash.
    8339                 :         21 :     assert(buf_len(&digest) != 0);
    8340                 :            : 
    8341                 :         21 :     Buf *this_dir = buf_alloc();
    8342                 :         21 :     os_path_join(manifest_dir, &digest, this_dir);
    8343                 :            : 
    8344         [ -  + ]:         21 :     if ((err = os_make_path(this_dir)))
    8345                 :          0 :         return err;
    8346                 :            : 
    8347                 :         21 :     const char *builtin_zig_basename = "builtin.zig";
    8348                 :         21 :     Buf *builtin_zig_path = buf_alloc();
    8349                 :         21 :     os_path_join(this_dir, buf_create_from_str(builtin_zig_basename), builtin_zig_path);
    8350                 :            : 
    8351                 :            :     bool hit;
    8352         [ -  + ]:         21 :     if ((err = os_file_exists(builtin_zig_path, &hit)))
    8353                 :          0 :         return err;
    8354                 :            :     Buf *contents;
    8355         [ +  + ]:         21 :     if (hit) {
    8356                 :          8 :         contents = buf_alloc();
    8357         [ -  + ]:          8 :         if ((err = os_fetch_file_path(builtin_zig_path, contents))) {
    8358                 :          0 :             fprintf(stderr, "Unable to open '%s': %s\n", buf_ptr(builtin_zig_path), err_str(err));
    8359                 :          0 :             exit(1);
    8360                 :            :         }
    8361                 :            :     } else {
    8362                 :         13 :         contents = codegen_generate_builtin_source(g);
    8363         [ -  + ]:         13 :         if ((err = os_write_file(builtin_zig_path, contents))) {
    8364                 :          0 :             fprintf(stderr, "Unable to write file '%s': %s\n", buf_ptr(builtin_zig_path), err_str(err));
    8365                 :          0 :             exit(1);
    8366                 :            :         }
    8367                 :            :     }
    8368                 :            : 
    8369                 :         21 :     assert(g->root_package);
    8370                 :         21 :     assert(g->std_package);
    8371                 :         21 :     g->compile_var_package = new_package(buf_ptr(this_dir), builtin_zig_basename, "builtin");
    8372                 :         21 :     g->root_package->package_table.put(buf_create_from_str("builtin"), g->compile_var_package);
    8373                 :         21 :     g->std_package->package_table.put(buf_create_from_str("builtin"), g->compile_var_package);
    8374                 :         21 :     g->std_package->package_table.put(buf_create_from_str("std"), g->std_package);
    8375                 :            :     ZigPackage *root_pkg;
    8376         [ +  + ]:         21 :     if (g->is_test_build) {
    8377         [ +  - ]:          8 :         if (g->test_runner_package == nullptr) {
    8378                 :          8 :             g->test_runner_package = create_test_runner_pkg(g);
    8379                 :            :         }
    8380                 :          8 :         root_pkg = g->test_runner_package;
    8381                 :            :     } else {
    8382                 :         13 :         root_pkg = g->root_package;
    8383                 :            :     }
    8384                 :         21 :     g->std_package->package_table.put(buf_create_from_str("root"), root_pkg);
    8385                 :         21 :     g->compile_var_import = add_source_file(g, g->compile_var_package, builtin_zig_path, contents,
    8386                 :            :             SourceKindPkgMain);
    8387                 :            : 
    8388                 :         21 :     return ErrorNone;
    8389                 :            : }
    8390                 :            : 
    8391                 :         48 : static void init(CodeGen *g) {
    8392         [ +  + ]:         48 :     if (g->module)
    8393                 :         27 :         return;
    8394                 :            : 
    8395                 :         21 :     g->have_dynamic_link = detect_dynamic_link(g);
    8396                 :         21 :     g->have_pic = detect_pic(g);
    8397                 :         21 :     g->have_stack_probing = detect_stack_probing(g);
    8398                 :         21 :     g->is_single_threaded = detect_single_threaded(g);
    8399                 :         21 :     g->have_err_ret_tracing = detect_err_ret_tracing(g);
    8400                 :            : 
    8401         [ -  + ]:         21 :     if (target_is_single_threaded(g->zig_target)) {
    8402                 :          0 :         g->is_single_threaded = true;
    8403                 :            :     }
    8404                 :            : 
    8405                 :         21 :     assert(g->root_out_name);
    8406                 :         21 :     g->module = LLVMModuleCreateWithName(buf_ptr(g->root_out_name));
    8407                 :            : 
    8408                 :         21 :     LLVMSetTarget(g->module, buf_ptr(&g->llvm_triple_str));
    8409                 :            : 
    8410         [ +  + ]:         21 :     if (target_object_format(g->zig_target) == ZigLLVM_COFF) {
    8411                 :          4 :         ZigLLVMAddModuleCodeViewFlag(g->module);
    8412                 :            :     } else {
    8413                 :         17 :         ZigLLVMAddModuleDebugInfoFlag(g->module);
    8414                 :            :     }
    8415                 :            : 
    8416                 :            :     LLVMTargetRef target_ref;
    8417                 :         21 :     char *err_msg = nullptr;
    8418         [ -  + ]:         21 :     if (LLVMGetTargetFromTriple(buf_ptr(&g->llvm_triple_str), &target_ref, &err_msg)) {
    8419                 :          0 :         fprintf(stderr,
    8420                 :            :             "Zig is expecting LLVM to understand this target: '%s'\n"
    8421                 :            :             "However LLVM responded with: \"%s\"\n"
    8422                 :            :             "Zig is unable to continue. This is a bug in Zig:\n"
    8423                 :            :             "https://github.com/ziglang/zig/issues/438\n"
    8424                 :            :         , buf_ptr(&g->llvm_triple_str), err_msg);
    8425                 :          0 :         exit(1);
    8426                 :            :     }
    8427                 :            : 
    8428                 :         21 :     bool is_optimized = g->build_mode != BuildModeDebug;
    8429         [ -  + ]:         21 :     LLVMCodeGenOptLevel opt_level = is_optimized ? LLVMCodeGenLevelAggressive : LLVMCodeGenLevelNone;
    8430                 :            : 
    8431                 :            :     LLVMRelocMode reloc_mode;
    8432         [ +  + ]:         21 :     if (g->have_pic) {
    8433                 :         15 :         reloc_mode = LLVMRelocPIC;
    8434         [ -  + ]:          6 :     } else if (g->have_dynamic_link) {
    8435                 :          0 :         reloc_mode = LLVMRelocDynamicNoPic;
    8436                 :            :     } else {
    8437                 :          6 :         reloc_mode = LLVMRelocStatic;
    8438                 :            :     }
    8439                 :            : 
    8440                 :            :     const char *target_specific_cpu_args;
    8441                 :            :     const char *target_specific_features;
    8442         [ +  + ]:         21 :     if (g->zig_target->is_native) {
    8443                 :            :         // LLVM creates invalid binaries on Windows sometimes.
    8444                 :            :         // See https://github.com/ziglang/zig/issues/508
    8445                 :            :         // As a workaround we do not use target native features on Windows.
    8446 [ +  - ][ -  + ]:         14 :         if (g->zig_target->os == OsWindows || g->zig_target->os == OsUefi) {
    8447                 :          0 :             target_specific_cpu_args = "";
    8448                 :          0 :             target_specific_features = "";
    8449                 :            :         } else {
    8450                 :         14 :             target_specific_cpu_args = ZigLLVMGetHostCPUName();
    8451                 :         14 :             target_specific_features = ZigLLVMGetNativeFeatures();
    8452                 :            :         }
    8453                 :            :     } else {
    8454                 :          7 :         target_specific_cpu_args = "";
    8455                 :          7 :         target_specific_features = "";
    8456                 :            :     }
    8457                 :            : 
    8458                 :         21 :     g->target_machine = ZigLLVMCreateTargetMachine(target_ref, buf_ptr(&g->llvm_triple_str),
    8459                 :            :             target_specific_cpu_args, target_specific_features, opt_level, reloc_mode,
    8460                 :         21 :             LLVMCodeModelDefault, g->function_sections);
    8461                 :            : 
    8462                 :         21 :     g->target_data_ref = LLVMCreateTargetDataLayout(g->target_machine);
    8463                 :            : 
    8464                 :         21 :     char *layout_str = LLVMCopyStringRepOfTargetData(g->target_data_ref);
    8465                 :         21 :     LLVMSetDataLayout(g->module, layout_str);
    8466                 :            : 
    8467                 :            : 
    8468                 :         21 :     assert(g->pointer_size_bytes == LLVMPointerSize(g->target_data_ref));
    8469                 :         21 :     g->is_big_endian = (LLVMByteOrder(g->target_data_ref) == LLVMBigEndian);
    8470                 :            : 
    8471                 :         21 :     g->builder = LLVMCreateBuilder();
    8472                 :         21 :     g->dbuilder = ZigLLVMCreateDIBuilder(g->module, true);
    8473                 :            : 
    8474                 :            :     // Don't use ZIG_VERSION_STRING here, llvm misparses it when it includes
    8475                 :            :     // the git revision.
    8476                 :         21 :     Buf *producer = buf_sprintf("zig %d.%d.%d", ZIG_VERSION_MAJOR, ZIG_VERSION_MINOR, ZIG_VERSION_PATCH);
    8477                 :         21 :     const char *flags = "";
    8478                 :         21 :     unsigned runtime_version = 0;
    8479                 :            : 
    8480                 :            :     // For macOS stack traces, we want to avoid having to parse the compilation unit debug
    8481                 :            :     // info. As long as each debug info file has a path independent of the compilation unit
    8482                 :            :     // directory (DW_AT_comp_dir), then we never have to look at the compilation unit debug
    8483                 :            :     // info. If we provide an absolute path to LLVM here for the compilation unit debug info,
    8484                 :            :     // LLVM will emit DWARF info that depends on DW_AT_comp_dir. To avoid this, we pass "."
    8485                 :            :     // for the compilation unit directory. This forces each debug file to have a directory
    8486                 :            :     // rather than be relative to DW_AT_comp_dir. According to DWARF 5, debug files will
    8487                 :            :     // no longer reference DW_AT_comp_dir, for the purpose of being able to support the
    8488                 :            :     // common practice of stripping all but the line number sections from an executable.
    8489         [ +  + ]:         21 :     const char *compile_unit_dir = target_os_is_darwin(g->zig_target->os) ? "." :
    8490                 :         39 :         buf_ptr(&g->root_package->root_src_dir);
    8491                 :            : 
    8492                 :         21 :     ZigLLVMDIFile *compile_unit_file = ZigLLVMCreateFile(g->dbuilder, buf_ptr(g->root_out_name),
    8493                 :         21 :             compile_unit_dir);
    8494                 :         21 :     g->compile_unit = ZigLLVMCreateCompileUnit(g->dbuilder, ZigLLVMLang_DW_LANG_C99(),
    8495                 :         21 :             compile_unit_file, buf_ptr(producer), is_optimized, flags, runtime_version,
    8496                 :         21 :             "", 0, !g->strip_debug_symbols);
    8497                 :            : 
    8498                 :            :     // This is for debug stuff that doesn't have a real file.
    8499                 :         21 :     g->dummy_di_file = nullptr;
    8500                 :            : 
    8501                 :         21 :     define_builtin_types(g);
    8502                 :            : 
    8503                 :         21 :     IrInstruction *sentinel_instructions = allocate<IrInstruction>(2);
    8504                 :         21 :     g->invalid_instruction = &sentinel_instructions[0];
    8505                 :         21 :     g->invalid_instruction->value.type = g->builtin_types.entry_invalid;
    8506                 :         21 :     g->invalid_instruction->value.global_refs = allocate<ConstGlobalRefs>(1);
    8507                 :            : 
    8508                 :         21 :     g->unreach_instruction = &sentinel_instructions[1];
    8509                 :         21 :     g->unreach_instruction->value.type = g->builtin_types.entry_unreachable;
    8510                 :         21 :     g->unreach_instruction->value.global_refs = allocate<ConstGlobalRefs>(1);
    8511                 :            : 
    8512                 :         21 :     g->const_void_val.special = ConstValSpecialStatic;
    8513                 :         21 :     g->const_void_val.type = g->builtin_types.entry_void;
    8514                 :         21 :     g->const_void_val.global_refs = allocate<ConstGlobalRefs>(1);
    8515                 :            : 
    8516                 :            :     {
    8517                 :         21 :         ConstGlobalRefs *global_refs = allocate<ConstGlobalRefs>(PanicMsgIdCount);
    8518         [ +  + ]:        525 :         for (size_t i = 0; i < PanicMsgIdCount; i += 1) {
    8519                 :        504 :             g->panic_msg_vals[i].global_refs = &global_refs[i];
    8520                 :            :         }
    8521                 :            :     }
    8522                 :            : 
    8523                 :         21 :     define_builtin_fns(g);
    8524                 :            :     Error err;
    8525         [ -  + ]:         21 :     if ((err = define_builtin_compile_vars(g))) {
    8526                 :          0 :         fprintf(stderr, "Unable to create builtin.zig: %s\n", err_str(err));
    8527                 :         21 :         exit(1);
    8528                 :            :     }
    8529                 :            : }
    8530                 :            : 
    8531                 :         81 : static void detect_dynamic_linker(CodeGen *g) {
    8532         [ +  + ]:         81 :     if (g->dynamic_linker_path != nullptr)
    8533                 :         51 :         return;
    8534         [ +  + ]:         30 :     if (!g->have_dynamic_link)
    8535                 :         12 :         return;
    8536 [ +  - ][ +  + ]:         18 :     if (g->out_type == OutTypeObj || (g->out_type == OutTypeLib && !g->is_dynamic))
                 [ +  - ]
    8537                 :          6 :         return;
    8538                 :            : 
    8539                 :         12 :     const char *standard_ld_path = target_dynamic_linker(g->zig_target);
    8540         [ +  + ]:         12 :     if (standard_ld_path == nullptr)
    8541                 :          8 :         return;
    8542                 :            : 
    8543         [ +  - ]:          4 :     if (g->zig_target->is_native) {
    8544                 :            :         // target_dynamic_linker is usually correct. However on some systems, such as NixOS
    8545                 :            :         // it will be incorrect. See if we can do better by looking at what zig's own
    8546                 :            :         // dynamic linker path is.
    8547                 :          4 :         g->dynamic_linker_path = get_self_dynamic_linker_path();
    8548         [ +  - ]:          4 :         if (g->dynamic_linker_path != nullptr)
    8549                 :          4 :             return;
    8550                 :            : 
    8551                 :            :         // If Zig is statically linked, such as via distributed binary static builds, the above
    8552                 :            :         // trick won't work. What are we left with? Try to run the system C compiler and get
    8553                 :            :         // it to tell us the dynamic linker path
    8554                 :            : #if defined(ZIG_OS_LINUX)
    8555                 :            :         {
    8556                 :            :             Error err;
    8557                 :          0 :             Buf *result = buf_alloc();
    8558         [ #  # ]:          0 :             for (size_t i = 0; possible_ld_names[i] != NULL; i += 1) {
    8559                 :          0 :                 const char *lib_name = possible_ld_names[i];
    8560         [ #  # ]:          0 :                 if ((err = zig_libc_cc_print_file_name(lib_name, result, false, true))) {
    8561 [ #  # ][ #  # ]:          0 :                     if (err != ErrorCCompilerCannotFindFile && err != ErrorNoCCompilerInstalled) {
    8562                 :          0 :                         fprintf(stderr, "Unable to detect native dynamic linker: %s\n", err_str(err));
    8563                 :          0 :                         exit(1);
    8564                 :            :                     }
    8565                 :          0 :                     continue;
    8566                 :            :                 }
    8567                 :          0 :                 g->dynamic_linker_path = result;
    8568                 :          0 :                 return;
    8569                 :            :             }
    8570                 :            :         }
    8571                 :            : #endif
    8572                 :            :     }
    8573                 :            : 
    8574                 :          0 :     g->dynamic_linker_path = buf_create_from_str(standard_ld_path);
    8575                 :            : }
    8576                 :            : 
    8577                 :         81 : static void detect_libc(CodeGen *g) {
    8578                 :            :     Error err;
    8579                 :            : 
    8580 [ +  - ][ +  + ]:         81 :     if (g->libc != nullptr || g->libc_link_lib == nullptr)
    8581                 :         67 :         return;
    8582                 :            : 
    8583         [ +  + ]:         14 :     if (target_can_build_libc(g->zig_target)) {
    8584                 :          8 :         const char *generic_name = target_libc_generic_name(g->zig_target);
    8585                 :          8 :         const char *arch_name = target_arch_name(g->zig_target->arch);
    8586                 :          8 :         const char *abi_name = target_abi_name(g->zig_target->abi);
    8587         [ -  + ]:          8 :         if (target_is_musl(g->zig_target)) {
    8588                 :            :             // musl has some overrides. its headers are ABI-agnostic and so they all have the "musl" ABI name.
    8589                 :          0 :             abi_name = "musl";
    8590                 :            :             // some architectures are handled by the same set of headers
    8591                 :          0 :             arch_name = target_arch_musl_name(g->zig_target->arch);
    8592                 :            :         }
    8593                 :          8 :         Buf *arch_include_dir = buf_sprintf("%s" OS_SEP "libc" OS_SEP "include" OS_SEP "%s-%s-%s",
    8594                 :          8 :                 buf_ptr(g->zig_lib_dir), arch_name, target_os_name(g->zig_target->os), abi_name);
    8595                 :          8 :         Buf *generic_include_dir = buf_sprintf("%s" OS_SEP "libc" OS_SEP "include" OS_SEP "generic-%s",
    8596                 :          8 :                 buf_ptr(g->zig_lib_dir), generic_name);
    8597                 :          8 :         Buf *arch_os_include_dir = buf_sprintf("%s" OS_SEP "libc" OS_SEP "include" OS_SEP "%s-%s-any",
    8598                 :          8 :                 buf_ptr(g->zig_lib_dir), target_arch_name(g->zig_target->arch), target_os_name(g->zig_target->os));
    8599                 :          8 :         Buf *generic_os_include_dir = buf_sprintf("%s" OS_SEP "libc" OS_SEP "include" OS_SEP "any-%s-any",
    8600                 :          8 :                 buf_ptr(g->zig_lib_dir), target_os_name(g->zig_target->os));
    8601                 :            : 
    8602                 :          8 :         g->libc_include_dir_len = 4;
    8603                 :          8 :         g->libc_include_dir_list = allocate<Buf*>(g->libc_include_dir_len);
    8604                 :          8 :         g->libc_include_dir_list[0] = arch_include_dir;
    8605                 :          8 :         g->libc_include_dir_list[1] = generic_include_dir;
    8606                 :          8 :         g->libc_include_dir_list[2] = arch_os_include_dir;
    8607                 :          8 :         g->libc_include_dir_list[3] = generic_os_include_dir;
    8608                 :          8 :         return;
    8609                 :            :     }
    8610                 :            : 
    8611         [ -  + ]:          6 :     if (g->zig_target->is_native) {
    8612                 :          0 :         g->libc = allocate<ZigLibCInstallation>(1);
    8613                 :            : 
    8614                 :            :         // Look for zig-cache/native_libc.txt
    8615                 :          0 :         Buf *native_libc_txt = buf_alloc();
    8616                 :          0 :         os_path_join(g->cache_dir, buf_create_from_str("native_libc.txt"), native_libc_txt);
    8617         [ #  # ]:          0 :         if ((err = zig_libc_parse(g->libc, native_libc_txt, g->zig_target, false))) {
    8618         [ #  # ]:          0 :             if ((err = zig_libc_find_native(g->libc, true))) {
    8619                 :          0 :                 fprintf(stderr,
    8620                 :            :                     "Unable to link against libc: Unable to find libc installation: %s\n"
    8621                 :            :                     "See `zig libc --help` for more details.\n", err_str(err));
    8622                 :          0 :                 exit(1);
    8623                 :            :             }
    8624         [ #  # ]:          0 :             if ((err = os_make_path(g->cache_dir))) {
    8625                 :          0 :                 fprintf(stderr, "Unable to create %s directory: %s\n",
    8626                 :            :                     buf_ptr(g->cache_dir), err_str(err));
    8627                 :          0 :                 exit(1);
    8628                 :            :             }
    8629                 :          0 :             Buf *native_libc_tmp = buf_sprintf("%s.tmp", buf_ptr(native_libc_txt));
    8630                 :          0 :             FILE *file = fopen(buf_ptr(native_libc_tmp), "wb");
    8631         [ #  # ]:          0 :             if (file == nullptr) {
    8632                 :          0 :                 fprintf(stderr, "Unable to open %s: %s\n", buf_ptr(native_libc_tmp), strerror(errno));
    8633                 :          0 :                 exit(1);
    8634                 :            :             }
    8635                 :          0 :             zig_libc_render(g->libc, file);
    8636         [ #  # ]:          0 :             if (fclose(file) != 0) {
    8637                 :          0 :                 fprintf(stderr, "Unable to save %s: %s\n", buf_ptr(native_libc_tmp), strerror(errno));
    8638                 :          0 :                 exit(1);
    8639                 :            :             }
    8640         [ #  # ]:          0 :             if ((err = os_rename(native_libc_tmp, native_libc_txt))) {
    8641                 :          0 :                 fprintf(stderr, "Unable to create %s: %s\n", buf_ptr(native_libc_txt), err_str(err));
    8642                 :          0 :                 exit(1);
    8643                 :            :             }
    8644                 :            :         }
    8645                 :          0 :         bool want_sys_dir = !buf_eql_buf(&g->libc->include_dir, &g->libc->sys_include_dir);
    8646                 :          0 :         size_t dir_count = 1 + want_sys_dir;
    8647                 :          0 :         g->libc_include_dir_len = dir_count;
    8648                 :          0 :         g->libc_include_dir_list = allocate<Buf*>(dir_count);
    8649                 :          0 :         g->libc_include_dir_list[0] = &g->libc->include_dir;
    8650         [ #  # ]:          0 :         if (want_sys_dir) {
    8651                 :          0 :             g->libc_include_dir_list[1] = &g->libc->sys_include_dir;
    8652                 :            :         }
    8653 [ +  + ][ +  - ]:         10 :     } else if ((g->out_type == OutTypeExe || (g->out_type == OutTypeLib && g->is_dynamic)) &&
           [ -  +  -  + ]
                 [ -  + ]
    8654                 :          4 :         !target_os_is_darwin(g->zig_target->os))
    8655                 :            :     {
    8656                 :          0 :         Buf triple_buf = BUF_INIT;
    8657                 :          0 :         target_triple_zig(&triple_buf, g->zig_target);
    8658                 :          0 :         fprintf(stderr,
    8659                 :            :             "Zig is unable to provide a libc for the chosen target '%s'.\n"
    8660                 :            :             "The target is non-native, so Zig also cannot use the native libc installation.\n"
    8661                 :            :             "Choose a target which has a libc available (see `zig targets`), or\n"
    8662                 :            :             "provide a libc installation text file (see `zig libc --help`).\n", buf_ptr(&triple_buf));
    8663                 :          0 :         exit(1);
    8664                 :            :     }
    8665                 :            : }
    8666                 :            : 
    8667                 :            : // does not add the "cc" arg
    8668                 :         35 : void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_path, bool translate_c) {
    8669         [ -  + ]:         35 :     if (translate_c) {
    8670                 :          0 :         args.append("-x");
    8671                 :          0 :         args.append("c");
    8672                 :            :     }
    8673                 :            : 
    8674         [ +  - ]:         35 :     if (out_dep_path != nullptr) {
    8675                 :         35 :         args.append("-MD");
    8676                 :         35 :         args.append("-MV");
    8677                 :         35 :         args.append("-MF");
    8678                 :         35 :         args.append(out_dep_path);
    8679                 :            :     }
    8680                 :            : 
    8681                 :         35 :     args.append("-nostdinc");
    8682                 :         35 :     args.append("-fno-spell-checking");
    8683                 :            : 
    8684         [ -  + ]:         35 :     if (g->function_sections) {
    8685                 :          0 :         args.append("-ffunction-sections");
    8686                 :            :     }
    8687                 :            : 
    8688         [ -  + ]:         35 :     if (translate_c) {
    8689                 :            :         // this gives us access to preprocessing entities, presumably at
    8690                 :            :         // the cost of performance
    8691                 :          0 :         args.append("-Xclang");
    8692                 :          0 :         args.append("-detailed-preprocessing-record");
    8693                 :            :     } else {
    8694   [ +  -  -  - ]:         35 :         switch (g->err_color) {
    8695                 :         35 :             case ErrColorAuto:
    8696                 :         35 :                 break;
    8697                 :          0 :             case ErrColorOff:
    8698                 :          0 :                 args.append("-fno-color-diagnostics");
    8699                 :          0 :                 args.append("-fno-caret-diagnostics");
    8700                 :          0 :                 break;
    8701                 :          0 :             case ErrColorOn:
    8702                 :          0 :                 args.append("-fcolor-diagnostics");
    8703                 :          0 :                 args.append("-fcaret-diagnostics");
    8704                 :          0 :                 break;
    8705                 :            :         }
    8706                 :            :     }
    8707                 :            : 
    8708                 :            :     //note(dimenus): appending libc headers before c_headers breaks intrinsics 
    8709                 :            :     //and other compiler specific items
    8710                 :            :     // According to Rich Felker libc headers are supposed to go before C language headers.
    8711                 :         35 :     args.append("-isystem");
    8712                 :         35 :     args.append(buf_ptr(g->zig_c_headers_dir));
    8713                 :            : 
    8714         [ +  + ]:         99 :     for (size_t i = 0; i < g->libc_include_dir_len; i += 1) {
    8715                 :         64 :         Buf *include_dir = g->libc_include_dir_list[i];
    8716                 :         64 :         args.append("-isystem");
    8717                 :         64 :         args.append(buf_ptr(include_dir));
    8718                 :            :     }
    8719                 :            : 
    8720                 :            : 
    8721         [ +  - ]:         35 :     if (g->zig_target->is_native) {
    8722                 :         35 :         args.append("-march=native");
    8723                 :            :     } else {
    8724                 :          0 :         args.append("-target");
    8725                 :          0 :         args.append(buf_ptr(&g->llvm_triple_str));
    8726                 :            :     }
    8727         [ -  + ]:         35 :     if (g->zig_target->os == OsFreestanding) {
    8728                 :          0 :         args.append("-ffreestanding");
    8729                 :            :     }
    8730                 :            : 
    8731                 :            :     // windows.h has files such as pshpack1.h which do #pragma packing, triggering a clang warning.
    8732                 :            :     // So for this target, we disable this warning.
    8733 [ -  + ][ #  # ]:         35 :     if (g->zig_target->os == OsWindows && target_abi_is_gnu(g->zig_target->abi)) {
                 [ -  + ]
    8734                 :          0 :         args.append("-Wno-pragma-pack");
    8735                 :            :     }
    8736                 :            : 
    8737         [ +  - ]:         35 :     if (!g->strip_debug_symbols) {
    8738                 :         35 :         args.append("-g");
    8739                 :            :     }
    8740                 :            : 
    8741         [ +  - ]:         35 :     if (codegen_have_frame_pointer(g)) {
    8742                 :         35 :         args.append("-fno-omit-frame-pointer");
    8743                 :            :     } else {
    8744                 :          0 :         args.append("-fomit-frame-pointer");
    8745                 :            :     }
    8746                 :            : 
    8747   [ +  -  -  -  :         35 :     switch (g->build_mode) {
                      - ]
    8748                 :         35 :         case BuildModeDebug:
    8749                 :            :             // windows c runtime requires -D_DEBUG if using debug libraries
    8750                 :         35 :             args.append("-D_DEBUG");
    8751                 :            : 
    8752         [ +  + ]:         35 :             if (g->libc_link_lib != nullptr) {
    8753                 :         16 :                 args.append("-fstack-protector-strong");
    8754                 :         16 :                 args.append("--param");
    8755                 :         16 :                 args.append("ssp-buffer-size=4");
    8756                 :            :             } else {
    8757                 :         19 :                 args.append("-fno-stack-protector");
    8758                 :            :             }
    8759                 :         35 :             break;
    8760                 :          0 :         case BuildModeSafeRelease:
    8761                 :            :             // See the comment in the BuildModeFastRelease case for why we pass -O2 rather
    8762                 :            :             // than -O3 here.
    8763                 :          0 :             args.append("-O2");
    8764         [ #  # ]:          0 :             if (g->libc_link_lib != nullptr) {
    8765                 :          0 :                 args.append("-D_FORTIFY_SOURCE=2");
    8766                 :          0 :                 args.append("-fstack-protector-strong");
    8767                 :          0 :                 args.append("--param");
    8768                 :          0 :                 args.append("ssp-buffer-size=4");
    8769                 :            :             } else {
    8770                 :          0 :                 args.append("-fno-stack-protector");
    8771                 :            :             }
    8772                 :          0 :             break;
    8773                 :          0 :         case BuildModeFastRelease:
    8774                 :          0 :             args.append("-DNDEBUG");
    8775                 :            :             // Here we pass -O2 rather than -O3 because, although we do the equivalent of
    8776                 :            :             // -O3 in Zig code, the justification for the difference here is that Zig
    8777                 :            :             // has better detection and prevention of undefined behavior, so -O3 is safer for
    8778                 :            :             // Zig code than it is for C code. Also, C programmers are used to their code
    8779                 :            :             // running in -O2 and thus the -O3 path has been tested less.
    8780                 :          0 :             args.append("-O2");
    8781                 :          0 :             args.append("-fno-stack-protector");
    8782                 :          0 :             break;
    8783                 :          0 :         case BuildModeSmallRelease:
    8784                 :          0 :             args.append("-DNDEBUG");
    8785                 :          0 :             args.append("-Os");
    8786                 :          0 :             args.append("-fno-stack-protector");
    8787                 :          0 :             break;
    8788                 :            :     }
    8789                 :            : 
    8790 [ +  - ][ +  - ]:         35 :     if (target_supports_fpic(g->zig_target) && g->have_pic) {
                 [ +  - ]
    8791                 :         35 :         args.append("-fPIC");
    8792                 :            :     }
    8793                 :            : 
    8794         [ -  + ]:         35 :     for (size_t arg_i = 0; arg_i < g->clang_argv_len; arg_i += 1) {
    8795                 :          0 :         args.append(g->clang_argv[arg_i]);
    8796                 :            :     }
    8797                 :         35 : }
    8798                 :            : 
    8799                 :          0 : void codegen_translate_c(CodeGen *g, Buf *full_path, FILE *out_file, bool use_userland_implementation) {
    8800                 :            :     Error err;
    8801                 :          0 :     Buf *src_basename = buf_alloc();
    8802                 :          0 :     Buf *src_dirname = buf_alloc();
    8803                 :          0 :     os_path_split(full_path, src_dirname, src_basename);
    8804                 :            : 
    8805                 :          0 :     Buf noextname = BUF_INIT;
    8806                 :          0 :     os_path_extname(src_basename, &noextname, nullptr);
    8807                 :            : 
    8808                 :          0 :     detect_libc(g);
    8809                 :            : 
    8810                 :          0 :     init(g);
    8811                 :            : 
    8812         [ #  # ]:          0 :     Stage2TranslateMode trans_mode = buf_ends_with_str(full_path, ".h") ?
    8813                 :          0 :         Stage2TranslateModeImport : Stage2TranslateModeTranslate;
    8814                 :            : 
    8815                 :            : 
    8816                 :          0 :     ZigList<const char *> clang_argv = {0};
    8817                 :          0 :     add_cc_args(g, clang_argv, nullptr, true);
    8818                 :            : 
    8819                 :          0 :     clang_argv.append(buf_ptr(full_path));
    8820                 :            : 
    8821         [ #  # ]:          0 :     if (g->verbose_cc) {
    8822                 :          0 :         fprintf(stderr, "clang");
    8823         [ #  # ]:          0 :         for (size_t i = 0; i < clang_argv.length; i += 1) {
    8824                 :          0 :             fprintf(stderr, " %s", clang_argv.at(i));
    8825                 :            :         }
    8826                 :          0 :         fprintf(stderr, "\n");
    8827                 :            :     }
    8828                 :            : 
    8829                 :          0 :     clang_argv.append(nullptr); // to make the [start...end] argument work
    8830                 :            : 
    8831                 :          0 :     const char *resources_path = buf_ptr(g->zig_c_headers_dir);
    8832                 :            :     Stage2ErrorMsg *errors_ptr;
    8833                 :            :     size_t errors_len;
    8834                 :            :     Stage2Ast *ast;
    8835                 :            :     AstNode *root_node;
    8836                 :            : 
    8837         [ #  # ]:          0 :     if (use_userland_implementation) {
    8838                 :          0 :         err = stage2_translate_c(&ast, &errors_ptr, &errors_len,
    8839                 :          0 :                         &clang_argv.at(0), &clang_argv.last(), trans_mode, resources_path);
    8840                 :            :     } else {
    8841                 :          0 :         err = parse_h_file(g, &root_node, &errors_ptr, &errors_len, &clang_argv.at(0), &clang_argv.last(),
    8842                 :            :                 trans_mode, resources_path);
    8843                 :            :     }
    8844                 :            : 
    8845 [ #  # ][ #  # ]:          0 :     if (err == ErrorCCompileErrors && errors_len > 0) {
    8846         [ #  # ]:          0 :         for (size_t i = 0; i < errors_len; i += 1) {
    8847                 :          0 :             Stage2ErrorMsg *clang_err = &errors_ptr[i];
    8848         [ #  # ]:          0 :             ErrorMsg *err_msg = err_msg_create_with_offset(
    8849                 :          0 :                     clang_err->filename_ptr ?
    8850                 :          0 :                         buf_create_from_mem(clang_err->filename_ptr, clang_err->filename_len) : buf_alloc(),
    8851                 :          0 :                     clang_err->line, clang_err->column, clang_err->offset, clang_err->source,
    8852                 :          0 :                     buf_create_from_mem(clang_err->msg_ptr, clang_err->msg_len));
    8853                 :          0 :             print_err_msg(err_msg, g->err_color);
    8854                 :            :         }
    8855                 :          0 :         exit(1);
    8856                 :            :     }
    8857                 :            : 
    8858         [ #  # ]:          0 :     if (err) {
    8859                 :          0 :         fprintf(stderr, "unable to parse C file: %s\n", err_str(err));
    8860                 :          0 :         exit(1);
    8861                 :            :     }
    8862                 :            : 
    8863                 :            : 
    8864         [ #  # ]:          0 :     if (use_userland_implementation) {
    8865                 :          0 :         stage2_render_ast(ast, out_file);
    8866                 :            :     } else {
    8867                 :          0 :         ast_render(out_file, root_node, 4);
    8868                 :            :     }
    8869                 :          0 : }
    8870                 :            : 
    8871                 :         26 : static ZigType *add_special_code(CodeGen *g, ZigPackage *package, const char *basename) {
    8872                 :         26 :     Buf *code_basename = buf_create_from_str(basename);
    8873                 :         26 :     Buf path_to_code_src = BUF_INIT;
    8874                 :         26 :     os_path_join(g->zig_std_special_dir, code_basename, &path_to_code_src);
    8875                 :            : 
    8876                 :         26 :     Buf *resolve_paths[] = {&path_to_code_src};
    8877                 :         26 :     Buf *resolved_path = buf_alloc();
    8878                 :         26 :     *resolved_path = os_path_resolve(resolve_paths, 1);
    8879                 :         26 :     Buf *import_code = buf_alloc();
    8880                 :            :     Error err;
    8881         [ -  + ]:         26 :     if ((err = file_fetch(g, resolved_path, import_code))) {
    8882                 :          0 :         zig_panic("unable to open '%s': %s\n", buf_ptr(&path_to_code_src), err_str(err));
    8883                 :            :     }
    8884                 :            : 
    8885                 :         26 :     return add_source_file(g, package, resolved_path, import_code, SourceKindPkgMain);
    8886                 :            : }
    8887                 :            : 
    8888                 :          9 : static ZigPackage *create_start_pkg(CodeGen *g, ZigPackage *pkg_with_main) {
    8889                 :          9 :     ZigPackage *package = codegen_create_package(g, buf_ptr(g->zig_std_special_dir), "start.zig", "std.special");
    8890                 :          9 :     package->package_table.put(buf_create_from_str("root"), pkg_with_main);
    8891                 :          9 :     return package;
    8892                 :            : }
    8893                 :            : 
    8894                 :          8 : static void create_test_compile_var_and_add_test_runner(CodeGen *g) {
    8895                 :            :     Error err;
    8896                 :            : 
    8897                 :          8 :     assert(g->is_test_build);
    8898                 :            : 
    8899         [ -  + ]:          8 :     if (g->test_fns.length == 0) {
    8900                 :          0 :         fprintf(stderr, "No tests to run.\n");
    8901                 :          0 :         exit(0);
    8902                 :            :     }
    8903                 :            : 
    8904                 :          8 :     ZigType *fn_type = get_test_fn_type(g);
    8905                 :            : 
    8906                 :          8 :     ConstExprValue *test_fn_type_val = get_builtin_value(g, "TestFn");
    8907                 :          8 :     assert(test_fn_type_val->type->id == ZigTypeIdMetaType);
    8908                 :          8 :     ZigType *struct_type = test_fn_type_val->data.x_type;
    8909         [ -  + ]:          8 :     if ((err = type_resolve(g, struct_type, ResolveStatusSizeKnown)))
    8910                 :          0 :         zig_unreachable();
    8911                 :            : 
    8912                 :          8 :     ConstExprValue *test_fn_array = create_const_vals(1);
    8913                 :          8 :     test_fn_array->type = get_array_type(g, struct_type, g->test_fns.length);
    8914                 :          8 :     test_fn_array->special = ConstValSpecialStatic;
    8915                 :          8 :     test_fn_array->data.x_array.data.s_none.elements = create_const_vals(g->test_fns.length);
    8916                 :            : 
    8917         [ +  + ]:       5888 :     for (size_t i = 0; i < g->test_fns.length; i += 1) {
    8918                 :       5880 :         ZigFn *test_fn_entry = g->test_fns.at(i);
    8919                 :            : 
    8920         [ -  + ]:       5880 :         if (fn_is_async(test_fn_entry)) {
    8921                 :          0 :             ErrorMsg *msg = add_node_error(g, test_fn_entry->proto_node,
    8922                 :          0 :                 buf_create_from_str("test functions cannot be async"));
    8923                 :          0 :             add_error_note(g, msg, test_fn_entry->proto_node,
    8924                 :            :                 buf_sprintf("this restriction may be lifted in the future. See https://github.com/ziglang/zig/issues/3117 for more details"));
    8925                 :          0 :             add_async_error_notes(g, msg, test_fn_entry);
    8926                 :          0 :             continue;
    8927                 :            :         }
    8928                 :            : 
    8929                 :       5880 :         ConstExprValue *this_val = &test_fn_array->data.x_array.data.s_none.elements[i];
    8930                 :       5880 :         this_val->special = ConstValSpecialStatic;
    8931                 :       5880 :         this_val->type = struct_type;
    8932                 :       5880 :         this_val->parent.id = ConstParentIdArray;
    8933                 :       5880 :         this_val->parent.data.p_array.array_val = test_fn_array;
    8934                 :       5880 :         this_val->parent.data.p_array.elem_index = i;
    8935                 :       5880 :         this_val->data.x_struct.fields = create_const_vals(2);
    8936                 :            : 
    8937                 :       5880 :         ConstExprValue *name_field = &this_val->data.x_struct.fields[0];
    8938                 :       5880 :         ConstExprValue *name_array_val = create_const_str_lit(g, &test_fn_entry->symbol_name);
    8939                 :       5880 :         init_const_slice(g, name_field, name_array_val, 0, buf_len(&test_fn_entry->symbol_name), true);
    8940                 :            : 
    8941                 :       5880 :         ConstExprValue *fn_field = &this_val->data.x_struct.fields[1];
    8942                 :       5880 :         fn_field->type = fn_type;
    8943                 :       5880 :         fn_field->special = ConstValSpecialStatic;
    8944                 :       5880 :         fn_field->data.x_ptr.special = ConstPtrSpecialFunction;
    8945                 :       5880 :         fn_field->data.x_ptr.mut = ConstPtrMutComptimeConst;
    8946                 :       5880 :         fn_field->data.x_ptr.data.fn.fn_entry = test_fn_entry;
    8947                 :            :     }
    8948                 :          8 :     report_errors_and_maybe_exit(g);
    8949                 :            : 
    8950                 :          8 :     ConstExprValue *test_fn_slice = create_const_slice(g, test_fn_array, 0, g->test_fns.length, true);
    8951                 :            : 
    8952                 :          8 :     update_compile_var(g, buf_create_from_str("test_functions"), test_fn_slice);
    8953                 :          8 :     assert(g->test_runner_package != nullptr);
    8954                 :          8 :     g->test_runner_import = add_special_code(g, g->test_runner_package, "test_runner.zig");
    8955                 :          8 : }
    8956                 :            : 
    8957                 :         20 : static Buf *get_resolved_root_src_path(CodeGen *g) {
    8958                 :            :     // TODO memoize
    8959         [ -  + ]:         20 :     if (buf_len(&g->root_package->root_src_path) == 0)
    8960                 :          0 :         return nullptr;
    8961                 :            : 
    8962                 :         20 :     Buf rel_full_path = BUF_INIT;
    8963                 :         20 :     os_path_join(&g->root_package->root_src_dir, &g->root_package->root_src_path, &rel_full_path);
    8964                 :            : 
    8965                 :         20 :     Buf *resolved_path = buf_alloc();
    8966                 :         20 :     Buf *resolve_paths[] = {&rel_full_path};
    8967                 :         20 :     *resolved_path = os_path_resolve(resolve_paths, 1);
    8968                 :            : 
    8969                 :         20 :     return resolved_path;
    8970                 :            : }
    8971                 :            : 
    8972                 :         20 : static bool want_startup_code(CodeGen *g) {
    8973                 :            :     // Test builds get handled separately.
    8974         [ +  + ]:         20 :     if (g->is_test_build)
    8975                 :          8 :         return false;
    8976                 :            : 
    8977                 :            :     // start code does not handle UEFI target
    8978         [ -  + ]:         12 :     if (g->zig_target->os == OsUefi)
    8979                 :          0 :         return false;
    8980                 :            : 
    8981                 :            :     // WASM freestanding can still have an entry point but other freestanding targets do not.
    8982 [ -  + ][ #  # ]:         12 :     if (g->zig_target->os == OsFreestanding && !target_is_wasm(g->zig_target))
                 [ -  + ]
    8983                 :          0 :         return false;
    8984                 :            : 
    8985                 :            :     // Declaring certain export functions means skipping the start code
    8986 [ +  - ][ +  - ]:         12 :     if (g->have_c_main || g->have_winmain || g->have_winmain_crt_startup)
                 [ -  + ]
    8987                 :          0 :         return false;
    8988                 :            : 
    8989                 :            :     // If there is a pub main in the root source file, that means we need start code.
    8990         [ +  + ]:         12 :     if (g->have_pub_main)
    8991                 :          1 :         return true;
    8992                 :            : 
    8993         [ -  + ]:         11 :     if (g->out_type == OutTypeExe) {
    8994                 :            :         // For build-exe, we might add start code even though there is no pub main, so that the
    8995                 :            :         // programmer gets the "no pub main" compile error. However if linking libc and there is
    8996                 :            :         // a C source file, that might have main().
    8997 [ #  # ][ #  # ]:          0 :         return g->c_source_files.length == 0 || g->libc_link_lib == nullptr;
    8998                 :            :     }
    8999                 :            : 
    9000                 :            :     // For objects and libraries, and we don't have pub main, no start code.
    9001                 :         11 :     return false;
    9002                 :            : }
    9003                 :            : 
    9004                 :         20 : static void gen_root_source(CodeGen *g) {
    9005                 :         20 :     Buf *resolved_path = get_resolved_root_src_path(g);
    9006         [ -  + ]:         20 :     if (resolved_path == nullptr)
    9007                 :          0 :         return;
    9008                 :            : 
    9009                 :         20 :     Buf *source_code = buf_alloc();
    9010                 :            :     Error err;
    9011                 :            :     // No need for using the caching system for this file fetch because it is handled
    9012                 :            :     // separately.
    9013         [ -  + ]:         20 :     if ((err = os_fetch_file_path(resolved_path, source_code))) {
    9014                 :          0 :         fprintf(stderr, "unable to open '%s': %s\n", buf_ptr(resolved_path), err_str(err));
    9015                 :          0 :         exit(1);
    9016                 :            :     }
    9017                 :            : 
    9018                 :         20 :     ZigType *root_import_alias = add_source_file(g, g->root_package, resolved_path, source_code, SourceKindRoot);
    9019                 :         20 :     assert(root_import_alias == g->root_import);
    9020                 :            : 
    9021                 :         20 :     assert(g->root_out_name);
    9022                 :         20 :     assert(g->out_type != OutTypeUnknown);
    9023                 :            : 
    9024         [ +  + ]:         20 :     if (!g->is_dummy_so) {
    9025                 :            :         // Zig has lazy top level definitions. Here we semantically analyze the panic function.
    9026                 :            :         ZigType *import_with_panic;
    9027         [ +  + ]:         15 :         if (g->have_pub_panic) {
    9028                 :          6 :             import_with_panic = g->root_import;
    9029                 :            :         } else {
    9030                 :          9 :             g->panic_package = create_panic_pkg(g);
    9031                 :          9 :             import_with_panic = add_special_code(g, g->panic_package, "panic.zig");
    9032                 :            :         }
    9033                 :         15 :         Tld *panic_tld = find_decl(g, &get_container_scope(import_with_panic)->base, buf_create_from_str("panic"));
    9034                 :         15 :         assert(panic_tld != nullptr);
    9035                 :         15 :         resolve_top_level_decl(g, panic_tld, nullptr, false);
    9036                 :            :     }
    9037                 :            : 
    9038                 :            : 
    9039         [ +  - ]:         20 :     if (!g->error_during_imports) {
    9040                 :         20 :         semantic_analyze(g);
    9041                 :            :     }
    9042                 :         20 :     report_errors_and_maybe_exit(g);
    9043                 :            : 
    9044         [ +  + ]:         20 :     if (want_startup_code(g)) {
    9045                 :          1 :         g->start_import = add_special_code(g, create_start_pkg(g, g->root_package), "start.zig");
    9046                 :            :     }
    9047 [ +  + ][ +  - ]:         20 :     if (g->zig_target->os == OsWindows && !g->have_dllmain_crt_startup &&
                 [ +  + ]
    9048         [ -  + ]:          2 :             g->out_type == OutTypeLib && g->is_dynamic)
    9049                 :            :     {
    9050                 :          0 :         g->start_import = add_special_code(g, create_start_pkg(g, g->root_package), "start_lib.zig");
    9051                 :            :     }
    9052                 :            : 
    9053         [ +  - ]:         20 :     if (!g->error_during_imports) {
    9054                 :         20 :         semantic_analyze(g);
    9055                 :            :     }
    9056         [ +  + ]:         20 :     if (g->is_test_build) {
    9057                 :          8 :         create_test_compile_var_and_add_test_runner(g);
    9058                 :          8 :         g->start_import = add_special_code(g, create_start_pkg(g, g->test_runner_package), "start.zig");
    9059                 :            : 
    9060         [ +  - ]:          8 :         if (!g->error_during_imports) {
    9061                 :          8 :             semantic_analyze(g);
    9062                 :            :         }
    9063                 :            :     }
    9064                 :            : 
    9065         [ +  + ]:         20 :     if (!g->is_dummy_so) {
    9066                 :         15 :         typecheck_panic_fn(g, g->panic_tld_fn, g->panic_fn);
    9067                 :            :     }
    9068                 :            : 
    9069                 :         20 :     report_errors_and_maybe_exit(g);
    9070                 :            : 
    9071                 :            : }
    9072                 :            : 
    9073                 :          0 : static void print_zig_cc_cmd(ZigList<const char *> *args) {
    9074         [ #  # ]:          0 :     for (size_t arg_i = 0; arg_i < args->length; arg_i += 1) {
    9075         [ #  # ]:          0 :         const char *space_str = (arg_i == 0) ? "" : " ";
    9076                 :          0 :         fprintf(stderr, "%s%s", space_str, args->at(arg_i));
    9077                 :            :     }
    9078                 :          0 :     fprintf(stderr, "\n");
    9079                 :          0 : }
    9080                 :            : 
    9081                 :            : // Caller should delete the file when done or rename it into a better location.
    9082                 :         35 : static Error get_tmp_filename(CodeGen *g, Buf *out, Buf *suffix) {
    9083                 :            :     Error err;
    9084                 :         35 :     buf_resize(out, 0);
    9085                 :         35 :     os_path_join(g->cache_dir, buf_create_from_str("tmp" OS_SEP), out);
    9086         [ -  + ]:         35 :     if ((err = os_make_path(out))) {
    9087                 :          0 :         return err;
    9088                 :            :     }
    9089                 :         35 :     const char base64[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
    9090                 :         35 :     assert(array_length(base64) == 64 + 1);
    9091         [ +  + ]:        455 :     for (size_t i = 0; i < 12; i += 1) {
    9092                 :        420 :         buf_append_char(out, base64[rand() % 64]);
    9093                 :            :     }
    9094                 :         35 :     buf_append_char(out, '-');
    9095                 :         35 :     buf_append_buf(out, suffix);
    9096                 :         35 :     return ErrorNone;
    9097                 :            : }
    9098                 :            : 
    9099                 :         54 : Error create_c_object_cache(CodeGen *g, CacheHash **out_cache_hash, bool verbose) {
    9100                 :            :     Error err;
    9101                 :         54 :     CacheHash *cache_hash = allocate<CacheHash>(1);
    9102                 :         54 :     Buf *manifest_dir = buf_sprintf("%s" OS_SEP CACHE_HASH_SUBDIR, buf_ptr(g->cache_dir));
    9103                 :         54 :     cache_init(cache_hash, manifest_dir);
    9104                 :            : 
    9105                 :            :     Buf *compiler_id;
    9106         [ -  + ]:         54 :     if ((err = get_compiler_id(&compiler_id))) {
    9107         [ #  # ]:          0 :         if (verbose) {
    9108                 :          0 :             fprintf(stderr, "unable to get compiler id: %s\n", err_str(err));
    9109                 :            :         }
    9110                 :          0 :         return err;
    9111                 :            :     }
    9112                 :         54 :     cache_buf(cache_hash, compiler_id);
    9113                 :         54 :     cache_int(cache_hash, g->err_color);
    9114                 :         54 :     cache_buf(cache_hash, g->zig_c_headers_dir);
    9115                 :         54 :     cache_list_of_buf(cache_hash, g->libc_include_dir_list, g->libc_include_dir_len);
    9116                 :         54 :     cache_int(cache_hash, g->zig_target->is_native);
    9117                 :         54 :     cache_int(cache_hash, g->zig_target->arch);
    9118                 :         54 :     cache_int(cache_hash, g->zig_target->sub_arch);
    9119                 :         54 :     cache_int(cache_hash, g->zig_target->vendor);
    9120                 :         54 :     cache_int(cache_hash, g->zig_target->os);
    9121                 :         54 :     cache_int(cache_hash, g->zig_target->abi);
    9122                 :         54 :     cache_bool(cache_hash, g->strip_debug_symbols);
    9123                 :         54 :     cache_int(cache_hash, g->build_mode);
    9124                 :         54 :     cache_bool(cache_hash, g->have_pic);
    9125                 :         54 :     cache_bool(cache_hash, want_valgrind_support(g));
    9126                 :         54 :     cache_bool(cache_hash, g->function_sections);
    9127         [ -  + ]:         54 :     for (size_t arg_i = 0; arg_i < g->clang_argv_len; arg_i += 1) {
    9128                 :          0 :         cache_str(cache_hash, g->clang_argv[arg_i]);
    9129                 :            :     }
    9130                 :            : 
    9131                 :         54 :     *out_cache_hash = cache_hash;
    9132                 :         54 :     return ErrorNone;
    9133                 :            : }
    9134                 :            : 
    9135                 :            : // returns true if it was a cache miss
    9136                 :         54 : static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {
    9137                 :            :     Error err;
    9138                 :            : 
    9139                 :            :     Buf *artifact_dir;
    9140                 :            :     Buf *o_final_path;
    9141                 :            : 
    9142                 :         54 :     Buf *o_dir = buf_sprintf("%s" OS_SEP CACHE_OUT_SUBDIR, buf_ptr(g->cache_dir));
    9143                 :            : 
    9144                 :         54 :     Buf *c_source_file = buf_create_from_str(c_file->source_path);
    9145                 :         54 :     Buf *c_source_basename = buf_alloc();
    9146                 :         54 :     os_path_split(c_source_file, nullptr, c_source_basename);
    9147                 :         54 :     Buf *final_o_basename = buf_alloc();
    9148                 :         54 :     os_path_extname(c_source_basename, final_o_basename, nullptr);
    9149                 :         54 :     buf_append_str(final_o_basename, target_o_file_ext(g->zig_target));
    9150                 :            : 
    9151                 :            :     CacheHash *cache_hash;
    9152         [ -  + ]:         54 :     if ((err = create_c_object_cache(g, &cache_hash, true))) {
    9153                 :            :         // Already printed error; verbose = true
    9154                 :          0 :         exit(1);
    9155                 :            :     }
    9156                 :         54 :     cache_file(cache_hash, c_source_file);
    9157                 :            : 
    9158                 :            :     // Note: not directory args, just args that always have a file next
    9159                 :            :     static const char *file_args[] = {
    9160                 :            :         "-include",
    9161                 :            :     };
    9162         [ +  + ]:       2348 :     for (size_t arg_i = 0; arg_i < c_file->args.length; arg_i += 1) {
    9163                 :       2294 :         const char *arg = c_file->args.at(arg_i);
    9164                 :       2294 :         cache_str(cache_hash, arg);
    9165         [ +  + ]:       4588 :         for (size_t file_arg_i = 0; file_arg_i < array_length(file_args); file_arg_i += 1) {
    9166 [ +  + ][ +  - ]:       2294 :             if (strcmp(arg, file_args[file_arg_i]) == 0 && arg_i + 1 < c_file->args.length) {
    9167                 :         68 :                 arg_i += 1;
    9168                 :         68 :                 cache_file(cache_hash, buf_create_from_str(c_file->args.at(arg_i)));
    9169                 :            :             }
    9170                 :            :         }
    9171                 :            :     }
    9172                 :            : 
    9173                 :         54 :     Buf digest = BUF_INIT;
    9174                 :         54 :     buf_resize(&digest, 0);
    9175         [ -  + ]:         54 :     if ((err = cache_hit(cache_hash, &digest))) {
    9176         [ #  # ]:          0 :         if (err != ErrorInvalidFormat) {
    9177         [ #  # ]:          0 :             if (err == ErrorCacheUnavailable) {
    9178                 :            :                 // already printed error
    9179                 :            :             } else {
    9180                 :          0 :                 fprintf(stderr, "unable to check cache when compiling C object: %s\n", err_str(err));
    9181                 :            :             }
    9182                 :          0 :             exit(1);
    9183                 :            :         }
    9184                 :            :     }
    9185                 :         54 :     bool is_cache_miss = (buf_len(&digest) == 0);
    9186         [ +  + ]:         54 :     if (is_cache_miss) {
    9187                 :            :         // we can't know the digest until we do the C compiler invocation, so we
    9188                 :            :         // need a tmp filename.
    9189                 :         35 :         Buf *out_obj_path = buf_alloc();
    9190         [ -  + ]:         35 :         if ((err = get_tmp_filename(g, out_obj_path, final_o_basename))) {
    9191                 :          0 :             fprintf(stderr, "unable to create tmp dir: %s\n", err_str(err));
    9192                 :          0 :             exit(1);
    9193                 :            :         }
    9194                 :            : 
    9195                 :            :         Termination term;
    9196                 :         35 :         ZigList<const char *> args = {};
    9197                 :         35 :         args.append(buf_ptr(self_exe_path));
    9198                 :         35 :         args.append("cc");
    9199                 :            : 
    9200                 :         35 :         Buf *out_dep_path = buf_sprintf("%s.d", buf_ptr(out_obj_path));
    9201                 :         35 :         add_cc_args(g, args, buf_ptr(out_dep_path), false);
    9202                 :            : 
    9203                 :         35 :         args.append("-o");
    9204                 :         35 :         args.append(buf_ptr(out_obj_path));
    9205                 :            : 
    9206                 :         35 :         args.append("-c");
    9207                 :         35 :         args.append(buf_ptr(c_source_file));
    9208                 :            : 
    9209         [ +  + ]:       1288 :         for (size_t arg_i = 0; arg_i < c_file->args.length; arg_i += 1) {
    9210                 :       1253 :             args.append(c_file->args.at(arg_i));
    9211                 :            :         }
    9212                 :            : 
    9213         [ -  + ]:         35 :         if (g->verbose_cc) {
    9214                 :          0 :             print_zig_cc_cmd(&args);
    9215                 :            :         }
    9216                 :         35 :         os_spawn_process(args, &term);
    9217 [ -  + ][ +  - ]:         35 :         if (term.how != TerminationIdClean || term.code != 0) {
    9218                 :          0 :             fprintf(stderr, "\nThe following command failed:\n");
    9219                 :          0 :             print_zig_cc_cmd(&args);
    9220                 :          0 :             exit(1);
    9221                 :            :         }
    9222                 :            : 
    9223                 :            :         // add the files depended on to the cache system
    9224         [ -  + ]:         35 :         if ((err = cache_add_dep_file(cache_hash, out_dep_path, true))) {
    9225                 :            :             // Don't treat the absence of the .d file as a fatal error, the
    9226                 :            :             // compiler may not produce one eg. when compiling .s files
    9227         [ #  # ]:          0 :             if (err != ErrorFileNotFound) {
    9228                 :          0 :                 fprintf(stderr, "Failed to add C source dependencies to cache: %s\n", err_str(err));
    9229                 :          0 :                 exit(1);
    9230                 :            :             }
    9231                 :            :         }
    9232         [ +  - ]:         35 :         if (err != ErrorFileNotFound) {
    9233                 :         35 :             os_delete_file(out_dep_path);
    9234                 :            :         }
    9235                 :            : 
    9236         [ -  + ]:         35 :         if ((err = cache_final(cache_hash, &digest))) {
    9237                 :          0 :             fprintf(stderr, "Unable to finalize cache hash: %s\n", err_str(err));
    9238                 :          0 :             exit(1);
    9239                 :            :         }
    9240                 :         35 :         artifact_dir = buf_alloc();
    9241                 :         35 :         os_path_join(o_dir, &digest, artifact_dir);
    9242         [ -  + ]:         35 :         if ((err = os_make_path(artifact_dir))) {
    9243                 :          0 :             fprintf(stderr, "Unable to create output directory '%s': %s",
    9244                 :            :                     buf_ptr(artifact_dir), err_str(err));
    9245                 :          0 :             exit(1);
    9246                 :            :         }
    9247                 :         35 :         o_final_path = buf_alloc();
    9248                 :         35 :         os_path_join(artifact_dir, final_o_basename, o_final_path);
    9249         [ -  + ]:         35 :         if ((err = os_rename(out_obj_path, o_final_path))) {
    9250                 :          0 :             fprintf(stderr, "Unable to rename object: %s\n", err_str(err));
    9251                 :         35 :             exit(1);
    9252                 :            :         }
    9253                 :            :     } else {
    9254                 :            :         // cache hit
    9255                 :         19 :         artifact_dir = buf_alloc();
    9256                 :         19 :         os_path_join(o_dir, &digest, artifact_dir);
    9257                 :         19 :         o_final_path = buf_alloc();
    9258                 :         19 :         os_path_join(artifact_dir, final_o_basename, o_final_path);
    9259                 :            :     }
    9260                 :            : 
    9261                 :         54 :     g->link_objects.append(o_final_path);
    9262                 :         54 :     g->caches_to_release.append(cache_hash);
    9263                 :         54 : }
    9264                 :            : 
    9265                 :            : // returns true if we had any cache misses
    9266                 :         81 : static void gen_c_objects(CodeGen *g) {
    9267                 :            :     Error err;
    9268                 :            : 
    9269         [ +  + ]:         81 :     if (g->c_source_files.length == 0)
    9270                 :         41 :         return;
    9271                 :            : 
    9272                 :         40 :     Buf *self_exe_path = buf_alloc();
    9273         [ -  + ]:         40 :     if ((err = os_self_exe_path(self_exe_path))) {
    9274                 :          0 :         fprintf(stderr, "Unable to get self exe path: %s\n", err_str(err));
    9275                 :          0 :         exit(1);
    9276                 :            :     }
    9277                 :            : 
    9278                 :         40 :     codegen_add_time_event(g, "Compile C Code");
    9279                 :            : 
    9280         [ +  + ]:         94 :     for (size_t c_file_i = 0; c_file_i < g->c_source_files.length; c_file_i += 1) {
    9281                 :         54 :         CFile *c_file = g->c_source_files.at(c_file_i);
    9282                 :         54 :         gen_c_object(g, self_exe_path, c_file);
    9283                 :            :     }
    9284                 :            : }
    9285                 :            : 
    9286                 :         34 : void codegen_add_object(CodeGen *g, Buf *object_path) {
    9287                 :         34 :     g->link_objects.append(object_path);
    9288                 :         34 : }
    9289                 :            : 
    9290                 :            : // Must be coordinated with with CIntType enum
    9291                 :            : static const char *c_int_type_names[] = {
    9292                 :            :     "short",
    9293                 :            :     "unsigned short",
    9294                 :            :     "int",
    9295                 :            :     "unsigned int",
    9296                 :            :     "long",
    9297                 :            :     "unsigned long",
    9298                 :            :     "long long",
    9299                 :            :     "unsigned long long",
    9300                 :            : };
    9301                 :            : 
    9302                 :            : struct GenH {
    9303                 :            :     ZigList<ZigType *> types_to_declare;
    9304                 :            : };
    9305                 :            : 
    9306                 :          0 : static void prepend_c_type_to_decl_list(CodeGen *g, GenH *gen_h, ZigType *type_entry) {
    9307         [ #  # ]:          0 :     if (type_entry->gen_h_loop_flag)
    9308                 :          0 :         return;
    9309                 :          0 :     type_entry->gen_h_loop_flag = true;
    9310                 :            : 
    9311   [ #  #  #  #  :          0 :     switch (type_entry->id) {
          #  #  #  #  #  
                #  #  # ]
    9312                 :          0 :         case ZigTypeIdInvalid:
    9313                 :            :         case ZigTypeIdMetaType:
    9314                 :            :         case ZigTypeIdComptimeFloat:
    9315                 :            :         case ZigTypeIdComptimeInt:
    9316                 :            :         case ZigTypeIdEnumLiteral:
    9317                 :            :         case ZigTypeIdUndefined:
    9318                 :            :         case ZigTypeIdNull:
    9319                 :            :         case ZigTypeIdBoundFn:
    9320                 :            :         case ZigTypeIdArgTuple:
    9321                 :            :         case ZigTypeIdErrorUnion:
    9322                 :            :         case ZigTypeIdErrorSet:
    9323                 :            :         case ZigTypeIdFnFrame:
    9324                 :            :         case ZigTypeIdAnyFrame:
    9325                 :          0 :             zig_unreachable();
    9326                 :          0 :         case ZigTypeIdVoid:
    9327                 :            :         case ZigTypeIdUnreachable:
    9328                 :            :         case ZigTypeIdBool:
    9329                 :            :         case ZigTypeIdInt:
    9330                 :            :         case ZigTypeIdFloat:
    9331                 :          0 :             return;
    9332                 :          0 :         case ZigTypeIdOpaque:
    9333                 :          0 :             gen_h->types_to_declare.append(type_entry);
    9334                 :          0 :             return;
    9335                 :          0 :         case ZigTypeIdStruct:
    9336         [ #  # ]:          0 :             for (uint32_t i = 0; i < type_entry->data.structure.src_field_count; i += 1) {
    9337                 :          0 :                 TypeStructField *field = &type_entry->data.structure.fields[i];
    9338                 :          0 :                 prepend_c_type_to_decl_list(g, gen_h, field->type_entry);
    9339                 :            :             }
    9340                 :          0 :             gen_h->types_to_declare.append(type_entry);
    9341                 :          0 :             return;
    9342                 :          0 :         case ZigTypeIdUnion:
    9343         [ #  # ]:          0 :             for (uint32_t i = 0; i < type_entry->data.unionation.src_field_count; i += 1) {
    9344                 :          0 :                 TypeUnionField *field = &type_entry->data.unionation.fields[i];
    9345                 :          0 :                 prepend_c_type_to_decl_list(g, gen_h, field->type_entry);
    9346                 :            :             }
    9347                 :          0 :             gen_h->types_to_declare.append(type_entry);
    9348                 :          0 :             return;
    9349                 :          0 :         case ZigTypeIdEnum:
    9350                 :          0 :             prepend_c_type_to_decl_list(g, gen_h, type_entry->data.enumeration.tag_int_type);
    9351                 :          0 :             gen_h->types_to_declare.append(type_entry);
    9352                 :          0 :             return;
    9353                 :          0 :         case ZigTypeIdPointer:
    9354                 :          0 :             prepend_c_type_to_decl_list(g, gen_h, type_entry->data.pointer.child_type);
    9355                 :          0 :             return;
    9356                 :          0 :         case ZigTypeIdArray:
    9357                 :          0 :             prepend_c_type_to_decl_list(g, gen_h, type_entry->data.array.child_type);
    9358                 :          0 :             return;
    9359                 :          0 :         case ZigTypeIdVector:
    9360                 :          0 :             prepend_c_type_to_decl_list(g, gen_h, type_entry->data.vector.elem_type);
    9361                 :          0 :             return;
    9362                 :          0 :         case ZigTypeIdOptional:
    9363                 :          0 :             prepend_c_type_to_decl_list(g, gen_h, type_entry->data.maybe.child_type);
    9364                 :          0 :             return;
    9365                 :          0 :         case ZigTypeIdFn:
    9366         [ #  # ]:          0 :             for (size_t i = 0; i < type_entry->data.fn.fn_type_id.param_count; i += 1) {
    9367                 :          0 :                 prepend_c_type_to_decl_list(g, gen_h, type_entry->data.fn.fn_type_id.param_info[i].type);
    9368                 :            :             }
    9369                 :          0 :             prepend_c_type_to_decl_list(g, gen_h, type_entry->data.fn.fn_type_id.return_type);
    9370                 :          0 :             return;
    9371                 :            :     }
    9372                 :            : }
    9373                 :            : 
    9374                 :          0 : static void get_c_type(CodeGen *g, GenH *gen_h, ZigType *type_entry, Buf *out_buf) {
    9375                 :          0 :     assert(type_entry);
    9376                 :            : 
    9377         [ #  # ]:          0 :     for (size_t i = 0; i < array_length(c_int_type_names); i += 1) {
    9378         [ #  # ]:          0 :         if (type_entry == g->builtin_types.entry_c_int[i]) {
    9379                 :          0 :             buf_init_from_str(out_buf, c_int_type_names[i]);
    9380                 :          0 :             return;
    9381                 :            :         }
    9382                 :            :     }
    9383         [ #  # ]:          0 :     if (type_entry == g->builtin_types.entry_c_longdouble) {
    9384                 :          0 :         buf_init_from_str(out_buf, "long double");
    9385                 :          0 :         return;
    9386                 :            :     }
    9387         [ #  # ]:          0 :     if (type_entry == g->builtin_types.entry_c_void) {
    9388                 :          0 :         buf_init_from_str(out_buf, "void");
    9389                 :          0 :         return;
    9390                 :            :     }
    9391         [ #  # ]:          0 :     if (type_entry == g->builtin_types.entry_isize) {
    9392                 :          0 :         g->c_want_stdint = true;
    9393                 :          0 :         buf_init_from_str(out_buf, "intptr_t");
    9394                 :          0 :         return;
    9395                 :            :     }
    9396         [ #  # ]:          0 :     if (type_entry == g->builtin_types.entry_usize) {
    9397                 :          0 :         g->c_want_stdint = true;
    9398                 :          0 :         buf_init_from_str(out_buf, "uintptr_t");
    9399                 :          0 :         return;
    9400                 :            :     }
    9401                 :            : 
    9402                 :          0 :     prepend_c_type_to_decl_list(g, gen_h, type_entry);
    9403                 :            : 
    9404   [ #  #  #  #  :          0 :     switch (type_entry->id) {
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
    9405                 :          0 :         case ZigTypeIdVoid:
    9406                 :          0 :             buf_init_from_str(out_buf, "void");
    9407                 :          0 :             break;
    9408                 :          0 :         case ZigTypeIdBool:
    9409                 :          0 :             buf_init_from_str(out_buf, "bool");
    9410                 :          0 :             g->c_want_stdbool = true;
    9411                 :          0 :             break;
    9412                 :          0 :         case ZigTypeIdUnreachable:
    9413                 :          0 :             buf_init_from_str(out_buf, "__attribute__((__noreturn__)) void");
    9414                 :          0 :             break;
    9415                 :          0 :         case ZigTypeIdFloat:
    9416   [ #  #  #  #  :          0 :             switch (type_entry->data.floating.bit_count) {
                      # ]
    9417                 :          0 :                 case 32:
    9418                 :          0 :                     buf_init_from_str(out_buf, "float");
    9419                 :          0 :                     break;
    9420                 :          0 :                 case 64:
    9421                 :          0 :                     buf_init_from_str(out_buf, "double");
    9422                 :          0 :                     break;
    9423                 :          0 :                 case 80:
    9424                 :          0 :                     buf_init_from_str(out_buf, "__float80");
    9425                 :          0 :                     break;
    9426                 :          0 :                 case 128:
    9427                 :          0 :                     buf_init_from_str(out_buf, "__float128");
    9428                 :          0 :                     break;
    9429                 :          0 :                 default:
    9430                 :          0 :                     zig_unreachable();
    9431                 :            :             }
    9432                 :          0 :             break;
    9433                 :          0 :         case ZigTypeIdInt:
    9434                 :          0 :             g->c_want_stdint = true;
    9435                 :          0 :             buf_resize(out_buf, 0);
    9436         [ #  # ]:          0 :             buf_appendf(out_buf, "%sint%" PRIu32 "_t",
    9437                 :          0 :                     type_entry->data.integral.is_signed ? "" : "u",
    9438                 :            :                     type_entry->data.integral.bit_count);
    9439                 :          0 :             break;
    9440                 :          0 :         case ZigTypeIdPointer:
    9441                 :            :             {
    9442                 :          0 :                 Buf child_buf = BUF_INIT;
    9443                 :          0 :                 ZigType *child_type = type_entry->data.pointer.child_type;
    9444                 :          0 :                 get_c_type(g, gen_h, child_type, &child_buf);
    9445                 :            : 
    9446         [ #  # ]:          0 :                 const char *const_str = type_entry->data.pointer.is_const ? "const " : "";
    9447                 :          0 :                 buf_resize(out_buf, 0);
    9448                 :          0 :                 buf_appendf(out_buf, "%s%s *", const_str, buf_ptr(&child_buf));
    9449                 :          0 :                 break;
    9450                 :            :             }
    9451                 :          0 :         case ZigTypeIdOptional:
    9452                 :            :             {
    9453                 :          0 :                 ZigType *child_type = type_entry->data.maybe.child_type;
    9454         [ #  # ]:          0 :                 if (!type_has_bits(child_type)) {
    9455                 :          0 :                     buf_init_from_str(out_buf, "bool");
    9456                 :          0 :                     return;
    9457         [ #  # ]:          0 :                 } else if (type_is_nonnull_ptr(child_type)) {
    9458                 :          0 :                     return get_c_type(g, gen_h, child_type, out_buf);
    9459                 :            :                 } else {
    9460                 :          0 :                     zig_unreachable();
    9461                 :            :                 }
    9462                 :            :             }
    9463                 :          0 :         case ZigTypeIdStruct:
    9464                 :            :         case ZigTypeIdOpaque:
    9465                 :            :             {
    9466                 :          0 :                 buf_init_from_str(out_buf, "struct ");
    9467                 :          0 :                 buf_append_buf(out_buf, type_h_name(type_entry));
    9468                 :          0 :                 return;
    9469                 :            :             }
    9470                 :          0 :         case ZigTypeIdUnion:
    9471                 :            :             {
    9472                 :          0 :                 buf_init_from_str(out_buf, "union ");
    9473                 :          0 :                 buf_append_buf(out_buf, type_h_name(type_entry));
    9474                 :          0 :                 return;
    9475                 :            :             }
    9476                 :          0 :         case ZigTypeIdEnum:
    9477                 :            :             {
    9478                 :          0 :                 buf_init_from_str(out_buf, "enum ");
    9479                 :          0 :                 buf_append_buf(out_buf, type_h_name(type_entry));
    9480                 :          0 :                 return;
    9481                 :            :             }
    9482                 :          0 :         case ZigTypeIdArray:
    9483                 :            :             {
    9484                 :          0 :                 ZigTypeArray *array_data = &type_entry->data.array;
    9485                 :            : 
    9486                 :          0 :                 Buf *child_buf = buf_alloc();
    9487                 :          0 :                 get_c_type(g, gen_h, array_data->child_type, child_buf);
    9488                 :            : 
    9489                 :          0 :                 buf_resize(out_buf, 0);
    9490                 :          0 :                 buf_appendf(out_buf, "%s", buf_ptr(child_buf));
    9491                 :          0 :                 return;
    9492                 :            :             }
    9493                 :          0 :         case ZigTypeIdVector:
    9494                 :          0 :             zig_panic("TODO implement get_c_type for vector types");
    9495                 :          0 :         case ZigTypeIdErrorUnion:
    9496                 :            :         case ZigTypeIdErrorSet:
    9497                 :            :         case ZigTypeIdFn:
    9498                 :          0 :             zig_panic("TODO implement get_c_type for more types");
    9499                 :          0 :         case ZigTypeIdInvalid:
    9500                 :            :         case ZigTypeIdMetaType:
    9501                 :            :         case ZigTypeIdBoundFn:
    9502                 :            :         case ZigTypeIdComptimeFloat:
    9503                 :            :         case ZigTypeIdComptimeInt:
    9504                 :            :         case ZigTypeIdEnumLiteral:
    9505                 :            :         case ZigTypeIdUndefined:
    9506                 :            :         case ZigTypeIdNull:
    9507                 :            :         case ZigTypeIdArgTuple:
    9508                 :            :         case ZigTypeIdFnFrame:
    9509                 :            :         case ZigTypeIdAnyFrame:
    9510                 :          0 :             zig_unreachable();
    9511                 :            :     }
    9512                 :            : }
    9513                 :            : 
    9514                 :            : static const char *preprocessor_alphabet1 = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    9515                 :            : static const char *preprocessor_alphabet2 = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    9516                 :            : 
    9517                 :          0 : static bool need_to_preprocessor_mangle(Buf *src) {
    9518         [ #  # ]:          0 :     for (size_t i = 0; i < buf_len(src); i += 1) {
    9519         [ #  # ]:          0 :         const char *alphabet = (i == 0) ? preprocessor_alphabet1 : preprocessor_alphabet2;
    9520                 :          0 :         uint8_t byte = buf_ptr(src)[i];
    9521         [ #  # ]:          0 :         if (strchr(alphabet, byte) == nullptr) {
    9522                 :          0 :             return true;
    9523                 :            :         }
    9524                 :            :     }
    9525                 :          0 :     return false;
    9526                 :            : }
    9527                 :            : 
    9528                 :          0 : static Buf *preprocessor_mangle(Buf *src) {
    9529         [ #  # ]:          0 :     if (!need_to_preprocessor_mangle(src)) {
    9530                 :          0 :         return buf_create_from_buf(src);
    9531                 :            :     }
    9532                 :          0 :     Buf *result = buf_alloc();
    9533         [ #  # ]:          0 :     for (size_t i = 0; i < buf_len(src); i += 1) {
    9534         [ #  # ]:          0 :         const char *alphabet = (i == 0) ? preprocessor_alphabet1 : preprocessor_alphabet2;
    9535                 :          0 :         uint8_t byte = buf_ptr(src)[i];
    9536         [ #  # ]:          0 :         if (strchr(alphabet, byte) == nullptr) {
    9537                 :            :             // perform escape
    9538                 :          0 :             buf_appendf(result, "_%02x_", byte);
    9539                 :            :         } else {
    9540                 :          0 :             buf_append_char(result, byte);
    9541                 :            :         }
    9542                 :            :     }
    9543                 :          0 :     return result;
    9544                 :            : }
    9545                 :            : 
    9546                 :          0 : static void gen_h_file(CodeGen *g) {
    9547                 :          0 :     GenH gen_h_data = {0};
    9548                 :          0 :     GenH *gen_h = &gen_h_data;
    9549                 :            : 
    9550                 :          0 :     assert(!g->is_test_build);
    9551                 :          0 :     assert(!g->disable_gen_h);
    9552                 :            : 
    9553                 :          0 :     Buf *out_h_path = buf_sprintf("%s" OS_SEP "%s.h", buf_ptr(g->output_dir), buf_ptr(g->root_out_name));
    9554                 :            : 
    9555                 :          0 :     FILE *out_h = fopen(buf_ptr(out_h_path), "wb");
    9556         [ #  # ]:          0 :     if (!out_h)
    9557                 :          0 :         zig_panic("unable to open %s: %s\n", buf_ptr(out_h_path), strerror(errno));
    9558                 :            : 
    9559                 :          0 :     Buf *export_macro = nullptr;
    9560         [ #  # ]:          0 :     if (g->is_dynamic) {
    9561                 :          0 :         export_macro = preprocessor_mangle(buf_sprintf("%s_EXPORT", buf_ptr(g->root_out_name)));
    9562                 :          0 :         buf_upcase(export_macro);
    9563                 :            :     }
    9564                 :            : 
    9565                 :          0 :     Buf *extern_c_macro = preprocessor_mangle(buf_sprintf("%s_EXTERN_C", buf_ptr(g->root_out_name)));
    9566                 :          0 :     buf_upcase(extern_c_macro);
    9567                 :            : 
    9568                 :          0 :     Buf h_buf = BUF_INIT;
    9569                 :          0 :     buf_resize(&h_buf, 0);
    9570         [ #  # ]:          0 :     for (size_t fn_def_i = 0; fn_def_i < g->fn_defs.length; fn_def_i += 1) {
    9571                 :          0 :         ZigFn *fn_table_entry = g->fn_defs.at(fn_def_i);
    9572                 :            : 
    9573         [ #  # ]:          0 :         if (fn_table_entry->export_list.length == 0)
    9574                 :          0 :             continue;
    9575                 :            : 
    9576                 :          0 :         FnTypeId *fn_type_id = &fn_table_entry->type_entry->data.fn.fn_type_id;
    9577                 :            : 
    9578                 :          0 :         Buf return_type_c = BUF_INIT;
    9579                 :          0 :         get_c_type(g, gen_h, fn_type_id->return_type, &return_type_c);
    9580                 :            : 
    9581                 :            :         Buf *symbol_name;
    9582         [ #  # ]:          0 :         if (fn_table_entry->export_list.length == 0) {
    9583                 :          0 :             symbol_name = &fn_table_entry->symbol_name;
    9584                 :            :         } else {
    9585                 :          0 :             GlobalExport *fn_export = &fn_table_entry->export_list.items[0];
    9586                 :          0 :             symbol_name = &fn_export->name;
    9587                 :            :         }
    9588                 :            : 
    9589         [ #  # ]:          0 :         buf_appendf(&h_buf, "%s %s %s(",
    9590                 :          0 :             buf_ptr(g->is_dynamic ? export_macro : extern_c_macro),
    9591                 :            :             buf_ptr(&return_type_c),
    9592                 :            :             buf_ptr(symbol_name));
    9593                 :            : 
    9594                 :          0 :         Buf param_type_c = BUF_INIT;
    9595         [ #  # ]:          0 :         if (fn_type_id->param_count > 0) {
    9596         [ #  # ]:          0 :             for (size_t param_i = 0; param_i < fn_type_id->param_count; param_i += 1) {
    9597                 :          0 :                 FnTypeParamInfo *param_info = &fn_type_id->param_info[param_i];
    9598                 :          0 :                 AstNode *param_decl_node = get_param_decl_node(fn_table_entry, param_i);
    9599                 :          0 :                 Buf *param_name = param_decl_node->data.param_decl.name;
    9600                 :            : 
    9601         [ #  # ]:          0 :                 const char *comma_str = (param_i == 0) ? "" : ", ";
    9602         [ #  # ]:          0 :                 const char *restrict_str = param_info->is_noalias ? "restrict" : "";
    9603                 :          0 :                 get_c_type(g, gen_h, param_info->type, &param_type_c);
    9604                 :            : 
    9605         [ #  # ]:          0 :                 if (param_info->type->id == ZigTypeIdArray) {
    9606                 :            :                     // Arrays decay to pointers
    9607                 :          0 :                     buf_appendf(&h_buf, "%s%s%s %s[]", comma_str, buf_ptr(&param_type_c),
    9608                 :            :                             restrict_str, buf_ptr(param_name));
    9609                 :            :                 } else {
    9610                 :          0 :                     buf_appendf(&h_buf, "%s%s%s %s", comma_str, buf_ptr(&param_type_c),
    9611                 :            :                             restrict_str, buf_ptr(param_name));
    9612                 :            :                 }
    9613                 :            :             }
    9614                 :          0 :             buf_appendf(&h_buf, ")");
    9615                 :            :         } else {
    9616                 :          0 :             buf_appendf(&h_buf, "void)");
    9617                 :            :         }
    9618                 :            : 
    9619                 :          0 :         buf_appendf(&h_buf, ";\n");
    9620                 :            : 
    9621                 :            :     }
    9622                 :            : 
    9623                 :          0 :     Buf *ifdef_dance_name = preprocessor_mangle(buf_sprintf("%s_H", buf_ptr(g->root_out_name)));
    9624                 :          0 :     buf_upcase(ifdef_dance_name);
    9625                 :            : 
    9626                 :          0 :     fprintf(out_h, "#ifndef %s\n", buf_ptr(ifdef_dance_name));
    9627                 :          0 :     fprintf(out_h, "#define %s\n\n", buf_ptr(ifdef_dance_name));
    9628                 :            : 
    9629         [ #  # ]:          0 :     if (g->c_want_stdbool)
    9630                 :          0 :         fprintf(out_h, "#include <stdbool.h>\n");
    9631         [ #  # ]:          0 :     if (g->c_want_stdint)
    9632                 :          0 :         fprintf(out_h, "#include <stdint.h>\n");
    9633                 :            : 
    9634                 :          0 :     fprintf(out_h, "\n");
    9635                 :            : 
    9636                 :          0 :     fprintf(out_h, "#ifdef __cplusplus\n");
    9637                 :          0 :     fprintf(out_h, "#define %s extern \"C\"\n", buf_ptr(extern_c_macro));
    9638                 :          0 :     fprintf(out_h, "#else\n");
    9639                 :          0 :     fprintf(out_h, "#define %s\n", buf_ptr(extern_c_macro));
    9640                 :          0 :     fprintf(out_h, "#endif\n");
    9641                 :          0 :     fprintf(out_h, "\n");
    9642                 :            : 
    9643         [ #  # ]:          0 :     if (g->is_dynamic) {
    9644                 :          0 :         fprintf(out_h, "#if defined(_WIN32)\n");
    9645                 :          0 :         fprintf(out_h, "#define %s %s __declspec(dllimport)\n", buf_ptr(export_macro), buf_ptr(extern_c_macro));
    9646                 :          0 :         fprintf(out_h, "#else\n");
    9647                 :          0 :         fprintf(out_h, "#define %s %s __attribute__((visibility (\"default\")))\n",
    9648                 :            :             buf_ptr(export_macro), buf_ptr(extern_c_macro));
    9649                 :          0 :         fprintf(out_h, "#endif\n");
    9650                 :          0 :         fprintf(out_h, "\n");
    9651                 :            :     }
    9652                 :            : 
    9653         [ #  # ]:          0 :     for (size_t type_i = 0; type_i < gen_h->types_to_declare.length; type_i += 1) {
    9654                 :          0 :         ZigType *type_entry = gen_h->types_to_declare.at(type_i);
    9655   [ #  #  #  #  :          0 :         switch (type_entry->id) {
                   #  # ]
    9656                 :          0 :             case ZigTypeIdInvalid:
    9657                 :            :             case ZigTypeIdMetaType:
    9658                 :            :             case ZigTypeIdVoid:
    9659                 :            :             case ZigTypeIdBool:
    9660                 :            :             case ZigTypeIdUnreachable:
    9661                 :            :             case ZigTypeIdInt:
    9662                 :            :             case ZigTypeIdFloat:
    9663                 :            :             case ZigTypeIdPointer:
    9664                 :            :             case ZigTypeIdComptimeFloat:
    9665                 :            :             case ZigTypeIdComptimeInt:
    9666                 :            :             case ZigTypeIdEnumLiteral:
    9667                 :            :             case ZigTypeIdArray:
    9668                 :            :             case ZigTypeIdUndefined:
    9669                 :            :             case ZigTypeIdNull:
    9670                 :            :             case ZigTypeIdErrorUnion:
    9671                 :            :             case ZigTypeIdErrorSet:
    9672                 :            :             case ZigTypeIdBoundFn:
    9673                 :            :             case ZigTypeIdArgTuple:
    9674                 :            :             case ZigTypeIdOptional:
    9675                 :            :             case ZigTypeIdFn:
    9676                 :            :             case ZigTypeIdVector:
    9677                 :            :             case ZigTypeIdFnFrame:
    9678                 :            :             case ZigTypeIdAnyFrame:
    9679                 :          0 :                 zig_unreachable();
    9680                 :            : 
    9681                 :          0 :             case ZigTypeIdEnum:
    9682         [ #  # ]:          0 :                 if (type_entry->data.enumeration.layout == ContainerLayoutExtern) {
    9683                 :          0 :                     fprintf(out_h, "enum %s {\n", buf_ptr(type_h_name(type_entry)));
    9684         [ #  # ]:          0 :                     for (uint32_t field_i = 0; field_i < type_entry->data.enumeration.src_field_count; field_i += 1) {
    9685                 :          0 :                         TypeEnumField *enum_field = &type_entry->data.enumeration.fields[field_i];
    9686                 :          0 :                         Buf *value_buf = buf_alloc();
    9687                 :          0 :                         bigint_append_buf(value_buf, &enum_field->value, 10);
    9688                 :          0 :                         fprintf(out_h, "    %s = %s", buf_ptr(enum_field->name), buf_ptr(value_buf));
    9689         [ #  # ]:          0 :                         if (field_i != type_entry->data.enumeration.src_field_count - 1) {
    9690                 :          0 :                             fprintf(out_h, ",");
    9691                 :            :                         }
    9692                 :          0 :                         fprintf(out_h, "\n");
    9693                 :            :                     }
    9694                 :          0 :                     fprintf(out_h, "};\n\n");
    9695                 :            :                 } else {
    9696                 :          0 :                     fprintf(out_h, "enum %s;\n", buf_ptr(type_h_name(type_entry)));
    9697                 :            :                 }
    9698                 :          0 :                 break;
    9699                 :          0 :             case ZigTypeIdStruct:
    9700         [ #  # ]:          0 :                 if (type_entry->data.structure.layout == ContainerLayoutExtern) {
    9701                 :          0 :                     fprintf(out_h, "struct %s {\n", buf_ptr(type_h_name(type_entry)));
    9702         [ #  # ]:          0 :                     for (uint32_t field_i = 0; field_i < type_entry->data.structure.src_field_count; field_i += 1) {
    9703                 :          0 :                         TypeStructField *struct_field = &type_entry->data.structure.fields[field_i];
    9704                 :            : 
    9705                 :          0 :                         Buf *type_name_buf = buf_alloc();
    9706                 :          0 :                         get_c_type(g, gen_h, struct_field->type_entry, type_name_buf);
    9707                 :            : 
    9708         [ #  # ]:          0 :                         if (struct_field->type_entry->id == ZigTypeIdArray) {
    9709                 :          0 :                             fprintf(out_h, "    %s %s[%" ZIG_PRI_u64 "];\n", buf_ptr(type_name_buf),
    9710                 :            :                                     buf_ptr(struct_field->name),
    9711                 :          0 :                                     struct_field->type_entry->data.array.len);
    9712                 :            :                         } else {
    9713                 :          0 :                             fprintf(out_h, "    %s %s;\n", buf_ptr(type_name_buf), buf_ptr(struct_field->name));
    9714                 :            :                         }
    9715                 :            : 
    9716                 :            :                     }
    9717                 :          0 :                     fprintf(out_h, "};\n\n");
    9718                 :            :                 } else {
    9719                 :          0 :                     fprintf(out_h, "struct %s;\n", buf_ptr(type_h_name(type_entry)));
    9720                 :            :                 }
    9721                 :          0 :                 break;
    9722                 :          0 :             case ZigTypeIdUnion:
    9723         [ #  # ]:          0 :                 if (type_entry->data.unionation.layout == ContainerLayoutExtern) {
    9724                 :          0 :                     fprintf(out_h, "union %s {\n", buf_ptr(type_h_name(type_entry)));
    9725         [ #  # ]:          0 :                     for (uint32_t field_i = 0; field_i < type_entry->data.unionation.src_field_count; field_i += 1) {
    9726                 :          0 :                         TypeUnionField *union_field = &type_entry->data.unionation.fields[field_i];
    9727                 :            : 
    9728                 :          0 :                         Buf *type_name_buf = buf_alloc();
    9729                 :          0 :                         get_c_type(g, gen_h, union_field->type_entry, type_name_buf);
    9730                 :          0 :                         fprintf(out_h, "    %s %s;\n", buf_ptr(type_name_buf), buf_ptr(union_field->name));
    9731                 :            :                     }
    9732                 :          0 :                     fprintf(out_h, "};\n\n");
    9733                 :            :                 } else {
    9734                 :          0 :                     fprintf(out_h, "union %s;\n", buf_ptr(type_h_name(type_entry)));
    9735                 :            :                 }
    9736                 :          0 :                 break;
    9737                 :          0 :             case ZigTypeIdOpaque:
    9738                 :          0 :                 fprintf(out_h, "struct %s;\n\n", buf_ptr(type_h_name(type_entry)));
    9739                 :          0 :                 break;
    9740                 :            :         }
    9741                 :            :     }
    9742                 :            : 
    9743                 :          0 :     fprintf(out_h, "%s", buf_ptr(&h_buf));
    9744                 :            : 
    9745                 :          0 :     fprintf(out_h, "\n#endif\n");
    9746                 :            : 
    9747         [ #  # ]:          0 :     if (fclose(out_h))
    9748                 :          0 :         zig_panic("unable to close h file: %s", strerror(errno));
    9749                 :          0 : }
    9750                 :            : 
    9751                 :          0 : void codegen_print_timing_report(CodeGen *g, FILE *f) {
    9752                 :          0 :     double start_time = g->timing_events.at(0).time;
    9753                 :          0 :     double end_time = g->timing_events.last().time;
    9754                 :          0 :     double total = end_time - start_time;
    9755                 :          0 :     fprintf(f, "%20s%12s%12s%12s%12s\n", "Name", "Start", "End", "Duration", "Percent");
    9756         [ #  # ]:          0 :     for (size_t i = 0; i < g->timing_events.length - 1; i += 1) {
    9757                 :          0 :         TimeEvent *te = &g->timing_events.at(i);
    9758                 :          0 :         TimeEvent *next_te = &g->timing_events.at(i + 1);
    9759                 :          0 :         fprintf(f, "%20s%12.4f%12.4f%12.4f%12.4f\n", te->name,
    9760                 :          0 :                 te->time - start_time,
    9761                 :          0 :                 next_te->time - start_time,
    9762                 :          0 :                 next_te->time - te->time,
    9763                 :          0 :                 (next_te->time - te->time) / total);
    9764                 :            :     }
    9765                 :          0 :     fprintf(f, "%20s%12.4f%12.4f%12.4f%12.4f\n", "Total", 0.0, total, total, 1.0);
    9766                 :          0 : }
    9767                 :            : 
    9768                 :        310 : void codegen_add_time_event(CodeGen *g, const char *name) {
    9769                 :        310 :     OsTimeStamp timestamp = os_timestamp_monotonic();
    9770                 :        310 :     double seconds = (double)timestamp.sec;
    9771                 :        310 :     seconds += ((double)timestamp.nsec) / 1000000000.0;
    9772                 :        310 :     g->timing_events.append({seconds, name});
    9773                 :        310 : }
    9774                 :            : 
    9775                 :         76 : static void add_cache_pkg(CodeGen *g, CacheHash *ch, ZigPackage *pkg) {
    9776         [ +  + ]:         76 :     if (buf_len(&pkg->root_src_path) == 0)
    9777                 :         44 :         return;
    9778                 :         32 :     pkg->added_to_cache = true;
    9779                 :            : 
    9780                 :         32 :     Buf *rel_full_path = buf_alloc();
    9781                 :         32 :     os_path_join(&pkg->root_src_dir, &pkg->root_src_path, rel_full_path);
    9782                 :         32 :     cache_file(ch, rel_full_path);
    9783                 :            : 
    9784                 :         32 :     auto it = pkg->package_table.entry_iterator();
    9785                 :            :     for (;;) {
    9786                 :        100 :         auto *entry = it.next();
    9787         [ +  + ]:        100 :         if (!entry)
    9788                 :         32 :             break;
    9789                 :            : 
    9790         [ -  + ]:         68 :         if (!pkg->added_to_cache) {
    9791                 :          0 :             cache_buf(ch, entry->key);
    9792                 :          0 :             add_cache_pkg(g, ch, entry->value);
    9793                 :            :         }
    9794                 :        100 :     }
    9795                 :            : }
    9796                 :            : 
    9797                 :            : // Called before init()
    9798                 :            : // is_cache_hit takes into account gen_c_objects
    9799                 :         76 : static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {
    9800                 :            :     Error err;
    9801                 :            : 
    9802                 :            :     Buf *compiler_id;
    9803         [ -  + ]:         76 :     if ((err = get_compiler_id(&compiler_id)))
    9804                 :          0 :         return err;
    9805                 :            : 
    9806                 :         76 :     CacheHash *ch = &g->cache_hash;
    9807                 :         76 :     cache_init(ch, manifest_dir);
    9808                 :            : 
    9809                 :         76 :     add_cache_pkg(g, ch, g->root_package);
    9810         [ -  + ]:         76 :     if (g->linker_script != nullptr) {
    9811                 :          0 :         cache_file(ch, buf_create_from_str(g->linker_script));
    9812                 :            :     }
    9813                 :         76 :     cache_buf(ch, compiler_id);
    9814                 :         76 :     cache_buf(ch, g->root_out_name);
    9815                 :         76 :     cache_buf(ch, g->zig_lib_dir);
    9816                 :         76 :     cache_buf(ch, g->zig_std_dir);
    9817                 :         76 :     cache_list_of_link_lib(ch, g->link_libs_list.items, g->link_libs_list.length);
    9818                 :         76 :     cache_list_of_buf(ch, g->darwin_frameworks.items, g->darwin_frameworks.length);
    9819                 :         76 :     cache_list_of_buf(ch, g->rpath_list.items, g->rpath_list.length);
    9820                 :         76 :     cache_list_of_buf(ch, g->forbidden_libs.items, g->forbidden_libs.length);
    9821                 :         76 :     cache_int(ch, g->build_mode);
    9822                 :         76 :     cache_int(ch, g->out_type);
    9823                 :         76 :     cache_bool(ch, g->zig_target->is_native);
    9824                 :         76 :     cache_int(ch, g->zig_target->arch);
    9825                 :         76 :     cache_int(ch, g->zig_target->sub_arch);
    9826                 :         76 :     cache_int(ch, g->zig_target->vendor);
    9827                 :         76 :     cache_int(ch, g->zig_target->os);
    9828                 :         76 :     cache_int(ch, g->zig_target->abi);
    9829         [ +  + ]:         76 :     if (g->zig_target->glibc_version != nullptr) {
    9830                 :         62 :         cache_int(ch, g->zig_target->glibc_version->major);
    9831                 :         62 :         cache_int(ch, g->zig_target->glibc_version->minor);
    9832                 :         62 :         cache_int(ch, g->zig_target->glibc_version->patch);
    9833                 :            :     }
    9834                 :         76 :     cache_int(ch, detect_subsystem(g));
    9835                 :         76 :     cache_bool(ch, g->strip_debug_symbols);
    9836                 :         76 :     cache_bool(ch, g->is_test_build);
    9837         [ +  + ]:         76 :     if (g->is_test_build) {
    9838                 :         16 :         cache_buf_opt(ch, g->test_filter);
    9839                 :         16 :         cache_buf_opt(ch, g->test_name_prefix);
    9840                 :            :     }
    9841                 :         76 :     cache_bool(ch, g->is_single_threaded);
    9842                 :         76 :     cache_bool(ch, g->linker_rdynamic);
    9843                 :         76 :     cache_bool(ch, g->each_lib_rpath);
    9844                 :         76 :     cache_bool(ch, g->disable_gen_h);
    9845                 :         76 :     cache_bool(ch, g->bundle_compiler_rt);
    9846                 :         76 :     cache_bool(ch, want_valgrind_support(g));
    9847                 :         76 :     cache_bool(ch, g->have_pic);
    9848                 :         76 :     cache_bool(ch, g->have_dynamic_link);
    9849                 :         76 :     cache_bool(ch, g->have_stack_probing);
    9850                 :         76 :     cache_bool(ch, g->is_dummy_so);
    9851                 :         76 :     cache_bool(ch, g->function_sections);
    9852                 :         76 :     cache_buf_opt(ch, g->mmacosx_version_min);
    9853                 :         76 :     cache_buf_opt(ch, g->mios_version_min);
    9854                 :         76 :     cache_usize(ch, g->version_major);
    9855                 :         76 :     cache_usize(ch, g->version_minor);
    9856                 :         76 :     cache_usize(ch, g->version_patch);
    9857                 :         76 :     cache_list_of_str(ch, g->llvm_argv, g->llvm_argv_len);
    9858                 :         76 :     cache_list_of_str(ch, g->clang_argv, g->clang_argv_len);
    9859                 :         76 :     cache_list_of_str(ch, g->lib_dirs.items, g->lib_dirs.length);
    9860                 :         76 :     cache_list_of_str(ch, g->framework_dirs.items, g->framework_dirs.length);
    9861         [ -  + ]:         76 :     if (g->libc) {
    9862                 :          0 :         cache_buf(ch, &g->libc->include_dir);
    9863                 :          0 :         cache_buf(ch, &g->libc->sys_include_dir);
    9864                 :          0 :         cache_buf(ch, &g->libc->crt_dir);
    9865                 :          0 :         cache_buf(ch, &g->libc->msvc_lib_dir);
    9866                 :          0 :         cache_buf(ch, &g->libc->kernel32_lib_dir);
    9867                 :            :     }
    9868                 :         76 :     cache_buf_opt(ch, g->dynamic_linker_path);
    9869                 :         76 :     cache_buf_opt(ch, g->version_script_path);
    9870                 :            : 
    9871                 :            :     // gen_c_objects appends objects to g->link_objects which we want to include in the hash
    9872                 :         76 :     gen_c_objects(g);
    9873                 :         76 :     cache_list_of_file(ch, g->link_objects.items, g->link_objects.length);
    9874                 :            : 
    9875                 :         76 :     buf_resize(digest, 0);
    9876         [ -  + ]:         76 :     if ((err = cache_hit(ch, digest))) {
    9877         [ #  # ]:          0 :         if (err != ErrorInvalidFormat)
    9878                 :          0 :             return err;
    9879                 :            :     }
    9880                 :            : 
    9881         [ +  - ]:         76 :     if (ch->manifest_file_path != nullptr) {
    9882                 :         76 :         g->caches_to_release.append(ch);
    9883                 :            :     }
    9884                 :            : 
    9885                 :         76 :     return ErrorNone;
    9886                 :            : }
    9887                 :            : 
    9888                 :        145 : static bool need_llvm_module(CodeGen *g) {
    9889                 :        145 :     return buf_len(&g->root_package->root_src_path) != 0;
    9890                 :            : }
    9891                 :            : 
    9892                 :         81 : static void resolve_out_paths(CodeGen *g) {
    9893                 :         81 :     assert(g->output_dir != nullptr);
    9894                 :         81 :     assert(g->root_out_name != nullptr);
    9895                 :            : 
    9896                 :         81 :     Buf *out_basename = buf_create_from_buf(g->root_out_name);
    9897                 :         81 :     Buf *o_basename = buf_create_from_buf(g->root_out_name);
    9898   [ +  -  -  - ]:         81 :     switch (g->emit_file_type) {
    9899                 :         81 :         case EmitFileTypeBinary: {
    9900   [ -  +  +  +  :         81 :             switch (g->out_type) {
                      - ]
    9901                 :          0 :                 case OutTypeUnknown:
    9902                 :          0 :                     zig_unreachable();
    9903                 :         40 :                 case OutTypeObj:
    9904 [ +  - ][ +  + ]:         40 :                     if (g->enable_cache && g->link_objects.length == 1 && !need_llvm_module(g)) {
         [ +  - ][ +  + ]
    9905                 :         38 :                         buf_init_from_buf(&g->output_file_path, g->link_objects.at(0));
    9906                 :         38 :                         return;
    9907                 :            :                     }
    9908 [ -  + ][ #  # ]:          2 :                     if (need_llvm_module(g) && g->link_objects.length != 0 && !g->enable_cache &&
           [ #  #  #  # ]
                 [ -  + ]
    9909                 :          0 :                         buf_eql_buf(o_basename, out_basename))
    9910                 :            :                     {
    9911                 :            :                         // make it not collide with main output object
    9912                 :          0 :                         buf_append_str(o_basename, ".root");
    9913                 :            :                     }
    9914                 :          2 :                     buf_append_str(o_basename, target_o_file_ext(g->zig_target));
    9915                 :          2 :                     buf_append_str(out_basename, target_o_file_ext(g->zig_target));
    9916                 :          2 :                     break;
    9917                 :         18 :                 case OutTypeExe:
    9918                 :         18 :                     buf_append_str(o_basename, target_o_file_ext(g->zig_target));
    9919                 :         18 :                     buf_append_str(out_basename, target_exe_file_ext(g->zig_target));
    9920                 :         18 :                     break;
    9921                 :         23 :                 case OutTypeLib:
    9922                 :         23 :                     buf_append_str(o_basename, target_o_file_ext(g->zig_target));
    9923                 :         23 :                     buf_resize(out_basename, 0);
    9924                 :         23 :                     buf_append_str(out_basename, target_lib_file_prefix(g->zig_target));
    9925                 :         23 :                     buf_append_buf(out_basename, g->root_out_name);
    9926                 :         23 :                     buf_append_str(out_basename, target_lib_file_ext(g->zig_target, !g->is_dynamic,
    9927                 :            :                                 g->version_major, g->version_minor, g->version_patch));
    9928                 :         23 :                     break;
    9929                 :            :             }
    9930                 :         43 :             break;
    9931                 :            :         }
    9932                 :          0 :         case EmitFileTypeAssembly: {
    9933                 :          0 :             const char *asm_ext = target_asm_file_ext(g->zig_target);
    9934                 :          0 :             buf_append_str(o_basename, asm_ext);
    9935                 :          0 :             buf_append_str(out_basename, asm_ext);
    9936                 :          0 :             break;
    9937                 :            :         }
    9938                 :          0 :         case EmitFileTypeLLVMIr: {
    9939                 :          0 :             const char *llvm_ir_ext = target_llvm_ir_file_ext(g->zig_target);
    9940                 :          0 :             buf_append_str(o_basename, llvm_ir_ext);
    9941                 :          0 :             buf_append_str(out_basename, llvm_ir_ext);
    9942                 :          0 :             break;
    9943                 :            :         }
    9944                 :            :     }
    9945                 :            : 
    9946                 :         43 :     os_path_join(g->output_dir, o_basename, &g->o_file_output_path);
    9947                 :         43 :     os_path_join(g->output_dir, out_basename, &g->output_file_path);
    9948                 :            : }
    9949                 :            : 
    9950                 :         81 : void codegen_build_and_link(CodeGen *g) {
    9951                 :            :     Error err;
    9952                 :         81 :     assert(g->out_type != OutTypeUnknown);
    9953                 :            : 
    9954 [ -  + ][ +  + ]:         81 :     if (!g->enable_cache && g->output_dir == nullptr) {
    9955                 :          0 :         g->output_dir = buf_create_from_str(".");
    9956                 :            :     }
    9957                 :            : 
    9958                 :         81 :     g->have_dynamic_link = detect_dynamic_link(g);
    9959                 :         81 :     g->have_pic = detect_pic(g);
    9960                 :         81 :     g->is_single_threaded = detect_single_threaded(g);
    9961                 :         81 :     g->have_err_ret_tracing = detect_err_ret_tracing(g);
    9962                 :         81 :     detect_libc(g);
    9963                 :         81 :     detect_dynamic_linker(g);
    9964                 :            : 
    9965                 :         81 :     Buf digest = BUF_INIT;
    9966         [ +  + ]:         81 :     if (g->enable_cache) {
    9967                 :         76 :         Buf *manifest_dir = buf_alloc();
    9968                 :         76 :         os_path_join(g->cache_dir, buf_create_from_str(CACHE_HASH_SUBDIR), manifest_dir);
    9969                 :            : 
    9970         [ -  + ]:         76 :         if ((err = check_cache(g, manifest_dir, &digest))) {
    9971         [ #  # ]:          0 :             if (err == ErrorCacheUnavailable) {
    9972                 :            :                 // message already printed
    9973         [ #  # ]:          0 :             } else if (err == ErrorNotDir) {
    9974                 :          0 :                 fprintf(stderr, "Unable to check cache: %s is not a directory\n",
    9975                 :            :                     buf_ptr(manifest_dir));
    9976                 :            :             } else {
    9977                 :          0 :                 fprintf(stderr, "Unable to check cache: %s: %s\n", buf_ptr(manifest_dir), err_str(err));
    9978                 :            :             }
    9979                 :         76 :             exit(1);
    9980                 :            :         }
    9981                 :            :     } else {
    9982                 :            :         // There is a call to this in check_cache
    9983                 :          5 :         gen_c_objects(g);
    9984                 :            :     }
    9985                 :            : 
    9986 [ +  + ][ +  + ]:         81 :     if (g->enable_cache && buf_len(&digest) != 0) {
                 [ +  + ]
    9987                 :         38 :         g->output_dir = buf_sprintf("%s" OS_SEP CACHE_OUT_SUBDIR OS_SEP "%s",
    9988                 :            :                 buf_ptr(g->cache_dir), buf_ptr(&digest));
    9989                 :         38 :         resolve_out_paths(g);
    9990                 :            :     } else {
    9991         [ +  + ]:         43 :         if (need_llvm_module(g)) {
    9992                 :         20 :             init(g);
    9993                 :            : 
    9994                 :         20 :             codegen_add_time_event(g, "Semantic Analysis");
    9995                 :            : 
    9996                 :         20 :             gen_root_source(g);
    9997                 :            : 
    9998                 :            :         }
    9999         [ +  + ]:         43 :         if (g->enable_cache) {
   10000         [ +  - ]:         38 :             if (buf_len(&digest) == 0) {
   10001         [ -  + ]:         38 :                 if ((err = cache_final(&g->cache_hash, &digest))) {
   10002                 :          0 :                     fprintf(stderr, "Unable to finalize cache hash: %s\n", err_str(err));
   10003                 :          0 :                     exit(1);
   10004                 :            :                 }
   10005                 :            :             }
   10006                 :         38 :             g->output_dir = buf_sprintf("%s" OS_SEP CACHE_OUT_SUBDIR OS_SEP "%s",
   10007                 :            :                     buf_ptr(g->cache_dir), buf_ptr(&digest));
   10008                 :            : 
   10009         [ -  + ]:         38 :             if ((err = os_make_path(g->output_dir))) {
   10010                 :          0 :                 fprintf(stderr, "Unable to create output directory: %s\n", err_str(err));
   10011                 :          0 :                 exit(1);
   10012                 :            :             }
   10013                 :            :         }
   10014                 :         43 :         resolve_out_paths(g);
   10015                 :            : 
   10016         [ +  + ]:         43 :         if (need_llvm_module(g)) {
   10017                 :         20 :             codegen_add_time_event(g, "Code Generation");
   10018                 :            : 
   10019                 :         20 :             do_code_gen(g);
   10020                 :         20 :             codegen_add_time_event(g, "LLVM Emit Output");
   10021                 :         20 :             zig_llvm_emit_output(g);
   10022                 :            : 
   10023 [ +  - ][ -  + ]:         20 :             if (!g->disable_gen_h && (g->out_type == OutTypeObj || g->out_type == OutTypeLib)) {
                 [ +  + ]
   10024                 :          0 :                 codegen_add_time_event(g, "Generate .h");
   10025                 :         20 :                 gen_h_file(g);
   10026                 :            :             }
   10027                 :            :         }
   10028                 :            : 
   10029                 :            :         // If we're outputting assembly or llvm IR we skip linking.
   10030                 :            :         // If we're making a library or executable we must link.
   10031                 :            :         // If there is more than one object, we have to link them (with -r).
   10032                 :            :         // Finally, if we didn't make an object from zig source, and we don't have caching enabled,
   10033                 :            :         // then we have an object from C source that we must copy to the output dir which we do with a -r link.
   10034 [ +  - ][ +  + ]:         81 :         if (g->emit_file_type == EmitFileTypeBinary && (g->out_type != OutTypeObj || g->link_objects.length > 1 ||
           [ +  +  +  - ]
                 [ +  + ]
   10035         [ -  + ]:         38 :                     (!need_llvm_module(g) && !g->enable_cache)))
   10036                 :            :         {
   10037                 :         24 :             codegen_link(g);
   10038                 :            :         }
   10039                 :            :     }
   10040                 :            : 
   10041                 :         81 :     codegen_release_caches(g);
   10042                 :         81 :     codegen_add_time_event(g, "Done");
   10043                 :         81 : }
   10044                 :            : 
   10045                 :         81 : void codegen_release_caches(CodeGen *g) {
   10046         [ +  + ]:        211 :     while (g->caches_to_release.length != 0) {
   10047                 :        130 :         cache_release(g->caches_to_release.pop());
   10048                 :            :     }
   10049                 :         81 : }
   10050                 :            : 
   10051                 :         28 : ZigPackage *codegen_create_package(CodeGen *g, const char *root_src_dir, const char *root_src_path,
   10052                 :            :         const char *pkg_path)
   10053                 :            : {
   10054                 :         28 :     init(g);
   10055                 :         28 :     ZigPackage *pkg = new_package(root_src_dir, root_src_path, pkg_path);
   10056         [ +  - ]:         28 :     if (g->std_package != nullptr) {
   10057                 :         28 :         assert(g->compile_var_package != nullptr);
   10058                 :         28 :         pkg->package_table.put(buf_create_from_str("std"), g->std_package);
   10059                 :            : 
   10060         [ +  + ]:         28 :         ZigPackage *main_pkg = g->is_test_build ? g->test_runner_package : g->root_package;
   10061                 :         28 :         pkg->package_table.put(buf_create_from_str("root"), main_pkg);
   10062                 :            : 
   10063                 :         28 :         pkg->package_table.put(buf_create_from_str("builtin"), g->compile_var_package);
   10064                 :            :     }
   10065                 :         28 :     return pkg;
   10066                 :            : }
   10067                 :            : 
   10068                 :         63 : CodeGen *create_child_codegen(CodeGen *parent_gen, Buf *root_src_path, OutType out_type,
   10069                 :            :         ZigLibCInstallation *libc)
   10070                 :            : {
   10071                 :         63 :     CodeGen *child_gen = codegen_create(nullptr, root_src_path, parent_gen->zig_target, out_type,
   10072                 :            :         parent_gen->build_mode, parent_gen->zig_lib_dir, parent_gen->zig_std_dir, libc, get_stage1_cache_path(),
   10073                 :         63 :         false);
   10074                 :         63 :     child_gen->disable_gen_h = true;
   10075                 :         63 :     child_gen->want_stack_check = WantStackCheckDisabled;
   10076                 :         63 :     child_gen->verbose_tokenize = parent_gen->verbose_tokenize;
   10077                 :         63 :     child_gen->verbose_ast = parent_gen->verbose_ast;
   10078                 :         63 :     child_gen->verbose_link = parent_gen->verbose_link;
   10079                 :         63 :     child_gen->verbose_ir = parent_gen->verbose_ir;
   10080                 :         63 :     child_gen->verbose_llvm_ir = parent_gen->verbose_llvm_ir;
   10081                 :         63 :     child_gen->verbose_cimport = parent_gen->verbose_cimport;
   10082                 :         63 :     child_gen->verbose_cc = parent_gen->verbose_cc;
   10083                 :         63 :     child_gen->llvm_argv = parent_gen->llvm_argv;
   10084                 :         63 :     child_gen->dynamic_linker_path = parent_gen->dynamic_linker_path;
   10085                 :            : 
   10086                 :         63 :     codegen_set_strip(child_gen, parent_gen->strip_debug_symbols);
   10087         [ +  + ]:         63 :     child_gen->want_pic = parent_gen->have_pic ? WantPICEnabled : WantPICDisabled;
   10088                 :         63 :     child_gen->valgrind_support = ValgrindSupportDisabled;
   10089                 :            : 
   10090                 :         63 :     codegen_set_errmsg_color(child_gen, parent_gen->err_color);
   10091                 :            : 
   10092                 :         63 :     codegen_set_mmacosx_version_min(child_gen, parent_gen->mmacosx_version_min);
   10093                 :         63 :     codegen_set_mios_version_min(child_gen, parent_gen->mios_version_min);
   10094                 :            : 
   10095                 :         63 :     child_gen->enable_cache = true;
   10096                 :            : 
   10097                 :         63 :     return child_gen;
   10098                 :            : }
   10099                 :            : 
   10100                 :         81 : CodeGen *codegen_create(Buf *main_pkg_path, Buf *root_src_path, const ZigTarget *target,
   10101                 :            :     OutType out_type, BuildMode build_mode, Buf *override_lib_dir, Buf *override_std_dir,
   10102                 :            :     ZigLibCInstallation *libc, Buf *cache_dir, bool is_test_build)
   10103                 :            : {
   10104                 :         81 :     CodeGen *g = allocate<CodeGen>(1);
   10105                 :            : 
   10106                 :         81 :     codegen_add_time_event(g, "Initialize");
   10107                 :            : 
   10108                 :         81 :     g->subsystem = TargetSubsystemAuto;
   10109                 :         81 :     g->libc = libc;
   10110                 :         81 :     g->zig_target = target;
   10111                 :         81 :     g->cache_dir = cache_dir;
   10112                 :            : 
   10113         [ +  + ]:         81 :     if (override_lib_dir == nullptr) {
   10114                 :         18 :         g->zig_lib_dir = get_zig_lib_dir();
   10115                 :            :     } else {
   10116                 :         63 :         g->zig_lib_dir = override_lib_dir;
   10117                 :            :     }
   10118                 :            : 
   10119         [ +  + ]:         81 :     if (override_std_dir == nullptr) {
   10120                 :         18 :         g->zig_std_dir = buf_alloc();
   10121                 :         18 :         os_path_join(g->zig_lib_dir, buf_create_from_str("std"), g->zig_std_dir);
   10122                 :            :     } else {
   10123                 :         63 :         g->zig_std_dir = override_std_dir;
   10124                 :            :     }
   10125                 :            : 
   10126                 :         81 :     g->zig_c_headers_dir = buf_alloc();
   10127                 :         81 :     os_path_join(g->zig_lib_dir, buf_create_from_str("include"), g->zig_c_headers_dir);
   10128                 :            : 
   10129                 :         81 :     g->build_mode = build_mode;
   10130                 :         81 :     g->out_type = out_type;
   10131                 :         81 :     g->import_table.init(32);
   10132                 :         81 :     g->builtin_fn_table.init(32);
   10133                 :         81 :     g->primitive_type_table.init(32);
   10134                 :         81 :     g->type_table.init(32);
   10135                 :         81 :     g->fn_type_table.init(32);
   10136                 :         81 :     g->error_table.init(16);
   10137                 :         81 :     g->generic_table.init(16);
   10138                 :         81 :     g->llvm_fn_table.init(16);
   10139                 :         81 :     g->memoized_fn_eval_table.init(16);
   10140                 :         81 :     g->exported_symbol_names.init(8);
   10141                 :         81 :     g->external_prototypes.init(8);
   10142                 :         81 :     g->string_literals_table.init(16);
   10143                 :         81 :     g->type_info_cache.init(32);
   10144                 :         81 :     g->is_test_build = is_test_build;
   10145                 :         81 :     g->is_single_threaded = false;
   10146                 :         81 :     buf_resize(&g->global_asm, 0);
   10147                 :            : 
   10148         [ +  + ]:       1944 :     for (size_t i = 0; i < array_length(symbols_that_llvm_depends_on); i += 1) {
   10149                 :       1863 :         g->external_prototypes.put(buf_create_from_str(symbols_that_llvm_depends_on[i]), nullptr);
   10150                 :            :     }
   10151                 :            : 
   10152         [ +  + ]:         81 :     if (root_src_path) {
   10153                 :            :         Buf *root_pkg_path;
   10154                 :            :         Buf *rel_root_src_path;
   10155         [ +  - ]:         37 :         if (main_pkg_path == nullptr) {
   10156                 :         37 :             Buf *src_basename = buf_alloc();
   10157                 :         37 :             Buf *src_dir = buf_alloc();
   10158                 :         37 :             os_path_split(root_src_path, src_dir, src_basename);
   10159                 :            : 
   10160         [ -  + ]:         37 :             if (buf_len(src_basename) == 0) {
   10161                 :          0 :                 fprintf(stderr, "Invalid root source path: %s\n", buf_ptr(root_src_path));
   10162                 :          0 :                 exit(1);
   10163                 :            :             }
   10164                 :         37 :             root_pkg_path = src_dir;
   10165                 :         37 :             rel_root_src_path = src_basename;
   10166                 :            :         } else {
   10167                 :          0 :             Buf resolved_root_src_path = os_path_resolve(&root_src_path, 1);
   10168                 :          0 :             Buf resolved_main_pkg_path = os_path_resolve(&main_pkg_path, 1);
   10169                 :            : 
   10170         [ #  # ]:          0 :             if (!buf_starts_with_buf(&resolved_root_src_path, &resolved_main_pkg_path)) {
   10171                 :          0 :                 fprintf(stderr, "Root source path '%s' outside main package path '%s'",
   10172                 :            :                         buf_ptr(root_src_path), buf_ptr(main_pkg_path));
   10173                 :          0 :                 exit(1);
   10174                 :            :             }
   10175                 :          0 :             root_pkg_path = main_pkg_path;
   10176                 :          0 :             rel_root_src_path = buf_create_from_mem(
   10177                 :          0 :                     buf_ptr(&resolved_root_src_path) + buf_len(&resolved_main_pkg_path) + 1,
   10178                 :          0 :                     buf_len(&resolved_root_src_path) - buf_len(&resolved_main_pkg_path) - 1);
   10179                 :            :         }
   10180                 :            : 
   10181                 :         37 :         g->root_package = new_package(buf_ptr(root_pkg_path), buf_ptr(rel_root_src_path), "");
   10182                 :         37 :         g->std_package = new_package(buf_ptr(g->zig_std_dir), "std.zig", "std");
   10183                 :         37 :         g->root_package->package_table.put(buf_create_from_str("std"), g->std_package);
   10184                 :            :     } else {
   10185                 :         44 :         g->root_package = new_package(".", "", "");
   10186                 :            :     }
   10187                 :            : 
   10188                 :         81 :     g->root_package->package_table.put(buf_create_from_str("root"), g->root_package);
   10189                 :            : 
   10190                 :         81 :     g->zig_std_special_dir = buf_alloc();
   10191                 :         81 :     os_path_join(g->zig_std_dir, buf_sprintf("special"), g->zig_std_special_dir);
   10192                 :            : 
   10193                 :         81 :     assert(target != nullptr);
   10194         [ +  + ]:         81 :     if (!target->is_native) {
   10195                 :         14 :         g->each_lib_rpath = false;
   10196                 :            :     } else {
   10197                 :         67 :         g->each_lib_rpath = true;
   10198                 :            : 
   10199         [ -  + ]:         67 :         if (target_os_is_darwin(g->zig_target->os)) {
   10200                 :          0 :             init_darwin_native(g);
   10201                 :            :         }
   10202                 :            : 
   10203                 :            :     }
   10204                 :            : 
   10205         [ +  + ]:         81 :     if (target_os_requires_libc(g->zig_target->os)) {
   10206                 :          6 :         g->libc_link_lib = create_link_lib(buf_create_from_str("c"));
   10207                 :          6 :         g->link_libs_list.append(g->libc_link_lib);
   10208                 :            :     }
   10209                 :            : 
   10210                 :         81 :     target_triple_llvm(&g->llvm_triple_str, g->zig_target);
   10211                 :         81 :     g->pointer_size_bytes = target_arch_pointer_bit_width(g->zig_target->arch) / 8;
   10212                 :            : 
   10213         [ -  + ]:         81 :     if (!target_has_debug_info(g->zig_target)) {
   10214                 :          0 :         g->strip_debug_symbols = true;
   10215                 :            :     }
   10216                 :            : 
   10217                 :         81 :     return g;
   10218                 :            : }
   10219                 :            : 
   10220                 :      53523 : bool codegen_fn_has_err_ret_tracing_arg(CodeGen *g, ZigType *return_type) {
   10221 [ +  - ][ +  + ]:      91530 :     return g->have_err_ret_tracing &&
   10222         [ +  + ]:      38007 :         (return_type->id == ZigTypeIdErrorUnion ||
   10223                 :      53523 :          return_type->id == ZigTypeIdErrorSet);
   10224                 :            : }
   10225                 :            : 
   10226                 :       1648 : bool codegen_fn_has_err_ret_tracing_stack(CodeGen *g, ZigFn *fn, bool is_async) {
   10227         [ +  - ]:       1648 :     if (is_async) {
   10228         [ +  - ]:       2480 :         return g->have_err_ret_tracing && (fn->calls_or_awaits_errorable_fn ||
           [ +  +  +  + ]
   10229                 :       2480 :             codegen_fn_has_err_ret_tracing_arg(g, fn->type_entry->data.fn.fn_type_id.return_type));
   10230                 :            :     } else {
   10231         [ #  # ]:          0 :         return g->have_err_ret_tracing && fn->calls_or_awaits_errorable_fn &&
           [ #  #  #  # ]
   10232                 :          0 :             !codegen_fn_has_err_ret_tracing_arg(g, fn->type_entry->data.fn.fn_type_id.return_type);
   10233                 :            :     }
   10234                 :            : }

Generated by: LCOV version 1.14