1 /*
2  * Copyright (c) 2012-2019, NVIDIA CORPORATION.  All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 /**
19    \file
20    \brief Main module to generate LLVM debug informations using metadata
21  */
22 
23 #include "lldebug.h"
24 #include "dtypeutl.h"
25 #include "global.h"
26 #include "symtab.h"
27 #include "ll_structure.h"
28 #include "ll_builder.h"
29 #include "dwarf2.h"
30 #include "error.h"
31 #include "version.h"
32 #include "fih.h"
33 #include "llassem.h"
34 #include "cgllvm.h"
35 #include "cgmain.h"
36 #include "flang/ADT/hash.h"
37 #include "symfun.h"
38 
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #ifndef HOST_WIN
43 #include <unistd.h>
44 #endif
45 
46 #include "upper.h"
47 
48 #ifdef __cplusplus
49 /* clang-format off */
GetParamSptr(int dpdsc,int i)50 inline SPTR GetParamSptr(int dpdsc, int i) {
51   return static_cast<SPTR>(aux.dpdsc_base[dpdsc + i]);
52 }
53 /* clang-format on */
54 #else
55 #define GetParamSptr(dpdsc, i) (aux.dpdsc_base[dpdsc + i])
56 #endif
57 
58 #if !defined(DECLLINEG)
59 #define DECLLINEG(sptr) 0
60 #endif
61 
62 #ifndef DW_TAG_auto_variable
63 #define DW_TAG_auto_variable 0x100
64 #endif
65 
66 #ifndef DW_TAG_arg_variable
67 #define DW_TAG_arg_variable 0x101
68 #endif
69 
70 #ifndef DW_TAG_return_variable
71 #define DW_TAG_return_variable 0x102
72 #endif
73 
74 #ifndef DW_TAG_vector_type
75 #define DW_TAG_vector_type 0x103
76 #endif
77 
78 const int DIFLAG_ARTIFICIAL = 1 << 6;
79 const int DIFLAG_ISMAINPGM = 1 << 21;
80 static int DIFLAG_PURE;
81 static int DIFLAG_ELEMENTAL;
82 static int DIFLAG_RECUSIVE;
83 
84 typedef struct {
85   LL_MDRef mdnode; /**< mdnode for block */
86   int sptr;        /**< block sptr */
87   int startline;
88   int endline;
89   int keep;
90   LL_MDRef *line_mdnodes; /**< mdnodes for block lines */
91   LL_MDRef null_loc;
92 } BLKINFO;
93 
94 typedef struct {
95   LL_MDRef mdnode;
96   INSTR_LIST *instr;
97   int sptr;
98 } PARAMINFO;
99 
100 struct sptr_to_mdnode_map {
101   int sptr;
102   LL_MDRef mdnode;
103   struct sptr_to_mdnode_map *next;
104 };
105 
106 typedef struct import_entity {
107   SPTR entity;                 /**< sptr of pending import entity */
108   IMPORT_TYPE entity_type;     /**< 0 for DECLARATION; 1 for MODULE; 2 for UNIT */
109   SPTR func;                   /**< sptr of function import to */
110   struct import_entity *next;  /**< pointer to the next node */
111 } import_entity;
112 
113 #define BLK_STACK_SIZE 1024
114 #define PARAM_STACK_SIZE 1024
115 
116 struct LL_DebugInfo {
117   LL_Module *module;           /**< Pointer to the containing LL_Module */
118   LL_MDRef llvm_dbg_sp;        /**< List of subprogram mdnodes */
119   LL_MDRef llvm_dbg_gv;        /**< List of global variables mdnodes */
120   LL_MDRef llvm_dbg_retained;  /**< List of retained type mdnodes */
121   LL_MDRef llvm_dbg_enum;      /**< List of enum mdnodes */
122   LL_MDRef llvm_dbg_imported;  /**< List of imported entity mdnodes */
123   LL_MDRef *llvm_dbg_lv_array; /**< List of formal parameters to routine */
124   char producer[1024];
125   LL_MDRef comp_unit_mdnode;
126   LL_MDRef *file_array;
127   int file_array_sz;
128   LL_MDRef cur_subprogram_mdnode;
129   unsigned cur_subprogram_func_ptr_offset;
130   LL_MDRef cur_parameters_mdnode;
131   LL_MDRef cur_module_mdnode;
132   LL_MDRef cur_cmnblk_mdnode;
133   int cur_subprogram_lineno;
134   LL_MDRef cur_subprogram_null_loc;
135   LL_MDRef cur_line_mdnode;
136   PARAMINFO param_stack[PARAM_STACK_SIZE];
137   LL_MDRef *dtype_array;
138   int dtype_array_sz;
139   LL_MDRef texture_type_mdnode;
140 
141   BLKINFO cur_blk;
142   BLKINFO *blk_tab;
143   int blk_tab_size;
144   int blk_idx;
145   char *cur_module_name;
146 
147   int param_idx;
148   int routine_count;
149   int routine_idx;
150 
151   struct sptr_to_mdnode_map *sptrs_to_mdnodes;
152   hashmap_t subroutine_mdnodes;
153   hashset_t entity_func_added;
154   import_entity *import_entity_list; /**< list of entities to be imported to func */
155   bool need_dup_composite_type; /**< indicator of duplicate composite type when needed */
156   SPTR gbl_var_sptr; /**< current global variable symbol */
157   LL_MDRef gbl_obj_mdnode; /**< mdnode reference to the global object in STATICS */
158   LL_MDRef gbl_obj_exp_mdnode; /**< the expression mdnode of the above global object */
159 
160   unsigned scope_is_global : 1;
161 };
162 
163 static LL_MDRef lldbg_emit_modified_type(LL_DebugInfo *, DTYPE, SPTR, int);
164 static LL_MDRef lldbg_create_module_flag_mdnode(LL_DebugInfo *db, int severity,
165                                                 char *name, int value);
166 static LL_MDRef lldbg_create_outlined_parameters_node(LL_DebugInfo *db);
167 static LL_MDRef lldbg_create_file_mdnode(LL_DebugInfo *db, char *filename,
168                                          char *sourcedir, LL_MDRef context,
169                                          int index);
170 static LL_MDRef lldbg_emit_type(LL_DebugInfo *db, DTYPE dtype, SPTR sptr,
171                                 int findex, bool is_reference,
172                                 bool skip_first_dim,
173                                 bool skipDataDependentTypes);
174 static LL_MDRef lldbg_fwd_local_variable(LL_DebugInfo *db, int sptr, int findex,
175                                          int emit_dummy_as_local);
176 static void lldbg_emit_imported_entity(LL_DebugInfo *db, SPTR entity_sptr,
177                                        SPTR func_sptr, IMPORT_TYPE entity_type);
178 /* ---------------------------------------------------------------------- */
179 
180 void
InitializeDIFlags(const LL_IRFeatures * feature)181 InitializeDIFlags(const LL_IRFeatures *feature)
182 {
183 #ifdef FLANG_LLVM_EXTENSIONS
184   if (ll_feature_debug_info_ver70(feature)) {
185     DIFLAG_PURE = 1 << 27;
186     DIFLAG_ELEMENTAL = 1 << 28;
187     DIFLAG_RECUSIVE = 1 << 29;
188   } else {
189     DIFLAG_PURE = 1 << 22;
190     DIFLAG_ELEMENTAL = 1 << 23;
191     DIFLAG_RECUSIVE = 1 << 24;
192   }
193 #else
194   // do nothing
195 #endif
196 }
197 
198 char *
lldbg_alloc(INT size)199 lldbg_alloc(INT size)
200 {
201   char *p = (char *)getitem(LLVM_LONGTERM_AREA, size);
202   assert(p, "lldbg_alloc(), out of memory", 0, ERR_Fatal);
203   memset(p, 0, size);
204   return p;
205 }
206 
207 static ISZ_T
lldbg_get_sizeof(int element)208 lldbg_get_sizeof(int element)
209 {
210   ISZ_T sz;
211 #if defined(FLDSZG)
212   if (FIELDG(element) && FLDSZG(element))
213     return FLDSZG(element);
214 #endif
215   if (!element || !DTYPEG(element))
216     return 0;
217   sz = zsize_of(DTYPEG(element)) * 8;
218   if (sz < 0)
219     sz = 0;
220   return sz;
221 }
222 
223 /**
224    \brief Make an i32 operand with a DWARF tag and possibly a version number.
225 
226    LLVM 3.6 onwards do not encode the debug info version in the tag field.
227  */
228 static int
make_dwtag(LL_DebugInfo * db,int tag)229 make_dwtag(LL_DebugInfo *db, int tag)
230 {
231   if (ll_feature_versioned_dw_tag(&db->module->ir))
232     tag |= db->module->ir.debug_info_version << 16;
233   return tag;
234 }
235 
236 static LL_MDRef
lldbg_create_module_flag_mdnode(LL_DebugInfo * db,int severity,char * name,int value)237 lldbg_create_module_flag_mdnode(LL_DebugInfo *db, int severity, char *name,
238                                 int value)
239 {
240   LLMD_Builder mdb = llmd_init(db->module);
241 
242   llmd_add_i32(mdb, severity);
243   llmd_add_string(mdb, name);
244   llmd_add_i32(mdb, value);
245 
246   return llmd_finish(mdb);
247 }
248 
249 static LL_MDRef
get_file_mdnode(LL_DebugInfo * db,int index)250 get_file_mdnode(LL_DebugInfo *db, int index)
251 {
252   if (index * 2 < db->file_array_sz)
253     return db->file_array[index * 2];
254   return ll_get_md_null();
255 }
256 
257 static LL_MDRef
get_filedesc_mdnode(LL_DebugInfo * db,int index)258 get_filedesc_mdnode(LL_DebugInfo *db, int index)
259 {
260   if ((index * 2 + 1) < db->file_array_sz)
261     return db->file_array[index * 2 + 1];
262   return ll_get_md_null();
263 }
264 
265 static LL_MDRef
lldbg_create_compile_unit_mdnode(LL_DebugInfo * db,int lang_tag,char * filename,char * sourcedir,char * producer,int main,int optimized,char * compflags,int vruntime,LL_MDRef * enum_types_list,LL_MDRef * retained_types_list,LL_MDRef * subprograms_list,LL_MDRef * gv_list,LL_MDRef * imported_entity_list)266 lldbg_create_compile_unit_mdnode(LL_DebugInfo *db, int lang_tag, char *filename,
267                                  char *sourcedir, char *producer, int main,
268                                  int optimized, char *compflags, int vruntime,
269                                  LL_MDRef *enum_types_list,
270                                  LL_MDRef *retained_types_list,
271                                  LL_MDRef *subprograms_list, LL_MDRef *gv_list,
272                                  LL_MDRef *imported_entity_list)
273 {
274   LLMD_Builder mdb = llmd_init(db->module);
275   LL_MDRef cur_mdnode;
276 
277   llmd_set_class(mdb, LL_DICompileUnit);
278   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_compile_unit));
279 
280   if (ll_feature_debug_info_pre34(&db->module->ir)) {
281     llmd_add_i32(mdb, 0); /* Unused field. */
282     llmd_add_i32(mdb, lang_tag);
283     llmd_add_string(mdb, filename);
284     llmd_add_string(mdb, sourcedir);
285   } else {
286     LL_MDRef file_mdnode = get_filedesc_mdnode(db, 1);
287     if (LL_MDREF_IS_NULL(file_mdnode))
288       file_mdnode = lldbg_create_file_mdnode(db, filename, sourcedir,
289                                              ll_get_md_null(), 1);
290     llmd_add_md(mdb, file_mdnode);
291     llmd_add_i32(mdb, lang_tag);
292   }
293 
294   llmd_add_string(mdb, producer);
295   if (ll_feature_debug_info_pre34(&db->module->ir))
296     llmd_add_i1(mdb, main);
297   llmd_add_i1(mdb, optimized);
298   llmd_add_string(mdb, compflags);
299   llmd_add_i32(mdb, vruntime);
300 
301   *enum_types_list = ll_create_flexible_md_node(db->module);
302   *retained_types_list = ll_create_flexible_md_node(db->module);
303   *subprograms_list = ll_create_flexible_md_node(db->module);
304   *gv_list = ll_create_flexible_md_node(db->module);
305   *imported_entity_list = ll_create_flexible_md_node(db->module);
306 
307   if (ll_feature_debug_info_pre34(&db->module->ir)) {
308     llmd_add_md(mdb,
309                 ll_get_md_node(db->module, LL_PlainMDNode, enum_types_list, 1));
310     llmd_add_md(mdb, ll_get_md_node(db->module, LL_PlainMDNode,
311                                     retained_types_list, 1));
312     llmd_add_md(
313         mdb, ll_get_md_node(db->module, LL_PlainMDNode, subprograms_list, 1));
314     llmd_add_md(mdb, ll_get_md_node(db->module, LL_PlainMDNode, gv_list, 1));
315   } else {
316     llmd_add_md(mdb, *enum_types_list);
317     llmd_add_md(mdb, *retained_types_list);
318     if (!ll_feature_subprogram_not_in_cu(&db->module->ir))
319       llmd_add_md(mdb, *subprograms_list);
320     llmd_add_md(mdb, *gv_list);
321     if (ll_feature_subprogram_not_in_cu(&db->module->ir))
322       llmd_add_i32(mdb, 1); /* emissionMode: FullDebug */
323     llmd_add_md(mdb, *imported_entity_list);
324     llmd_add_string(mdb, "");
325   }
326 
327   llmd_set_distinct(mdb);
328   cur_mdnode = llmd_finish(mdb);
329   ll_extend_named_md_node(db->module, MD_llvm_dbg_cu, cur_mdnode);
330 
331   return cur_mdnode;
332 }
333 
334 static LL_MDRef
lldbg_create_module_mdnode(LL_DebugInfo * db,LL_MDRef _,char * name,LL_MDRef scope,int lineno)335 lldbg_create_module_mdnode(LL_DebugInfo *db, LL_MDRef _, char *name,
336                            LL_MDRef scope, int lineno)
337 {
338   LLMD_Builder mdb;
339   char *module_name, *pname, *pmname;
340   unsigned tag = ll_feature_debug_info_pre34(&db->module->ir) ? DW_TAG_namespace
341                                                               : DW_TAG_module;
342 
343   if (name && db->cur_module_name && !strcmp(name, db->cur_module_name))
344     return db->cur_module_mdnode;
345 
346   mdb = llmd_init(db->module);
347   module_name = (char *)lldbg_alloc(strlen(name) + 1);
348   pname = name;
349   pmname = module_name;
350   while (*pname != '\0') {
351     *pmname = tolower(*pname);
352     pname++;
353     pmname++;
354   }
355   *pmname = '\0'; /* append null char to end of string */
356 
357   if (ll_feature_no_file_in_namespace(&db->module->ir)) {
358     // Use the DIModule template
359     llmd_set_class(mdb, LL_DIModule);
360     llmd_add_i32(mdb, make_dwtag(db, DW_TAG_module)); // tag
361     llmd_add_md(mdb, scope);                          // scope
362     llmd_add_string(mdb, module_name);                // name
363   } else {
364     llmd_set_class(mdb, LL_DINamespace);
365     llmd_add_i32(mdb, make_dwtag(db, tag));
366     if (!ll_feature_debug_info_pre34(&db->module->ir))
367       llmd_add_md(mdb, scope);
368     llmd_add_null(mdb);
369     llmd_add_string(mdb, module_name);
370     if (ll_feature_debug_info_pre34(&db->module->ir))
371       llmd_add_md(mdb, scope);
372     llmd_add_i32(mdb, lineno);
373   }
374   db->cur_module_name = module_name;
375   db->cur_module_mdnode = llmd_finish(mdb);
376   if (flg.debug && ll_feature_no_file_in_namespace(&db->module->ir))
377     ll_add_module_debug(cpu_llvm_module->module_debug_map, module_name,
378                         db->cur_module_mdnode);
379   return db->cur_module_mdnode;
380 }
381 
382 static LL_MDRef
lldbg_create_file_mdnode(LL_DebugInfo * db,char * filename,char * sourcedir,LL_MDRef context,int index)383 lldbg_create_file_mdnode(LL_DebugInfo *db, char *filename, char *sourcedir,
384                          LL_MDRef context, int index)
385 {
386   LLMD_Builder mdb = llmd_init(db->module);
387   LL_MDRef cur_mdnode;
388 
389   llmd_set_class(mdb, LL_DIFile);
390   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_file_type));
391 
392   if (!ll_feature_debug_info_pre34(&db->module->ir)) {
393     LLMD_Builder pairmd = llmd_init(db->module);
394     llmd_set_class(pairmd, LL_DIFile);
395     llmd_add_string(pairmd, filename);
396     llmd_add_string(pairmd, sourcedir);
397     cur_mdnode = llmd_finish(pairmd);
398 
399     llmd_add_md(mdb, cur_mdnode);
400     NEEDB(fihb.stg_avail * 2, db->file_array, LL_MDRef, db->file_array_sz,
401           fihb.stg_avail * 2);
402     db->file_array[2 * index] = llmd_finish(mdb);
403     db->file_array[2 * index + 1] = cur_mdnode;
404   } else {
405     llmd_add_string(mdb, filename);
406     llmd_add_string(mdb, sourcedir);
407     llmd_add_md(mdb, context);
408 
409     cur_mdnode = llmd_finish(mdb);
410     NEEDB(fihb.stg_avail * 2, db->file_array, LL_MDRef, db->file_array_sz,
411           fihb.stg_avail * 2);
412     db->file_array[2 * index] = cur_mdnode;
413     db->file_array[2 * index + 1] = ll_get_md_null();
414   }
415   return cur_mdnode;
416 }
417 
418 /**
419  * \brief Create a sub-program mdnode and store it in db->cur_subprogram_mdnode
420  *
421  * Don't set the function pointer field, but remember where it goes in
422  * cur_subprogram_func_ptr_offset.
423  */
424 static void
lldbg_create_subprogram_mdnode(LL_DebugInfo * db,LL_MDRef context,const char * routine,const char * mips_linkage_name,LL_MDRef def_context,int line,LL_MDRef type_mdnode,int is_local,int is_definition,int virtuality,int vindex,int unknown,int flags,int is_optimized,LL_MDRef template_param_mdnode,LL_MDRef decl_desc_mdnode,LL_MDRef lv_list_mdnode,int scope)425 lldbg_create_subprogram_mdnode(
426     LL_DebugInfo *db, LL_MDRef context, const char *routine,
427     const char *mips_linkage_name, LL_MDRef def_context, int line,
428     LL_MDRef type_mdnode, int is_local, int is_definition, int virtuality,
429     int vindex, int unknown, int flags, int is_optimized,
430     LL_MDRef template_param_mdnode, LL_MDRef decl_desc_mdnode,
431     LL_MDRef lv_list_mdnode, int scope)
432 {
433   LLMD_Builder mdb = llmd_init(db->module);
434 
435   llmd_set_class(mdb, LL_DISubprogram);
436   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_subprogram));
437 
438   if (ll_feature_debug_info_pre34(&db->module->ir))
439     llmd_add_i32(mdb, 0);
440   else
441     llmd_add_md(mdb, def_context);
442   llmd_add_md(mdb, context);
443   llmd_add_string(mdb, routine);
444   llmd_add_string(mdb, routine);
445   llmd_add_string(mdb, mips_linkage_name);
446   if (ll_feature_debug_info_pre34(&db->module->ir))
447     llmd_add_md(mdb, def_context);
448   llmd_add_i32(mdb, line);
449   llmd_add_md(mdb, type_mdnode);
450   llmd_add_i1(mdb, is_local);
451   llmd_add_i1(mdb, is_definition);
452   llmd_add_i32(mdb, virtuality);
453   llmd_add_i32(mdb, vindex);
454   llmd_add_null(mdb);
455   llmd_add_i32(mdb, flags);
456   llmd_add_i1(mdb, is_optimized);
457 
458   /* The actual function pointer is inserted here later by
459    * lldbg_set_func_ptr(). */
460   db->cur_subprogram_func_ptr_offset = llmd_get_nelems(mdb);
461   llmd_add_null(mdb);
462 
463   llmd_add_md(mdb, template_param_mdnode);
464   llmd_add_md(mdb, decl_desc_mdnode);
465   if (ll_feature_subprogram_not_in_cu(&db->module->ir))
466     llmd_add_md(mdb, db->comp_unit_mdnode);
467 
468   /* Add extra layer of indirection before 3.4. */
469   if (!ll_feature_debug_info_ver70(&db->module->ir)) {
470     if (ll_feature_debug_info_pre34(&db->module->ir))
471       llmd_add_md(mdb,
472           ll_get_md_node(db->module, LL_PlainMDNode, &lv_list_mdnode, 1));
473     else
474       llmd_add_md(mdb, lv_list_mdnode);
475   }
476   llmd_add_i32(mdb, scope);
477 
478   /* Request a distinct mdnode so that it can be updated with a function pointer
479    * later. */
480   llmd_set_distinct(mdb);
481   db->cur_subprogram_mdnode = llmd_finish(mdb);
482   ll_extend_md_node(db->module, db->llvm_dbg_sp, db->cur_subprogram_mdnode);
483 }
484 
485 void
lldbg_set_func_ptr(LL_DebugInfo * db,LL_Value * func_ptr)486 lldbg_set_func_ptr(LL_DebugInfo *db, LL_Value *func_ptr)
487 {
488   LL_MDRef mdref = ll_get_md_value(db->module, func_ptr);
489   ll_update_md_node(db->module, db->cur_subprogram_mdnode,
490                     db->cur_subprogram_func_ptr_offset, mdref);
491 }
492 
493 LL_MDRef
lldbg_subprogram(LL_DebugInfo * db)494 lldbg_subprogram(LL_DebugInfo *db)
495 {
496   LL_MDRef rv = db->cur_subprogram_mdnode;
497   db->cur_subprogram_mdnode = (LL_MDRef)0;
498   return rv;
499 }
500 
501 void
lldbg_reset_module(LL_DebugInfo * db)502 lldbg_reset_module(LL_DebugInfo *db)
503 {
504   db->cur_module_name = NULL;
505   db->cur_module_mdnode = ll_get_md_null();
506 }
507 
508 static LL_MDRef
lldbg_create_global_variable_mdnode(LL_DebugInfo * db,LL_MDRef context,const char * display_name,char * name,char * mips_linkage_name,LL_MDRef def_context,int line,LL_MDRef type_mdnode,int is_local,int is_definition,LL_Value * var_ptr,int addrspace,int flags,ISZ_T off,SPTR sptr,LL_MDRef fwd)509 lldbg_create_global_variable_mdnode(LL_DebugInfo *db, LL_MDRef context,
510                                     const char *display_name, char *name,
511                                     char *mips_linkage_name,
512                                     LL_MDRef def_context, int line,
513                                     LL_MDRef type_mdnode, int is_local,
514                                     int is_definition, LL_Value *var_ptr,
515                                     int addrspace, int flags, ISZ_T off,
516                                     SPTR sptr, LL_MDRef fwd)
517 {
518   LLMD_Builder mdb = llmd_init(db->module);
519   LL_MDRef cur_mdnode;
520 
521   llmd_set_class(mdb, LL_DIGlobalVariable);
522   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_variable));
523   llmd_add_i32(mdb, 0);
524   llmd_add_md(mdb, context);
525 #ifdef FLANG_LLVM_EXTENSIONS
526   if (ll_feature_debug_info_ver70(&db->module->ir) &&
527       !XBIT(183, 0x40000000) &&
528       (flags & DIFLAG_ARTIFICIAL))
529     display_name = ""; // Do not expose the name of compiler created variable.
530 #endif
531   llmd_add_string(mdb, display_name);
532   llmd_add_string(mdb, name);
533   llmd_add_string(mdb, mips_linkage_name);
534   llmd_add_md(mdb, def_context);
535   llmd_add_i32(mdb, line);
536   llmd_add_md(mdb, type_mdnode);
537   llmd_add_i32(mdb, is_local);
538   llmd_add_i32(mdb, is_definition);
539   if (!ll_feature_from_global_to_md(&db->module->ir))
540     llmd_add_md(mdb, ll_get_md_value(db->module, var_ptr));
541 #ifdef FLANG_LLVM_EXTENSIONS
542   if (ll_feature_debug_info_ver70(&db->module->ir))
543     llmd_add_i32(mdb, flags);
544 #endif
545   if (addrspace >= 0)
546     llmd_add_i32(mdb, addrspace);
547 
548   if (ll_feature_from_global_to_md(&db->module->ir))
549     llmd_set_distinct(mdb);
550   cur_mdnode = ll_finish_variable(mdb, fwd);
551 
552   if (ll_feature_from_global_to_md(&db->module->ir)) {
553     LL_MDRef expr_mdnode;
554     const ISZ_T off0 = ((off >> 27) == 0) ? off : 0;
555     const unsigned v = lldbg_encode_expression_arg(LL_DW_OP_int, off0);
556     const unsigned cnt = (off0 > 0) ? 2 : 0;
557     LLMD_Builder mdb2 = llmd_init(db->module);
558     llmd_set_class(mdb2, LL_DIGlobalVariableExpression);
559     llmd_add_md(mdb2, cur_mdnode);
560     /* Handle the Fortran allocatable array cases. Emit expression mdnode with a
561      * sigle argument of DW_OP_deref because of using sptr array$p instead of
562      * sptr array for debugging purpose.
563      */
564     if (ftn_array_need_debug_info(sptr)) {
565       const unsigned deref = lldbg_encode_expression_arg(LL_DW_OP_deref, 0);
566       expr_mdnode = lldbg_emit_expression_mdnode(db, 1, deref);
567     } else
568     if (ll_feature_use_5_diexpression(&db->module->ir)) {
569       const unsigned add = lldbg_encode_expression_arg(LL_DW_OP_plus_uconst, 0);
570       expr_mdnode = lldbg_emit_expression_mdnode(db, cnt, add, v);
571     } else {
572       const unsigned add = lldbg_encode_expression_arg(LL_DW_OP_plus, 0);
573       expr_mdnode = lldbg_emit_expression_mdnode(db, cnt, add, v);
574     }
575     llmd_add_md(mdb2, expr_mdnode);
576     cur_mdnode = llmd_finish(mdb2);
577   }
578 
579   ll_extend_md_node(db->module, db->llvm_dbg_gv, cur_mdnode);
580   return cur_mdnode;
581 }
582 
583 static LL_MDRef
lldbg_create_block_mdnode(LL_DebugInfo * db,LL_MDRef routine_context,int line,int column,int findex,int ID)584 lldbg_create_block_mdnode(LL_DebugInfo *db, LL_MDRef routine_context, int line,
585                           int column, int findex, int ID)
586 {
587   LLMD_Builder mdb = llmd_init(db->module);
588 
589   if (!line)
590     line = 1;
591 
592   llmd_set_class(mdb, LL_DILexicalBlock);
593   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_lexical_block));
594   if (!ll_feature_debug_info_pre34(&db->module->ir))
595     llmd_add_md(mdb, get_filedesc_mdnode(db, findex));
596   llmd_add_md(mdb, routine_context);
597   llmd_add_i32(mdb, line);
598   llmd_add_i32(mdb, column);
599   if (ll_feature_debug_info_pre34(&db->module->ir))
600     llmd_add_md(mdb, get_file_mdnode(db, findex));
601   llmd_add_i32(mdb, ID);
602 
603   return llmd_finish(mdb);
604 }
605 
606 INLINE static LL_MDRef
lldbg_create_string_type_mdnode(LL_DebugInfo * db,ISZ_T sz,DBLINT64 alignment,const char * name,int encoding)607 lldbg_create_string_type_mdnode(LL_DebugInfo *db, ISZ_T sz, DBLINT64 alignment,
608                                 const char *name, int encoding)
609 {
610   LLMD_Builder mdb = llmd_init(db->module);
611 
612   if (ll_feature_has_diextensions(&db->module->ir)) {
613     llmd_set_class(mdb, LL_DIStringType);
614   } else {
615     llmd_set_class(mdb, LL_DIBasicType_string);
616   }
617   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_string_type));
618   llmd_add_string(mdb, name);
619   llmd_add_i64(mdb, sz);
620   llmd_add_INT64(mdb, alignment);
621   if (!ll_feature_has_diextensions(&db->module->ir)) {
622     llmd_add_i32(mdb, encoding);
623   }
624   return llmd_finish(mdb);
625 }
626 
627 static LL_MDRef
lldbg_create_basic_type_mdnode(LL_DebugInfo * db,LL_MDRef context,const char * name,LL_MDRef fileref,int line,ISZ_T sz,DBLINT64 alignment,DBLINT64 offset,int flags,int dwarf_encoding)628 lldbg_create_basic_type_mdnode(LL_DebugInfo *db, LL_MDRef context,
629                                const char *name, LL_MDRef fileref, int line,
630                                ISZ_T sz, DBLINT64 alignment, DBLINT64 offset,
631                                int flags, int dwarf_encoding)
632 {
633   DBLINT64 size;
634   LLMD_Builder mdb = llmd_init(db->module);
635 
636   ISZ_2_INT64(sz, size);
637   llmd_set_class(mdb, LL_DIBasicType);
638 
639   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_base_type));
640   if (ll_feature_debug_info_pre34(&db->module->ir)) {
641     llmd_add_md(mdb, context);
642     llmd_add_string(mdb, name);
643     llmd_add_md(mdb, fileref);
644   } else {
645     llmd_add_null(mdb);
646     llmd_add_null(mdb);
647     llmd_add_string(mdb, name);
648   }
649   llmd_add_i32(mdb, line);
650   llmd_add_INT64(mdb, size);
651   llmd_add_INT64(mdb, alignment);
652   llmd_add_INT64(mdb, offset);
653   llmd_add_i32(mdb, flags);
654   llmd_add_i32(mdb, dwarf_encoding);
655 
656   return llmd_finish(mdb);
657 }
658 
659 static LL_MDRef
lldbg_create_pointer_type_mdnode(LL_DebugInfo * db,LL_MDRef context,char * name,LL_MDRef fileref,int line,ISZ_T sz,DBLINT64 alignment,DBLINT64 offset,int flags,LL_MDRef pts_to)660 lldbg_create_pointer_type_mdnode(LL_DebugInfo *db, LL_MDRef context, char *name,
661                                  LL_MDRef fileref, int line, ISZ_T sz,
662                                  DBLINT64 alignment, DBLINT64 offset, int flags,
663                                  LL_MDRef pts_to)
664 {
665   DBLINT64 size;
666   LLMD_Builder mdb = llmd_init(db->module);
667 
668   ISZ_2_INT64(sz, size);
669   llmd_set_class(mdb, LL_DIDerivedType);
670   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_pointer_type));
671 
672   if (!ll_feature_debug_info_pre34(&db->module->ir)) {
673     llmd_add_null(mdb);
674     llmd_add_null(mdb);
675     llmd_add_string(mdb, name);
676   } else {
677     llmd_add_md(mdb, context);
678     llmd_add_string(mdb, name);
679     llmd_add_md(mdb, fileref);
680   }
681   llmd_add_i32(mdb, line);
682   llmd_add_INT64(mdb, size);
683   llmd_add_INT64(mdb, alignment);
684   llmd_add_INT64(mdb, offset);
685   llmd_add_i32(mdb, flags);
686   llmd_add_md(mdb, pts_to);
687 
688   return llmd_finish(mdb);
689 }
690 
691 static LL_MDRef
lldbg_create_ftn_array_type_mdnode(LL_DebugInfo * db,LL_MDRef context,int line,ISZ_T sz,DBLINT64 alignment,LL_MDRef eleTy,LL_MDRef subscripts)692 lldbg_create_ftn_array_type_mdnode(LL_DebugInfo *db, LL_MDRef context, int line,
693                                    ISZ_T sz, DBLINT64 alignment, LL_MDRef eleTy,
694                                    LL_MDRef subscripts)
695 {
696   LLMD_Builder mdb = llmd_init(db->module);
697 
698   llmd_set_class(mdb, LL_DIFortranArrayType);
699   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_array_type));
700   llmd_add_md(mdb, context);
701   llmd_add_i32(mdb, line);
702   llmd_add_i64(mdb, sz);
703   llmd_add_INT64(mdb, alignment);
704   llmd_add_md(mdb, eleTy);
705   llmd_add_md(mdb, subscripts);
706 
707   return llmd_finish(mdb);
708 }
709 
710 /**
711    \brief Create an array type, \c DW_TAG_array_type
712    \param db
713    \param context
714    \param line       line number
715    \param sz       size of array, must be in bits
716    \param alignment  alignment of array
717    \param pts_to
718    \param subscripts
719  */
720 static LL_MDRef
lldbg_create_array_type_mdnode(LL_DebugInfo * db,LL_MDRef context,int line,ISZ_T sz,DBLINT64 alignment,LL_MDRef pts_to,LL_MDRef subscripts)721 lldbg_create_array_type_mdnode(LL_DebugInfo *db, LL_MDRef context, int line,
722                                ISZ_T sz, DBLINT64 alignment, LL_MDRef pts_to,
723                                LL_MDRef subscripts)
724 {
725   DBLINT64 size;
726   LLMD_Builder mdb = llmd_init(db->module);
727 
728   ISZ_2_INT64(sz, size);
729   llmd_set_class(mdb, LL_DICompositeType);
730   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_array_type));
731 
732   if (!ll_feature_debug_info_pre34(&db->module->ir)) {
733     llmd_add_null(mdb);
734     llmd_add_null(mdb);
735     llmd_add_string(mdb, "");
736   } else {
737     llmd_add_md(mdb, context);
738     llmd_add_string(mdb, "");
739     llmd_add_md(mdb, context);
740   }
741   llmd_add_i32(mdb, line);
742   llmd_add_INT64(mdb, size);
743   llmd_add_INT64(mdb, alignment);
744   llmd_add_i32(mdb, 0);
745   llmd_add_i32(mdb, 0);
746   llmd_add_md(mdb, pts_to);
747   llmd_add_md(mdb, subscripts);
748   llmd_add_i32(mdb, 0);
749   if (ll_feature_debug_info_pre34(&db->module->ir)) {
750     llmd_add_i32(mdb, 0);
751   } else {
752     llmd_add_null(mdb);
753     llmd_add_null(mdb);
754   }
755 
756   return llmd_finish(mdb);
757 }
758 
759 static LL_MDRef
lldbg_create_aggregate_type_mdnode(LL_DebugInfo * db,int dw_tag,LL_MDRef context,const char * name,LL_MDRef fileref,int line,ISZ_T sz,DBLINT64 alignment,int flags,LL_MDRef members,int runtime)760 lldbg_create_aggregate_type_mdnode(LL_DebugInfo *db, int dw_tag,
761                                    LL_MDRef context, const char *name,
762                                    LL_MDRef fileref, int line, ISZ_T sz,
763                                    DBLINT64 alignment, int flags, LL_MDRef members,
764                                    int runtime)
765 {
766   DBLINT64 size;
767   LLMD_Builder mdb = llmd_init(db->module);
768 
769   ISZ_2_INT64(sz, size);
770   llmd_set_class(mdb, LL_DICompositeType);
771   llmd_add_i32(mdb, make_dwtag(db, dw_tag));
772 
773   if (!ll_feature_debug_info_pre34(&db->module->ir)) {
774     llmd_add_md(mdb, fileref);
775     llmd_add_null(mdb); /* Here should be non compile unit scope */
776     llmd_add_string(mdb, name);
777     llmd_add_i32(mdb, line);
778     llmd_add_INT64(mdb, size);
779     llmd_add_INT64(mdb, alignment);
780     llmd_add_i32(mdb, 0);
781     llmd_add_i32(mdb, flags);
782     llmd_add_null(mdb); /* Derived from ? */
783     llmd_add_md(mdb, members);
784     llmd_add_i32(mdb, runtime);
785     llmd_add_null(mdb); /* Virtual table holder ? */
786     llmd_add_null(mdb);
787     llmd_add_null(mdb); /* Unique identifier ? */
788   } else {
789     llmd_add_md(mdb, context);
790     llmd_add_string(mdb, name);
791     llmd_add_md(mdb, fileref);
792     llmd_add_i32(mdb, line);
793     llmd_add_INT64(mdb, size);
794     llmd_add_INT64(mdb, alignment);
795     llmd_add_i32(mdb, 0);
796     llmd_add_i32(mdb, flags);
797     llmd_add_i32(mdb, 0);
798     llmd_add_md(mdb, members);
799     llmd_add_i32(mdb, runtime);
800     llmd_add_i32(mdb, 0);
801   }
802 
803   return llmd_finish(mdb);
804 }
805 
806 static LL_MDRef
lldbg_create_structure_type_mdnode(LL_DebugInfo * db,LL_MDRef context,const char * name,LL_MDRef fileref,int line,ISZ_T sz,DBLINT64 alignment,int flags,LL_MDRef members,int runtime)807 lldbg_create_structure_type_mdnode(LL_DebugInfo *db, LL_MDRef context,
808                                    const char *name, LL_MDRef fileref, int line,
809                                    ISZ_T sz, DBLINT64 alignment, int flags,
810                                    LL_MDRef members, int runtime)
811 {
812   return lldbg_create_aggregate_type_mdnode(db, DW_TAG_structure_type, context,
813                                             name, fileref, line, sz, alignment,
814                                             flags, members, runtime);
815 }
816 
817 static LL_MDRef
lldbg_create_union_type_mdnode(LL_DebugInfo * db,LL_MDRef context,const char * name,LL_MDRef fileref,int line,ISZ_T sz,DBLINT64 alignment,int flags,LL_MDRef members,int runtime)818 lldbg_create_union_type_mdnode(LL_DebugInfo *db, LL_MDRef context,
819                                const char *name, LL_MDRef fileref, int line,
820                                ISZ_T sz, DBLINT64 alignment, int flags,
821                                LL_MDRef members, int runtime)
822 {
823   return lldbg_create_aggregate_type_mdnode(db, DW_TAG_union_type, context,
824                                             name, fileref, line, sz, alignment,
825                                             flags, members, runtime);
826 }
827 
828 static LL_MDRef
lldbg_create_member_mdnode(LL_DebugInfo * db,LL_MDRef fileref,LL_MDRef parent_mdnode,const char * name,int line,ISZ_T sz,DBLINT64 alignment,DBLINT64 offset,int flags,LL_MDRef type_mdnode,LL_MDRef fwd)829 lldbg_create_member_mdnode(LL_DebugInfo *db, LL_MDRef fileref,
830                            LL_MDRef parent_mdnode, const char *name, int line,
831                            ISZ_T sz, DBLINT64 alignment, DBLINT64 offset, int flags,
832                            LL_MDRef type_mdnode, LL_MDRef fwd)
833 {
834   DBLINT64 size;
835   LLMD_Builder mdb = llmd_init(db->module);
836 
837   ISZ_2_INT64(sz, size);
838   llmd_set_class(mdb, LL_DIDerivedType);
839   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_member));
840   llmd_add_md(mdb, fileref);
841   if (ll_feature_debug_info_pre34(&db->module->ir)) {
842     llmd_add_string(mdb, name);
843     llmd_add_md(mdb, fileref);
844   } else {
845     llmd_add_md(mdb, parent_mdnode);
846     llmd_add_string(mdb, name);
847   }
848   llmd_add_i32(mdb, line);
849   llmd_add_INT64(mdb, size);
850   llmd_add_INT64(mdb, alignment);
851   llmd_add_INT64(mdb, offset);
852   llmd_add_i32(mdb, flags);
853   llmd_add_md(mdb, type_mdnode);
854 
855   return ll_finish_variable(mdb, fwd);
856 }
857 
858 static void
lldbg_create_aggregate_members_type(LL_DebugInfo * db,SPTR first,int findex,LL_MDRef file_mdnode,LL_MDRef members_mdnode,LL_MDRef parent_mdnode)859 lldbg_create_aggregate_members_type(LL_DebugInfo *db, SPTR first, int findex,
860                                     LL_MDRef file_mdnode,
861                                     LL_MDRef members_mdnode,
862                                     LL_MDRef parent_mdnode)
863 {
864   LL_MDRef member_mdnode, member_type_mdnode, fwd;
865   ISZ_T sz;
866   DBLINT64 align, offset;
867   SPTR element, member;
868   DTYPE elem_dtype;
869   hash_data_t val;
870   int skip_elem_num = 0;
871   bool is_desc_member = false;
872   bool contains_allocatable = false;
873   SPTR base_sptr = SPTR_NULL;
874   char* prefix = NULL;
875 
876   if (!ll_feature_debug_info_pre34(&db->module->ir))
877     file_mdnode = get_filedesc_mdnode(db, findex);
878   for (element = first; element > NOSYM; element = SYMLKG(element)) {
879     if (CCSYMG(element))
880       continue;
881     if (SCG(element) == SC_BASED && POINTERG(element)) {
882       /* member syms linked list could contain descriptor(s):
883        * case #1: array type sym "foo" followed by "foo$p", "foo$o", "foo$sd";
884        * case #2: structure type sym "zar" followed by "zar$p", "zar$td";
885        * case #3: pointer type sym "bar" followed by "bar$p".
886        */
887       base_sptr = element;
888       if (ALLOCATTRG(element) && SDSCG(element)) {
889         if (db->gbl_var_sptr) {
890           contains_allocatable = true;
891           db->need_dup_composite_type |= true;
892         }
893       } else {
894         element = SYMLKG(element);
895         assert(element > NOSYM,
896                "lldbg_create_aggregate_members_type: element not exists",
897                element, ERR_Fatal);
898         is_desc_member = true;
899         db->need_dup_composite_type = false;
900       }
901     }
902     elem_dtype = DTYPEG(element);
903     sz = lldbg_get_sizeof(element);
904     align[1] = ((alignment(elem_dtype) + 1) * 8);
905     align[0] = 0;
906     offset[1] = ((ADDRESSG(element)) * 8);
907     offset[0] = 0;
908     member_type_mdnode =
909         lldbg_emit_type(db, elem_dtype, element, findex, false, false, false);
910     if (hashmap_lookup(db->module->mdnodes_fwdvars, INT2HKEY(element), &val)) {
911       fwd = (LL_MDRef)(unsigned long)val;
912       hashmap_erase(db->module->mdnodes_fwdvars, INT2HKEY(element), NULL);
913     } else {
914       fwd = ll_get_md_null();
915     }
916     member = element;
917     if (is_desc_member) {
918       member = base_sptr;
919       is_desc_member = false;
920     }
921     if (contains_allocatable) {
922       db->need_dup_composite_type |= true;
923     }
924     if (base_sptr && SDSCG(element)) {
925       /* for case #1 and case #2, sdsc always appears as the last descriptor.
926        * skip all of the subsequent descriptors.
927        */
928       element = SDSCG(element);
929       base_sptr = SPTR_NULL;
930     }
931     member_mdnode = lldbg_create_member_mdnode(
932         db, file_mdnode, parent_mdnode, CCSYMG(member) ? "" : SYMNAME(member),
933         0, sz, align, offset, 0, member_type_mdnode, fwd);
934     ll_extend_md_node(db->module, members_mdnode, member_mdnode);
935   }
936 }
937 
938 static bool
map_sptr_to_mdnode(LL_MDRef * mdnode,LL_DebugInfo * db,int sptr)939 map_sptr_to_mdnode(LL_MDRef *mdnode, LL_DebugInfo *db, int sptr)
940 {
941   struct sptr_to_mdnode_map *map = db->sptrs_to_mdnodes;
942   if (sptr > NOSYM) {
943     for (; map != NULL; map = map->next) {
944       if (map->sptr == sptr) {
945         if (mdnode != NULL)
946           *mdnode = map->mdnode;
947         return true;
948       }
949     }
950   }
951   return false;
952 }
953 
954 /**
955    \brief Fill in extra data about a symbol
956 
957    Probes any debug symbol information that may have been saved by the front-end
958    in order to generate a good display name and proper namespace or class scope
959    for a symbol.  Falls back to the symbol table name and the compile unit's
960    outermost scope if better symbolic information cannot be found.
961  */
962 static void
get_extra_info_for_sptr(const char ** display_name,LL_MDRef * scope_mdnode,LL_MDRef * type_mdnode,LL_DebugInfo * db,int sptr)963 get_extra_info_for_sptr(const char **display_name, LL_MDRef *scope_mdnode,
964                         LL_MDRef *type_mdnode, LL_DebugInfo *db, int sptr)
965 {
966   *display_name = SYMNAME(sptr);
967   if (scope_mdnode != NULL) {
968     if (db->cur_cmnblk_mdnode != ll_get_md_null())
969       *scope_mdnode = db->cur_cmnblk_mdnode;
970     else
971     if (db->cur_subprogram_mdnode != ll_get_md_null())
972       *scope_mdnode = db->cur_subprogram_mdnode;
973     else if (db->cur_module_mdnode != ll_get_md_null() &&
974              ((STYPEG(sptr) != ST_ENTRY) ||
975               (STYPEG(sptr) == ST_ENTRY && INMODULEG(sptr))))
976       *scope_mdnode = db->cur_module_mdnode;
977     else
978       *scope_mdnode = lldbg_emit_compile_unit(db);
979   }
980 
981 }
982 
983 static LL_MDRef
lldbg_create_enumeration_type_mdnode(LL_DebugInfo * db,LL_MDRef context,char * name,LL_MDRef fileref,int line,ISZ_T sz,DBLINT64 alignment,LL_MDRef elements)984 lldbg_create_enumeration_type_mdnode(LL_DebugInfo *db, LL_MDRef context,
985                                      char *name, LL_MDRef fileref, int line,
986                                      ISZ_T sz, DBLINT64 alignment,
987                                      LL_MDRef elements)
988 {
989   return lldbg_create_aggregate_type_mdnode(
990       db, DW_TAG_enumeration_type, context, name, fileref, line, sz, alignment,
991       /*flags=*/0, elements, /*runtime=*/0);
992 }
993 
994 static LL_MDRef
lldbg_create_enumerator_mdnode(LL_DebugInfo * db,int sptr,DBLINT64 value)995 lldbg_create_enumerator_mdnode(LL_DebugInfo *db, int sptr, DBLINT64 value)
996 {
997   LLMD_Builder mdb = llmd_init(db->module);
998   const char *name;
999 
1000   llmd_set_class(mdb, LL_DIEnumerator);
1001   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_enumerator));
1002   /* TODO(pmk): this fails to find pretty names for enumeration members */
1003   get_extra_info_for_sptr(&name, NULL /* scope */, NULL /* type */, db, sptr);
1004   llmd_add_string(mdb, name);
1005   llmd_add_INT64(mdb, value);
1006 
1007   return llmd_finish(mdb);
1008 }
1009 
1010 /**
1011    Create an mdnode that is a list of enumerators, starting from element in the
1012    symbol table.
1013  */
1014 static LL_MDRef
lldbg_create_enumerator_list(LL_DebugInfo * db,int element)1015 lldbg_create_enumerator_list(LL_DebugInfo *db, int element)
1016 {
1017   LLMD_Builder mdb = llmd_init(db->module);
1018 
1019   /* empty enum: required for version  3.7, works for all */
1020   if (element <= NOSYM) {
1021     llmd_add_md(mdb, ll_get_md_null());
1022   } else
1023     while (element > NOSYM) {
1024       DBLINT64 value;
1025       value[0] = CONVAL1G(element);
1026       value[1] = CONVAL2G(element);
1027       llmd_add_md(mdb, lldbg_create_enumerator_mdnode(db, element, value));
1028       element = SYMLKG(element);
1029     }
1030 
1031   /* The symbol table linked list has the enumerators in backwards order. */
1032   llmd_reverse(mdb);
1033 
1034   return llmd_finish(mdb);
1035 }
1036 
1037 static LL_MDRef
lldbg_create_vector_type_mdnode(LL_DebugInfo * db,LL_MDRef context,ISZ_T sz,DBLINT64 alignment,LL_MDRef type,LL_MDRef subscripts)1038 lldbg_create_vector_type_mdnode(LL_DebugInfo *db, LL_MDRef context, ISZ_T sz,
1039                                 DBLINT64 alignment, LL_MDRef type,
1040                                 LL_MDRef subscripts)
1041 {
1042   DBLINT64 size;
1043   LLMD_Builder mdb = llmd_init(db->module);
1044 
1045   ISZ_2_INT64(sz, size);
1046   llmd_set_class(mdb, LL_DICompositeType);
1047   /* vector types are marked as arrays in LLVM debug information. */
1048   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_array_type));
1049   llmd_add_null(mdb);
1050   llmd_add_null(mdb);
1051   llmd_add_string(mdb, "");
1052   llmd_add_i32(mdb, 0);
1053   llmd_add_INT64(mdb, size);
1054   llmd_add_INT64(mdb, alignment);
1055   llmd_add_i32(mdb, 0);
1056   llmd_add_i32(mdb, 0);
1057   llmd_add_md(mdb, type);
1058   llmd_add_md(mdb, subscripts);
1059   llmd_add_i32(mdb, 0);
1060   llmd_add_null(mdb);
1061   llmd_add_null(mdb);
1062 
1063   return llmd_finish(mdb);
1064 }
1065 
1066 static LL_MDRef
lldbg_create_derived_type_mdnode(LL_DebugInfo * db,int dw_tag,LL_MDRef context,char * name,LL_MDRef fileref,int line,ISZ_T sz,DBLINT64 alignment,DBLINT64 offset,int flags,LL_MDRef derived)1067 lldbg_create_derived_type_mdnode(LL_DebugInfo *db, int dw_tag, LL_MDRef context,
1068                                  char *name, LL_MDRef fileref, int line,
1069                                  ISZ_T sz, DBLINT64 alignment, DBLINT64 offset,
1070                                  int flags, LL_MDRef derived)
1071 {
1072   DBLINT64 size;
1073   LLMD_Builder mdb = llmd_init(db->module);
1074 
1075   ISZ_2_INT64(sz, size);
1076   llmd_set_class(mdb, LL_DIDerivedType);
1077   llmd_add_i32(mdb, make_dwtag(db, dw_tag));
1078   llmd_add_md(mdb, context);
1079   if (ll_feature_debug_info_pre34(&db->module->ir)) {
1080     llmd_add_string(mdb, name);
1081     llmd_add_md(mdb, fileref);
1082   } else {
1083     llmd_add_md(mdb, fileref);
1084     llmd_add_string(mdb, name);
1085   }
1086   llmd_add_i32(mdb, line);
1087   llmd_add_INT64(mdb, size);
1088   llmd_add_INT64(mdb, alignment);
1089   llmd_add_INT64(mdb, offset);
1090   llmd_add_i32(mdb, flags);
1091   llmd_add_md(mdb, derived);
1092 
1093   return llmd_finish(mdb);
1094 }
1095 
1096 static LL_MDRef
lldbg_create_subroutine_type_mdnode(LL_DebugInfo * db,LL_MDRef context,LL_MDRef fileref,LL_MDRef params,const int cc)1097 lldbg_create_subroutine_type_mdnode(LL_DebugInfo *db, LL_MDRef context,
1098                                     LL_MDRef fileref, LL_MDRef params,
1099                                     const int cc)
1100 {
1101   LLMD_Builder mdb = llmd_init(db->module);
1102 
1103   llmd_set_class(mdb, LL_DISubroutineType);
1104   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_subroutine_type));
1105   llmd_add_i32(mdb, 0);
1106   llmd_add_null(mdb);
1107   llmd_add_string(mdb, "");
1108   llmd_add_i32(mdb, 0);
1109   llmd_add_i64(mdb, 0);
1110   llmd_add_i64(mdb, 0);
1111   llmd_add_i64(mdb, 0);
1112   llmd_add_i32(mdb, 0);
1113   llmd_add_null(mdb);
1114   llmd_add_md(mdb, params);
1115   llmd_add_i32(mdb, 0);
1116   llmd_add_null(mdb);
1117   llmd_add_null(mdb);
1118   if (ll_feature_subprogram_not_in_cu(&db->module->ir))
1119     llmd_add_i32(mdb, cc);
1120 
1121   return llmd_finish(mdb);
1122 }
1123 
1124 static LL_MDRef
emit_deref_expression_mdnode(LL_DebugInfo * db)1125 emit_deref_expression_mdnode(LL_DebugInfo *db)
1126 {
1127   const unsigned deref = lldbg_encode_expression_arg(LL_DW_OP_deref, 0);
1128   return lldbg_emit_expression_mdnode(db, 1, deref);
1129 }
1130 
1131 static LL_MDRef
lldbg_create_ftn_subrange_mdnode(LL_DebugInfo * db,ISZ_T clb,LL_MDRef lbv,ISZ_T cub,LL_MDRef ubv)1132 lldbg_create_ftn_subrange_mdnode(LL_DebugInfo *db, ISZ_T clb, LL_MDRef lbv,
1133                                  ISZ_T cub, LL_MDRef ubv)
1134 {
1135   LLMD_Builder mdb = llmd_init(db->module);
1136 
1137   llmd_set_class(mdb, LL_DIFortranSubrange);
1138   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_subrange_type));
1139 
1140   if (LL_MDREF_IS_NULL(lbv) && LL_MDREF_IS_NULL(ubv)) {
1141     llmd_add_i64(mdb, clb);
1142     llmd_add_i64(mdb, cub);
1143     llmd_add_null(mdb);
1144     llmd_add_null(mdb);
1145     llmd_add_null(mdb);
1146     llmd_add_null(mdb);
1147   } else if (LL_MDREF_IS_NULL(lbv)) {
1148     llmd_add_i64(mdb, clb);
1149     llmd_add_i64(mdb, 0);
1150     llmd_add_null(mdb);
1151     llmd_add_null(mdb);
1152     llmd_add_md(mdb, ubv);
1153     llmd_add_md(mdb, emit_deref_expression_mdnode(db));
1154   } else if (LL_MDREF_IS_NULL(ubv)) {
1155     llmd_add_i64(mdb, 0);
1156     llmd_add_i64(mdb, cub);
1157     llmd_add_md(mdb, lbv);
1158     llmd_add_md(mdb, emit_deref_expression_mdnode(db));
1159     llmd_add_null(mdb);
1160     llmd_add_null(mdb);
1161   } else {
1162     llmd_add_i64(mdb, 0);
1163     llmd_add_i64(mdb, 0);
1164     llmd_add_md(mdb, lbv);
1165     llmd_add_md(mdb, emit_deref_expression_mdnode(db));
1166     llmd_add_md(mdb, ubv);
1167     llmd_add_md(mdb, emit_deref_expression_mdnode(db));
1168   }
1169   return llmd_finish(mdb);
1170 }
1171 
1172 #define F90_DESC_SIZE 10 /* num of fields of Struct F90_Desc */
1173 #define F90_DESCDIM_SIZE 6 /* num of fields of Struct F90_DescDim */
1174 /* Create subrange mdnode based on array descriptor */
1175 static LL_MDRef
lldbg_create_ftn_subrange_via_sdsc(LL_DebugInfo * db,int findex,SPTR sptr,int rank)1176 lldbg_create_ftn_subrange_via_sdsc(LL_DebugInfo *db, int findex, SPTR sptr,
1177                                    int rank)
1178 {
1179   LL_MDRef array_desc_mdnode, lbnd_expr_mdnode, ubnd_expr_mdnode;
1180 
1181   const int gbl_offset = (db->gbl_var_sptr && db->need_dup_composite_type &&
1182                          ADDRESSG(db->gbl_var_sptr) > 0 ) ?
1183                          ADDRESSG(db->gbl_var_sptr) : 0;
1184   /* array descrpitor object's offset within an aggregate object needs to be
1185    * counted in, if exists. */
1186   const int orig_offset = (SCG(SDSCG(sptr)) == SC_CMBLK ||
1187                            STYPEG(SDSCG(sptr)) == ST_MEMBER) ?
1188                            ADDRESSG(SDSCG(sptr)) : 0;
1189   const int lbnd_offset = gbl_offset + orig_offset +
1190                           8 * (F90_DESC_SIZE + rank * F90_DESCDIM_SIZE);
1191   const int extent_offset = lbnd_offset + 8;
1192   const unsigned v1 = lldbg_encode_expression_arg(LL_DW_OP_int, lbnd_offset);
1193   const unsigned v2 = lldbg_encode_expression_arg(LL_DW_OP_int, extent_offset);
1194   const unsigned one = lldbg_encode_expression_arg(LL_DW_OP_int, 1);
1195   const unsigned add = lldbg_encode_expression_arg(LL_DW_OP_plus_uconst, 0);
1196   const unsigned dup = lldbg_encode_expression_arg(LL_DW_OP_dup, 0);
1197   const unsigned deref = lldbg_encode_expression_arg(LL_DW_OP_deref, 0);
1198   const unsigned swap = lldbg_encode_expression_arg(LL_DW_OP_swap, 0);
1199   const unsigned plus = lldbg_encode_expression_arg(LL_DW_OP_plus, 0);
1200   const unsigned minus = lldbg_encode_expression_arg(LL_DW_OP_minus, 0);
1201   const unsigned constu = lldbg_encode_expression_arg(LL_DW_OP_constu, 0);
1202 
1203   array_desc_mdnode = (db->need_dup_composite_type) ?
1204                       db->gbl_obj_mdnode :
1205                       ll_get_global_debug(db->module, SDSCG(sptr));
1206   if (LL_MDREF_IS_NULL(array_desc_mdnode)) {
1207     array_desc_mdnode = lldbg_fwd_local_variable(db, SDSCG(sptr), findex, false);
1208     if (db->need_dup_composite_type) {
1209       db->gbl_obj_mdnode = array_desc_mdnode;
1210       hashmap_erase(db->module->mdnodes_fwdvars, INT2HKEY(SDSCG(sptr)), NULL);
1211     }
1212   }
1213   lbnd_expr_mdnode = lldbg_emit_expression_mdnode(db, 3, add, v1, deref);
1214   ubnd_expr_mdnode =
1215       lldbg_emit_expression_mdnode(db, 12, dup, add, v1, deref, swap, add, v2,
1216                                    deref, plus, constu, one, minus);
1217 
1218   LLMD_Builder mdb = llmd_init(db->module);
1219   llmd_set_class(mdb, LL_DIFortranSubrange);
1220   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_subrange_type));
1221   llmd_add_i64(mdb, 0);
1222   llmd_add_i64(mdb, 0);
1223   llmd_add_md(mdb, array_desc_mdnode);
1224   llmd_add_md(mdb, lbnd_expr_mdnode);
1225   llmd_add_md(mdb, array_desc_mdnode);
1226   llmd_add_md(mdb, ubnd_expr_mdnode);
1227   return llmd_finish(mdb);
1228 }
1229 
1230 static LL_MDRef
lldbg_create_subrange_mdnode(LL_DebugInfo * db,ISZ_T lb,ISZ_T ub)1231 lldbg_create_subrange_mdnode(LL_DebugInfo *db, ISZ_T lb, ISZ_T ub)
1232 {
1233   DBLINT64 count, low, high;
1234   DBLINT64 one;
1235   LLMD_Builder mdb = llmd_init(db->module);
1236 
1237   ISZ_2_INT64(lb, low);
1238   ISZ_2_INT64(ub, high);
1239   llmd_set_class(mdb, LL_DISubRange);
1240   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_subrange_type));
1241   llmd_add_INT64(mdb, low);
1242   if (ll_feature_debug_info_pre34(&db->module->ir)) {
1243     llmd_add_INT64(mdb, high);
1244   } else {
1245     /* Count for LLVM 3.4+ */
1246     ISZ_2_INT64(1, one);
1247     sub64(high, low, count);
1248     /* In 3.7 syntax empty subrange is denoted with count: -1 */
1249     if (ll_feature_debug_info_subrange_needs_count(&db->module->ir)) {
1250       if (!count[0] && !count[1])
1251         ISZ_2_INT64(-1, count);
1252     }
1253     add64(one, count, count);
1254     llmd_add_INT64(mdb, count);
1255   }
1256 
1257   return llmd_finish(mdb);
1258 }
1259 
1260 static LL_MDRef
lldbg_create_unspecified_mdnode(LL_DebugInfo * db,int dw_tag)1261 lldbg_create_unspecified_mdnode(LL_DebugInfo *db, int dw_tag)
1262 {
1263   LLMD_Builder mdb = llmd_init(db->module);
1264 
1265   llmd_add_i32(mdb, make_dwtag(db, dw_tag));
1266 
1267   return llmd_finish(mdb);
1268 }
1269 
1270 static LL_MDRef
lldbg_create_unspecified_type_mdnode(LL_DebugInfo * db)1271 lldbg_create_unspecified_type_mdnode(LL_DebugInfo *db)
1272 {
1273   return ll_get_md_null();
1274 }
1275 
1276 static LL_MDRef
lldbg_create_unspecified_parameters_mdnode(LL_DebugInfo * db)1277 lldbg_create_unspecified_parameters_mdnode(LL_DebugInfo *db)
1278 {
1279   return lldbg_create_unspecified_mdnode(db, DW_TAG_unspecified_parameters);
1280 }
1281 
1282 LL_MDRef
lldbg_emit_empty_expression_mdnode(LL_DebugInfo * db)1283 lldbg_emit_empty_expression_mdnode(LL_DebugInfo *db)
1284 {
1285   LLMD_Builder mdb = llmd_init(db->module);
1286   llmd_set_class(mdb, LL_DIExpression);
1287   return llmd_finish(mdb);
1288 }
1289 
1290 int
lldbg_encode_expression_arg(LL_DW_OP_t op,int value)1291 lldbg_encode_expression_arg(LL_DW_OP_t op, int value)
1292 {
1293   DEBUG_ASSERT(ll_dw_op_ok(op), "invalid op");
1294   return (op == LL_DW_OP_int) ? (value << 1) : ((op << 1) | 1);
1295 }
1296 
1297 LL_MDRef
lldbg_emit_expression_mdnode(LL_DebugInfo * db,unsigned cnt,...)1298 lldbg_emit_expression_mdnode(LL_DebugInfo *db, unsigned cnt, ...)
1299 {
1300   unsigned i;
1301   va_list ap;
1302   LLMD_Builder mdb = llmd_init(db->module);
1303   // enforce an arbitrary limit for now to catch bugs
1304   DEBUG_ASSERT(cnt < 20, "DIExpression unsupported");
1305   llmd_set_class(mdb, LL_DIExpression);
1306   va_start(ap, cnt);
1307   for (i = 0; i != cnt; ++i) {
1308     int arg = va_arg(ap, int);
1309     llmd_add_i32(mdb, arg);
1310   }
1311   va_end(ap);
1312   return llmd_finish(mdb);
1313 }
1314 
1315 static LL_MDRef
lldbg_create_local_variable_mdnode(LL_DebugInfo * db,int dw_tag,LL_MDRef context,char * name,LL_MDRef fileref,int line,int argnum,LL_MDRef type_mdnode,int flags,LL_MDRef fwd)1316 lldbg_create_local_variable_mdnode(LL_DebugInfo *db, int dw_tag,
1317                                    LL_MDRef context, char *name,
1318                                    LL_MDRef fileref, int line, int argnum,
1319                                    LL_MDRef type_mdnode, int flags,
1320                                    LL_MDRef fwd)
1321 {
1322   LLMD_Builder mdb = llmd_init(db->module);
1323 
1324   llmd_set_class(mdb, LL_DILocalVariable);
1325   if (!ll_feature_debug_info_ver38(&db->module->ir))
1326     llmd_add_i32(mdb, make_dwtag(db, dw_tag));
1327   llmd_add_md(mdb, context);
1328   if (flags & DIFLAG_ARTIFICIAL)
1329     llmd_add_string(mdb, ""); // Do not expose the name of compiler created variable.
1330   else
1331     llmd_add_string(mdb, name);
1332   if (!ll_feature_dbg_local_variable_embeds_argnum(&db->module->ir))
1333     llmd_add_i32(mdb, argnum);
1334   llmd_add_md(mdb, fileref);
1335   if (ll_feature_dbg_local_variable_embeds_argnum(&db->module->ir))
1336     llmd_add_i32(mdb, line | (argnum << 24));
1337   else
1338     llmd_add_i32(mdb, line);
1339   llmd_add_md(mdb, type_mdnode);
1340   llmd_add_i32(mdb, flags);
1341   llmd_add_i32(mdb, 0);
1342   if (fwd)
1343     return ll_finish_variable(mdb, fwd);
1344   return llmd_finish(mdb);
1345 }
1346 
1347 static LL_MDRef
lldbg_create_location_mdnode(LL_DebugInfo * db,int line,int column,LL_MDRef scope)1348 lldbg_create_location_mdnode(LL_DebugInfo *db, int line, int column,
1349                              LL_MDRef scope)
1350 {
1351   LLMD_Builder mdb = llmd_init(db->module);
1352 
1353   llmd_set_class(mdb, LL_DILocation);
1354   llmd_add_i32(mdb, line);
1355   llmd_add_i32(mdb, column);
1356   llmd_add_md(mdb, scope);
1357   llmd_add_null(mdb); /* InlinedAt */
1358   return llmd_finish(mdb);
1359 }
1360 
1361 void
lldbg_reset_dtype_array(LL_DebugInfo * db,const int off)1362 lldbg_reset_dtype_array(LL_DebugInfo *db, const int off)
1363 {
1364   BZERO(db->dtype_array + off, LL_MDRef, db->dtype_array_sz - off);
1365 }
1366 
1367 void
lldbg_update_arrays(LL_DebugInfo * db,int lastDType,int newSz)1368 lldbg_update_arrays(LL_DebugInfo *db, int lastDType, int newSz)
1369 {
1370   const int fromSz = db->dtype_array_sz;
1371   assert(db, "Debug info not enabled", 0, ERR_Fatal);
1372   NEED(newSz, db->dtype_array, LL_MDRef, db->dtype_array_sz, newSz);
1373   if (newSz > fromSz) {
1374     BZERO(db->dtype_array + lastDType, LL_MDRef, newSz - lastDType);
1375   }
1376 }
1377 
1378 void
lldbg_init_arrays(LL_DebugInfo * db)1379 lldbg_init_arrays(LL_DebugInfo *db)
1380 {
1381   const int new_size = stb.dt.stg_avail + 2000;
1382   assert(db, "Debug info not enabled", 0, ERR_Fatal);
1383   NEED(new_size, db->dtype_array, LL_MDRef, db->dtype_array_sz, new_size);
1384   if (db->module->ir.is_nvvm && (db->dtype_array_sz > DT_MAX)) {
1385     BZERO(&db->dtype_array[DT_MAX], LL_MDRef, db->dtype_array_sz - DT_MAX);
1386   }
1387 }
1388 
1389 void
lldbg_init(LL_Module * module)1390 lldbg_init(LL_Module *module)
1391 {
1392   LL_DebugInfo *db;
1393   int sptr;
1394 
1395   if (module->debug_info) {
1396     const int newSz = stb.dt.stg_avail + 2000;
1397     db = module->debug_info;
1398     NEEDB(newSz, db->dtype_array, LL_MDRef, db->dtype_array_sz, newSz);
1399     return;
1400   }
1401 
1402   db = (LL_DebugInfo *)calloc(1, sizeof(LL_DebugInfo));
1403   module->debug_info = db;
1404 
1405   /* calloc initializes most struct members to the right initial value. */
1406   db->module = module;
1407   db->blk_idx = -1;
1408   db->cur_module_name = NULL;
1409   db->import_entity_list = NULL;
1410   db->need_dup_composite_type = false;
1411   db->gbl_var_sptr = SPTR_NULL;
1412   db->gbl_obj_mdnode = ll_get_md_null();
1413   db->gbl_obj_exp_mdnode = ll_get_md_null();
1414 
1415   if (!ll_feature_debug_info_pre34(&db->module->ir)) {
1416     const int mdVers = ll_feature_versioned_dw_tag(&module->ir)
1417                            ? 1
1418                            : module->ir.debug_info_version;
1419     const unsigned dwarfVers = ll_feature_dwarf_version(&module->ir);
1420     if (!module->named_mdnodes[MD_llvm_module_flags]) {
1421       ll_extend_named_md_node(
1422           module, MD_llvm_module_flags,
1423           lldbg_create_module_flag_mdnode(db, 2, "Dwarf Version", dwarfVers));
1424       ll_extend_named_md_node(
1425           module, MD_llvm_module_flags,
1426           lldbg_create_module_flag_mdnode(db, 2, "Debug Info Version", mdVers));
1427     }
1428   }
1429 
1430   sprintf(db->producer, "%s %s %s%s", version.product, version.lang,
1431           version.vsn, version.bld);
1432   NEW(db->file_array, LL_MDRef, fihb.stg_avail * 2);
1433   BZERO(db->file_array, LL_MDRef, fihb.stg_avail * 2);
1434   db->file_array_sz = fihb.stg_avail * 2;
1435   NEW(db->dtype_array, LL_MDRef, stb.dt.stg_avail + 2000);
1436   BZERO(db->dtype_array, LL_MDRef, stb.dt.stg_avail + 2000);
1437   db->dtype_array_sz = stb.dt.stg_avail + 2000;
1438   for (sptr = gbl.entries; sptr > NOSYM; sptr = SYMLKG(sptr)) {
1439     db->routine_count++;
1440   }
1441   if (db->routine_count)
1442     db->llvm_dbg_lv_array =
1443         (LL_MDRef *)calloc(db->routine_count, sizeof(LL_MDRef));
1444   else
1445     db->llvm_dbg_lv_array = NULL;
1446 }
1447 
1448 void
lldbg_free(LL_DebugInfo * db)1449 lldbg_free(LL_DebugInfo *db)
1450 {
1451   if (!db)
1452     return;
1453   FREE(db->file_array);
1454   FREE(db->dtype_array);
1455   db->file_array_sz = 0;
1456   db->dtype_array_sz = 0;
1457   while (db->sptrs_to_mdnodes != NULL) {
1458     struct sptr_to_mdnode_map *nsp = db->sptrs_to_mdnodes;
1459     db->sptrs_to_mdnodes = nsp->next;
1460     free(nsp);
1461   }
1462   while (db->import_entity_list != NULL) {
1463     import_entity *node = db->import_entity_list;
1464     db->import_entity_list = node->next;
1465     free(node);
1466   }
1467   free(db);
1468 }
1469 
1470 /**
1471    \brief Double any backslash characters in \p name
1472    \param name   A filename
1473 
1474    Precondition: \p name must be allocated on the heap, as it may be
1475    deallocated.
1476  */
1477 static char *
double_backslash(char * name)1478 double_backslash(char *name)
1479 {
1480   int len;
1481   char *new_name, *psrc, *pdst;
1482   int bs_count;
1483 
1484   psrc = name;
1485   bs_count = 0;
1486   len = 1;
1487   while (*psrc != '\0') {
1488     if (*psrc == '\\')
1489       bs_count++;
1490     len++;
1491     psrc++;
1492   }
1493   if (!bs_count)
1494     return name;
1495   NEW(new_name, char, len + bs_count);
1496   psrc = name;
1497   pdst = new_name;
1498   while (*psrc != '\0') {
1499     if (*psrc == '\\') {
1500       *pdst++ = '\\';
1501     }
1502     *pdst++ = *psrc++;
1503   }
1504   *pdst = '\0';
1505   FREE(name);
1506 
1507   return new_name;
1508 }
1509 
1510 /**
1511    \brief Get the filename associated with file index, \p findex.
1512    \param findex  The file's index
1513    \return a heap allocated string; caller must deallocate.
1514  */
1515 static char *
get_filename(int findex)1516 get_filename(int findex)
1517 {
1518   char *fullpath;
1519   const char *dirname = FIH_DIRNAME(findex);
1520   const char *filename = FIH_FILENAME(findex);
1521   const int dirnameLen = dirname ? strlen(dirname) : 0;
1522   const int filenameLen = filename ? strlen(filename) : 0;
1523   const char *dir = dirname ? dirname : "";
1524   const char *file = filename ? filename : "";
1525 #if defined(TARGET_WIN)
1526   const char *sep = "\\";
1527 #else
1528   const char *sep = "/";
1529 #endif
1530   const bool addSep = (dirnameLen > 0) && (dirname[dirnameLen - 1] != *sep);
1531   const int allocLen = dirnameLen + filenameLen + 1 + (addSep ? 1 : 0);
1532 
1533   NEW(fullpath, char, allocLen);
1534   snprintf(fullpath, allocLen, "%s%s%s", dir, (addSep ? sep : ""), file);
1535   return double_backslash(fullpath);
1536 }
1537 
1538 #define MAX_FNAME 1024
1539 
1540 static char *
get_currentdir(void)1541 get_currentdir(void)
1542 {
1543   char *cwd = (char *)malloc(PATH_MAX);
1544   getcwd(cwd, PATH_MAX);
1545   return cwd;
1546 }
1547 
1548 LL_MDRef
lldbg_emit_compile_unit(LL_DebugInfo * db)1549 lldbg_emit_compile_unit(LL_DebugInfo *db)
1550 {
1551   int lang_tag;
1552   assert(db, "Debug info not enabled", 0, ERR_Fatal);
1553   if (LL_MDREF_IS_NULL(db->comp_unit_mdnode)) {
1554     lang_tag = DW_LANG_Fortran90;
1555     db->comp_unit_mdnode = lldbg_create_compile_unit_mdnode(
1556         db, lang_tag, get_filename(1), get_currentdir(), db->producer, 1, 0, "",
1557         0, &db->llvm_dbg_enum, &db->llvm_dbg_retained, &db->llvm_dbg_sp,
1558         &db->llvm_dbg_gv, &db->llvm_dbg_imported);
1559   }
1560   return db->comp_unit_mdnode;
1561 }
1562 
1563 static LL_MDRef
lldbg_emit_file(LL_DebugInfo * db,int findex)1564 lldbg_emit_file(LL_DebugInfo *db, int findex)
1565 {
1566   LL_MDRef cu_mnode;
1567 
1568   cu_mnode = lldbg_emit_compile_unit(db);
1569   if (LL_MDREF_IS_NULL(get_file_mdnode(db, findex))) {
1570     cu_mnode = ll_get_md_null();
1571     lldbg_create_file_mdnode(db, get_filename(findex), get_currentdir(),
1572                              cu_mnode, findex);
1573   }
1574   return get_file_mdnode(db, findex);
1575 }
1576 
1577 static LL_MDRef
lldbg_emit_parameter_list(LL_DebugInfo * db,DTYPE dtype,DTYPE ret_dtype,SPTR sptr,int findex)1578 lldbg_emit_parameter_list(LL_DebugInfo *db, DTYPE dtype, DTYPE ret_dtype,
1579                           SPTR sptr, int findex)
1580 {
1581   LLMD_Builder mdb = llmd_init(db->module);
1582   LL_MDRef parameter_mdnode, retval_mdnode;
1583   int params, param_dtype, num_args, param_sptr;
1584   DTYPE call_dtype = dtype;
1585   int dpdsc, paramct, i;
1586   SPTR fval;
1587   int is_reference;
1588 
1589   assert(db, "Debug info not enabled", 0, ERR_Fatal);
1590 
1591   while (DTY(call_dtype) == TY_ARRAY || DTY(call_dtype) == TY_PTR)
1592     call_dtype = DTySeqTyElement(call_dtype);
1593 
1594   dpdsc = DPDSCG(sptr);
1595   paramct = PARAMCTG(sptr);
1596   fval = FVALG(sptr);
1597 
1598   if (ret_dtype) {
1599 #ifdef CUDA_DEVICE
1600     if (CUDAG(sptr) & CUDA_DEVICE)
1601       retval_mdnode =
1602           lldbg_emit_modified_type(db, ret_dtype, SPTR_NULL, findex);
1603     else
1604 #endif
1605       retval_mdnode =
1606           lldbg_emit_type(db, ret_dtype, SPTR_NULL, findex, true, false, true);
1607   } else {
1608     if (ll_feature_debug_info_pre34(&db->module->ir))
1609       retval_mdnode = ll_get_md_null();
1610     else
1611       retval_mdnode = lldbg_create_unspecified_type_mdnode(db);
1612   }
1613 
1614   llmd_add_md(mdb, retval_mdnode);
1615 
1616   /* do the argument list;
1617    * kernel arguments are either typed value arguments, or global pointer
1618    * arguments */
1619 
1620   /* do the return value, if it appears in the argument list */
1621   num_args = 0;
1622   if (fval && SCG(fval) == SC_DUMMY) {
1623     is_reference =
1624         ((SCG(fval) == SC_DUMMY) && HOMEDG(fval) && !PASSBYVALG(fval));
1625     parameter_mdnode = lldbg_emit_type(db, DTYPEG(fval), fval, findex,
1626                                        is_reference, false, true);
1627     llmd_add_md(mdb, parameter_mdnode);
1628     ++num_args;
1629   }
1630   for (i = 0; i < paramct; i++) {
1631     SPTR param_sptr = GetParamSptr(dpdsc, i);
1632     if (param_sptr == fval)
1633       continue;
1634     is_reference = ((SCG(param_sptr) == SC_DUMMY) && HOMEDG(param_sptr) &&
1635                     !PASSBYVALG(param_sptr));
1636     parameter_mdnode = lldbg_emit_type(db, DTYPEG(param_sptr), param_sptr,
1637                                        findex, is_reference, false, true);
1638     llmd_add_md(mdb, parameter_mdnode);
1639     ++num_args;
1640   }
1641 
1642   if (num_args == 0 && ll_feature_debug_info_pre34(&db->module->ir)) {
1643     parameter_mdnode = lldbg_create_unspecified_parameters_mdnode(db);
1644     llmd_add_md(mdb, parameter_mdnode);
1645   }
1646   return llmd_finish(mdb);
1647 }
1648 
1649 INLINE static LL_MDRef
lldbg_emit_subroutine_type(LL_DebugInfo * db,SPTR sptr,DTYPE ret_dtype,int findex,LL_MDRef file_mdnode)1650 lldbg_emit_subroutine_type(LL_DebugInfo *db, SPTR sptr, DTYPE ret_dtype,
1651                            int findex, LL_MDRef file_mdnode)
1652 {
1653   LL_MDRef subroutine_type_mdnode;
1654   int cc = 0;
1655   DTYPE dtype = DTYPEG(sptr);
1656   LL_MDRef parameters_mdnode =
1657       lldbg_emit_parameter_list(db, dtype, ret_dtype, sptr, findex);
1658   cc = (gbl.rutype == RU_PROG) ? 2 : 0;
1659   subroutine_type_mdnode = lldbg_create_subroutine_type_mdnode(
1660       db, ll_get_md_null(), file_mdnode, parameters_mdnode, cc);
1661   return subroutine_type_mdnode;
1662 }
1663 
1664 static LL_MDRef
lldbg_emit_outlined_subroutine(LL_DebugInfo * db,int sptr,int ret_dtype,int findex,LL_MDRef file_mdnode)1665 lldbg_emit_outlined_subroutine(LL_DebugInfo *db, int sptr, int ret_dtype,
1666                                int findex, LL_MDRef file_mdnode)
1667 {
1668   LL_MDRef subroutine_type_mdnode;
1669   int cc = 0;
1670   LL_MDRef parameters_mdnode = lldbg_create_outlined_parameters_node(db);
1671   cc = (gbl.rutype == RU_PROG) ? 2 : 0;
1672   subroutine_type_mdnode = lldbg_create_subroutine_type_mdnode(
1673       db, ll_get_md_null(), file_mdnode, parameters_mdnode, cc);
1674   return subroutine_type_mdnode;
1675 }
1676 
1677 static void
lldbg_reserve_lexical_block(LL_DebugInfo * db,int sptr,int lineno,int findex)1678 lldbg_reserve_lexical_block(LL_DebugInfo *db, int sptr, int lineno, int findex)
1679 {
1680   int endline, startline;
1681 
1682   endline = ENDLINEG(sptr);
1683   startline = lineno;
1684   if (endline < startline)
1685     endline = startline;
1686   NEEDB((db->blk_idx + 1), db->blk_tab, BLKINFO, db->blk_tab_size,
1687         (db->blk_tab_size + 64));
1688   db->blk_tab[db->blk_idx].mdnode = ll_get_md_null();
1689   db->blk_tab[db->blk_idx].sptr = sptr;
1690   db->blk_tab[db->blk_idx].startline = startline;
1691   db->blk_tab[db->blk_idx].endline = endline;
1692   db->blk_tab[db->blk_idx].line_mdnodes = NULL;
1693   db->blk_idx++;
1694 }
1695 
1696 static BLKINFO *
lldbg_limit_lexical_blocks(LL_DebugInfo * db,int startline)1697 lldbg_limit_lexical_blocks(LL_DebugInfo *db, int startline)
1698 {
1699   int i;
1700   BLKINFO *parent_blk;
1701 
1702   for (i = 0; i < db->blk_idx; i++)
1703     db->blk_tab[i].keep = 0;
1704   parent_blk = NULL;
1705   for (i = 0; i < db->blk_idx; i++) {
1706     if (db->blk_tab[i].startline <= startline &&
1707         db->blk_tab[i].endline > startline) {
1708       /* We have found a candidate, is it the best ? */
1709       if (parent_blk == NULL) {
1710         parent_blk = &db->blk_tab[i];
1711       } else if (parent_blk->startline <= db->blk_tab[i].startline ||
1712                  parent_blk->endline >= db->blk_tab[i].endline) {
1713         parent_blk->keep = 0;
1714         parent_blk = &db->blk_tab[i];
1715       }
1716       parent_blk->keep = 1;
1717     }
1718   }
1719   if (parent_blk == NULL) {
1720     for (i = 0; i < db->blk_idx; i++)
1721       db->blk_tab[i].keep = 1;
1722     return NULL;
1723   }
1724 
1725   for (i = 0; i < db->blk_idx; i++) {
1726     if (!db->blk_tab[i].keep &&
1727         db->blk_tab[i].startline >= parent_blk->startline &&
1728         db->blk_tab[i].endline <= parent_blk->endline)
1729       db->blk_tab[i].keep = 1;
1730   }
1731   return parent_blk;
1732 }
1733 
1734 static void
lldbg_assign_lexical_block(LL_DebugInfo * db,int idx,int findex,bool targetNVVM)1735 lldbg_assign_lexical_block(LL_DebugInfo *db, int idx, int findex,
1736                            bool targetNVVM)
1737 {
1738   static int ID = 0;
1739   int endline, startline;
1740   BLKINFO *parent_blk;
1741   LL_MDRef parent_blk_mdnode;
1742   int i;
1743   int lineno = 0, column = 0;
1744 
1745   startline = db->blk_tab[idx].startline;
1746   endline = db->blk_tab[idx].endline;
1747   parent_blk = NULL;
1748   for (i = 0; i < db->blk_idx; i++) {
1749     if (i != idx) {
1750       if (db->blk_tab[i].keep && db->blk_tab[i].startline <= startline &&
1751           db->blk_tab[i].endline >= endline && db->blk_tab[i].mdnode) {
1752         /* We have found a candidate, is it the best ? */
1753         if (parent_blk == NULL)
1754           parent_blk = &db->blk_tab[i];
1755         else if ((parent_blk->startline <= db->blk_tab[i].startline) ||
1756                  (parent_blk->endline >= db->blk_tab[i].endline))
1757           parent_blk = &db->blk_tab[i];
1758       }
1759     }
1760   }
1761   if (parent_blk != NULL) {
1762     parent_blk_mdnode = parent_blk->mdnode;
1763     assert(parent_blk_mdnode, "Parent of a DILexicalBlock must exist",
1764            parent_blk_mdnode, ERR_Severe);
1765   } else
1766     parent_blk_mdnode = db->cur_subprogram_mdnode;
1767   db->blk_tab[idx].mdnode = lldbg_create_block_mdnode(
1768       db, parent_blk_mdnode, startline, 1, findex, ID++);
1769   db->blk_tab[idx].line_mdnodes =
1770       (LL_MDRef *)calloc((endline - startline + 1), sizeof(LL_MDRef));
1771   db->blk_tab[idx].null_loc =
1772       lldbg_create_location_mdnode(db, lineno, column, db->blk_tab[idx].mdnode);
1773 }
1774 
1775 static void
lldbg_emit_lexical_block(LL_DebugInfo * db,int sptr,int lineno,int findex,bool targetNVVM)1776 lldbg_emit_lexical_block(LL_DebugInfo *db, int sptr, int lineno, int findex,
1777                          bool targetNVVM)
1778 {
1779   static int ID = 0;
1780   LL_MDRef null_loc_mdnode;
1781   int endline, startline;
1782   BLKINFO *parent_blk;
1783   LL_MDRef parent_blk_mdnode;
1784   int i;
1785 
1786   endline = ENDLINEG(sptr);
1787   startline = lineno;
1788   if (endline < startline)
1789     endline = startline;
1790   parent_blk = NULL;
1791   for (i = 0; i < db->blk_idx; i++) {
1792     if (db->blk_tab[i].startline <= startline &&
1793         db->blk_tab[i].endline >= endline) {
1794       /* We have found a candidate, is it the best ? */
1795       if (parent_blk == NULL)
1796         parent_blk = &db->blk_tab[i];
1797       else if (parent_blk->startline <= db->blk_tab[i].startline ||
1798                parent_blk->endline >= db->blk_tab[i].endline)
1799         parent_blk = &db->blk_tab[i];
1800     }
1801   }
1802   if (parent_blk != NULL)
1803     parent_blk_mdnode = parent_blk->mdnode;
1804   else
1805     parent_blk_mdnode = db->cur_subprogram_mdnode;
1806   NEEDB((db->blk_idx + 1), db->blk_tab, BLKINFO, db->blk_tab_size,
1807         (db->blk_tab_size + 64));
1808   db->blk_tab[db->blk_idx].mdnode =
1809       lldbg_create_block_mdnode(db, parent_blk_mdnode, lineno, 1, findex, ID++);
1810   db->blk_tab[db->blk_idx].sptr = sptr;
1811   db->blk_tab[db->blk_idx].startline = startline;
1812   db->blk_tab[db->blk_idx].endline = endline;
1813   db->blk_tab[db->blk_idx].keep = 1;
1814   db->blk_tab[db->blk_idx].line_mdnodes =
1815       (LL_MDRef *)calloc((endline - startline + 1), sizeof(LL_MDRef));
1816     null_loc_mdnode =
1817         lldbg_create_location_mdnode(db, 0, 0, db->blk_tab[db->blk_idx].mdnode);
1818   db->blk_tab[db->blk_idx].null_loc = null_loc_mdnode;
1819   db->blk_idx++;
1820 }
1821 
1822 static void
lldbg_emit_lexical_blocks(LL_DebugInfo * db,int sptr,int findex,bool targetNVVM)1823 lldbg_emit_lexical_blocks(LL_DebugInfo *db, int sptr, int findex,
1824                           bool targetNVVM)
1825 {
1826   int encl_block;
1827   int blk_sptr;
1828   int idx;
1829   int lineno;
1830 
1831   for (idx = 0; idx < db->blk_idx; idx++) {
1832     if (db->blk_tab[idx].line_mdnodes) {
1833       free(db->blk_tab[idx].line_mdnodes);
1834       db->blk_tab[idx].line_mdnodes = NULL;
1835     }
1836   }
1837   db->blk_idx = 0;
1838   lineno = FUNCLINEG(sptr);
1839   lldbg_emit_lexical_block(db, sptr, lineno, findex, targetNVVM);
1840   db->cur_blk = db->blk_tab[0];
1841 
1842   /* An extraordinary amount of the total compilation time (19% on 510.parest
1843    * with the DEV compiler on a Tuleta) is spent for C++ compilations in the
1844    * following loop nest, which passes over most of the symbol table in search
1845    * of ST_BLOCK entries whose enclosing entries match any of the ones named by
1846    * db->blk_tab[].sptr so that they can be passed in order, without duplicates,
1847    * to lldbg_emit_lexical_block().
1848    *
1849    * So we use the original algorithm only for Fortran and C, which don't
1850    * exhibit the problem and whose symbol table re-use on a subprogram basis
1851    * wouldn't allow the code below to work anyway.
1852    */
1853   blk_sptr = sptr + 1;
1854   for (; blk_sptr < stb.stg_avail; blk_sptr++) {
1855     if (STYPEG(blk_sptr) == ST_BLOCK) {
1856       /*
1857        * check to see if it is enclosed by one of the prior blocks
1858        * entered
1859        */
1860       encl_block = ENCLFUNCG(blk_sptr);
1861       while (true) {
1862         /*
1863          * It may be the case that the owner of the block is
1864          * a fake block.  For example, a parallel region creates
1865          * a block just to ensure that the scoping is correct;
1866          * any lexical block in the parallel region is owned
1867          * by the fake block.
1868          *
1869          * Just check the owner -- if it's fake, look at its
1870          * owner, etc.
1871          */
1872         if (encl_block == 0 || STYPEG(encl_block) != ST_BLOCK ||
1873             ENDLABG(encl_block))
1874           break;
1875         encl_block = ENCLFUNCG(encl_block);
1876       }
1877       for (idx = 0; idx < db->blk_idx; idx++) {
1878         if (db->blk_tab[idx].sptr == encl_block) {
1879           lldbg_emit_lexical_block(db, blk_sptr, STARTLINEG(blk_sptr), findex,
1880                                    targetNVVM);
1881           break;
1882         }
1883       }
1884     }
1885   }
1886 }
1887 
1888 static void
lldbg_reserve_lexical_blocks(LL_DebugInfo * db,int sptr,int findex)1889 lldbg_reserve_lexical_blocks(LL_DebugInfo *db, int sptr, int findex)
1890 {
1891   int encl_block;
1892   int blk_sptr;
1893   int idx;
1894 
1895   for (idx = 0; idx < db->blk_idx; idx++) {
1896     if (db->blk_tab[idx].line_mdnodes) {
1897       free(db->blk_tab[idx].line_mdnodes);
1898       db->blk_tab[idx].line_mdnodes = NULL;
1899     }
1900   }
1901   db->blk_idx = 0;
1902   lldbg_reserve_lexical_block(db, sptr, FUNCLINEG(sptr), findex);
1903   db->cur_blk = db->blk_tab[0];
1904   blk_sptr = sptr + 1;
1905   for (; blk_sptr < stb.stg_avail; blk_sptr++) {
1906     if (STYPEG(blk_sptr) == ST_BLOCK) {
1907       /*
1908        * check to see if it is enclosed by one of the prior blocks
1909        * entered
1910        */
1911       encl_block = ENCLFUNCG(blk_sptr);
1912       while (true) {
1913         /*
1914          * It may be the case that the owner of the block is
1915          * a fake block.  For example, a parallel region creates
1916          * a block just to ensure that the scoping is correct;
1917          * any lexical block in the parallel region is owned
1918          * by the fake block.
1919          *
1920          * Just check the owner -- if it's fake, look at its
1921          * owner, etc.
1922          */
1923         if (encl_block == 0 || STYPEG(encl_block) != ST_BLOCK ||
1924             ENDLABG(encl_block))
1925           break;
1926         encl_block = ENCLFUNCG(encl_block);
1927       }
1928       for (idx = 0; idx < db->blk_idx; idx++) {
1929         if (db->blk_tab[idx].sptr == encl_block) {
1930           lldbg_reserve_lexical_block(db, blk_sptr, STARTLINEG(blk_sptr),
1931                                       findex);
1932           break;
1933         }
1934       }
1935     }
1936   }
1937 }
1938 
1939 static void
lldbg_assign_lexical_blocks(LL_DebugInfo * db,int findex,BLKINFO * parent_blk,bool targetNVVM)1940 lldbg_assign_lexical_blocks(LL_DebugInfo *db, int findex, BLKINFO *parent_blk,
1941                             bool targetNVVM)
1942 {
1943   int idx;
1944   if (parent_blk == NULL) {
1945     for (idx = 0; idx < db->blk_idx; idx++)
1946       lldbg_assign_lexical_block(db, idx, findex, targetNVVM);
1947   } else {
1948     for (idx = 0; idx < db->blk_idx; idx++)
1949       if (db->blk_tab[idx].keep)
1950         lldbg_assign_lexical_block(db, idx, findex, targetNVVM);
1951     for (idx = 0; idx < db->blk_idx; idx++)
1952       if (!db->blk_tab[idx].keep)
1953         db->blk_tab[idx].mdnode = parent_blk->mdnode;
1954   }
1955 }
1956 
1957 /**
1958    \brief Construct the flag set that corresponds with LLVM metadata
1959  */
1960 INLINE static int
set_disubprogram_flags(int sptr)1961 set_disubprogram_flags(int sptr)
1962 {
1963   return (PUREG(sptr) ? DIFLAG_PURE : 0) |
1964          (CCSYMG(sptr) ? DIFLAG_ARTIFICIAL : 0) |
1965          ((gbl.rutype == RU_PROG) ? DIFLAG_ISMAINPGM : 0);
1966 }
1967 
1968 void
lldbg_emit_outlined_subprogram(LL_DebugInfo * db,int sptr,int findex,const char * func_name,int startlineno,bool targetNVVM)1969 lldbg_emit_outlined_subprogram(LL_DebugInfo *db, int sptr, int findex,
1970                                const char *func_name, int startlineno,
1971                                bool targetNVVM)
1972 {
1973   LL_MDRef file_mdnode;
1974   LL_MDRef type_mdnode;
1975   LL_MDRef lv_list_mdnode;
1976   const char *mips_linkage_name = "";
1977   int virtuality = 0;
1978   int vindex = 0;
1979   int unknown = 0;
1980   int flags = 0;
1981   int is_optimized = 0;
1982   int sc = SCG(sptr);
1983   int is_def;
1984   int lineno;
1985   BLKINFO *parent_blk;
1986 
1987   assert(db, "Debug info not enabled", 0, ERR_Fatal);
1988   file_mdnode = lldbg_emit_file(db, findex);
1989   type_mdnode = lldbg_emit_outlined_subroutine(
1990       db, sptr, DTyReturnType(DTYPEG(sptr)), findex, file_mdnode);
1991   if (ll_feature_has_diextensions(&db->module->ir))
1992     flags = set_disubprogram_flags(sptr);
1993   db->cur_line_mdnode = ll_get_md_null();
1994   lv_list_mdnode = ll_create_flexible_md_node(db->module);
1995   if (db->routine_idx >= db->routine_count)
1996     db->routine_count = db->routine_idx + 1;
1997   db->llvm_dbg_lv_array = (LL_MDRef *)realloc(
1998       db->llvm_dbg_lv_array, sizeof(LL_MDRef) * db->routine_count);
1999   db->llvm_dbg_lv_array[db->routine_idx++] = lv_list_mdnode;
2000 
2001   lldbg_reserve_lexical_blocks(db, sptr, findex);
2002   parent_blk = lldbg_limit_lexical_blocks(db, startlineno);
2003 
2004   if (parent_blk == NULL)
2005     lineno = startlineno;
2006   else
2007     lineno = parent_blk->startline;
2008   mips_linkage_name = func_name;
2009   is_def = DEFDG(sptr);
2010   is_def |= (STYPEG(sptr) == ST_ENTRY);
2011   if (ll_feature_debug_info_pre34(&db->module->ir))
2012     lldbg_create_subprogram_mdnode(
2013         db, file_mdnode, func_name, mips_linkage_name, file_mdnode, lineno,
2014         type_mdnode, (sc == SC_STATIC), is_def, virtuality, vindex, unknown,
2015         flags, is_optimized, ll_get_md_null(), ll_get_md_null(), lv_list_mdnode,
2016         lineno);
2017   else if (ll_feature_debug_info_ver38(&(db)->module->ir))
2018     lldbg_create_subprogram_mdnode(
2019         db, lldbg_emit_compile_unit(db), func_name, mips_linkage_name,
2020         get_filedesc_mdnode(db, findex), lineno, type_mdnode, (sc == SC_STATIC),
2021         is_def, virtuality, vindex, unknown, flags, is_optimized,
2022         ll_get_md_null(), ll_get_md_null(), lv_list_mdnode, lineno);
2023   else
2024     lldbg_create_subprogram_mdnode(
2025         db, file_mdnode, func_name, mips_linkage_name,
2026         get_filedesc_mdnode(db, findex), lineno, type_mdnode, (sc == SC_STATIC),
2027         is_def, virtuality, vindex, unknown, flags, is_optimized,
2028         ll_get_md_null(), ll_get_md_null(), lv_list_mdnode, lineno);
2029   db->cur_subprogram_null_loc =
2030       lldbg_create_location_mdnode(db, lineno, 1, db->cur_subprogram_mdnode);
2031   db->cur_subprogram_lineno = lineno;
2032   db->param_idx = 0;
2033   memset(db->param_stack, 0, sizeof(PARAMINFO) * PARAM_STACK_SIZE);
2034   lldbg_assign_lexical_blocks(db, findex, parent_blk, targetNVVM);
2035 }
2036 
2037 LL_MDRef
lldbg_emit_module_mdnode(LL_DebugInfo * db,int sptr)2038 lldbg_emit_module_mdnode(LL_DebugInfo *db, int sptr)
2039 {
2040   LL_MDRef module_mdnode;
2041 
2042   lldbg_emit_file(db, 1);
2043   module_mdnode =
2044       ll_get_module_debug(db->module->module_debug_map, SYMNAME(sptr));
2045   if (!LL_MDREF_IS_NULL(module_mdnode))
2046     return module_mdnode;
2047   return lldbg_create_module_mdnode(db, ll_get_md_null(), SYMNAME(sptr),
2048                                     lldbg_emit_compile_unit(db), 1);
2049 }
2050 
2051 void
lldbg_emit_subprogram(LL_DebugInfo * db,SPTR sptr,DTYPE ret_dtype,int findex,bool targetNVVM)2052 lldbg_emit_subprogram(LL_DebugInfo *db, SPTR sptr, DTYPE ret_dtype, int findex,
2053                       bool targetNVVM)
2054 {
2055   LL_MDRef file_mdnode;
2056   LL_MDRef type_mdnode;
2057   LL_MDRef lv_list_mdnode;
2058   LL_MDRef context_mdnode;
2059   LL_MDRef scope;
2060   char *mips_linkage_name = "";
2061   const char *func_name;
2062   int virtuality = 0;
2063   int vindex = 0;
2064   int unknown = 0;
2065   int flags = 0;
2066   int is_optimized = 0;
2067   int sc = SCG(sptr);
2068   int is_def;
2069   int lineno;
2070   hash_data_t scopeData;
2071 
2072   assert(db, "Debug info not enabled", 0, ERR_Fatal);
2073   file_mdnode = lldbg_emit_file(db, findex);
2074   /* For `DI' syntax use file desctipion */
2075   if (ll_feature_debug_info_need_file_descriptions(&db->module->ir))
2076     file_mdnode = get_filedesc_mdnode(db, findex);
2077   type_mdnode =
2078       lldbg_emit_subroutine_type(db, sptr, ret_dtype, findex, file_mdnode);
2079   db->cur_line_mdnode = ll_get_md_null();
2080   lv_list_mdnode = ll_create_flexible_md_node(db->module);
2081   if (db->routine_idx >= db->routine_count)
2082     db->routine_count = db->routine_idx + 1;
2083   db->llvm_dbg_lv_array = (LL_MDRef *)realloc(
2084       db->llvm_dbg_lv_array, sizeof(LL_MDRef) * db->routine_count);
2085   db->llvm_dbg_lv_array[db->routine_idx++] = lv_list_mdnode;
2086 
2087   lineno = FUNCLINEG(sptr);
2088   if (ll_feature_has_diextensions(&db->module->ir))
2089     flags = set_disubprogram_flags(sptr);
2090   get_extra_info_for_sptr(&func_name, &context_mdnode,
2091                           NULL /* pmk: &type_mdnode */, db, sptr);
2092   is_def = DEFDG(sptr);
2093   is_def |= (STYPEG(sptr) == ST_ENTRY);
2094   if (INMODULEG(sptr) && ll_feature_create_dimodule(&db->module->ir)) {
2095     char *modNm = SYMNAME(INMODULEG(sptr));
2096     LL_MDRef fileMD = get_filedesc_mdnode(db, findex);
2097     LL_MDRef unused = ll_get_md_null();
2098     context_mdnode = lldbg_emit_module_mdnode(db, INMODULEG(sptr));
2099   }
2100   scope = ll_feature_debug_info_pre34(&db->module->ir)
2101               ? file_mdnode
2102               : get_filedesc_mdnode(db, findex);
2103   if (CONTAINEDG(sptr) && db->subroutine_mdnodes &&
2104       hashmap_lookup(db->subroutine_mdnodes, INT2HKEY(gbl.outersub),
2105                      &scopeData)) {
2106     context_mdnode = (LL_MDRef)(unsigned long)scopeData;
2107   }
2108   lldbg_create_subprogram_mdnode(db, context_mdnode, func_name,
2109                                  mips_linkage_name, scope, lineno, type_mdnode,
2110                                  (sc == SC_STATIC), is_def, virtuality, vindex,
2111                                  unknown, flags, is_optimized, ll_get_md_null(),
2112                                  ll_get_md_null(), lv_list_mdnode, lineno);
2113   if (!db->subroutine_mdnodes)
2114     db->subroutine_mdnodes = hashmap_alloc(hash_functions_direct);
2115   scopeData = (hash_data_t)(unsigned long)db->cur_subprogram_mdnode;
2116   hashmap_replace(db->subroutine_mdnodes, INT2HKEY(sptr), &scopeData);
2117   while (db->import_entity_list) {
2118     /* There are pending entities to be imported into this func */
2119     lldbg_emit_imported_entity(db, db->import_entity_list->entity, sptr,
2120                                db->import_entity_list->entity_type);
2121     db->import_entity_list = db->import_entity_list->next;
2122   }
2123     db->cur_subprogram_null_loc =
2124         lldbg_create_location_mdnode(db, 0, 0, db->cur_subprogram_mdnode);
2125   db->param_idx = 0;
2126   memset(db->param_stack, 0, sizeof(PARAMINFO) * PARAM_STACK_SIZE);
2127   lldbg_emit_lexical_blocks(db, sptr, findex, targetNVVM);
2128 }
2129 
2130 /**
2131    \brief Is \p fn a function, but not the current function?
2132    \param fn  The symbol to test
2133 
2134    Helper to hide the differences between compilers.
2135  */
2136 INLINE static bool
getLexBlock_notCurrentFunc(const int fn)2137 getLexBlock_notCurrentFunc(const int fn)
2138 {
2139   return (STYPEG(fn) == ST_ENTRY) && (fn != gbl.currsub);
2140 }
2141 
2142 LL_MDRef
lldbg_get_var_line(LL_DebugInfo * db,int sptr)2143 lldbg_get_var_line(LL_DebugInfo *db, int sptr)
2144 {
2145   int idx;
2146   const int blk_sptr = ENCLFUNCG(sptr);
2147 
2148   assert(db, "Debug info not enabled", 0, ERR_Fatal);
2149   if (blk_sptr == 0) {
2150     assert(db->blk_idx > 0,
2151            "get_var_line(): empty blk_tab when "
2152            "processing sptr",
2153            sptr, ERR_Fatal);
2154     return db->blk_tab[0].null_loc;
2155   }
2156   switch (STYPEG(blk_sptr)) {
2157   case ST_BLOCK:
2158     if (flg.smp) {
2159       const int fn = ENCLFUNCG(blk_sptr);
2160       if (fn && getLexBlock_notCurrentFunc(fn))
2161         return db->blk_tab[0].null_loc;
2162     }
2163     for (idx = db->blk_idx - 1; idx >= 0; --idx) {
2164       if (db->blk_tab[idx].sptr == blk_sptr)
2165         return db->blk_tab[idx].null_loc;
2166     }
2167     break;
2168   case ST_PROC:
2169     return db->cur_subprogram_null_loc;
2170   case ST_ENTRY:
2171     return db->cur_subprogram_null_loc;
2172   default:
2173     assert(false, "get_var_line(): line not found for sptr", sptr, ERR_Fatal);
2174     break;
2175   }
2176   return ll_get_md_null();
2177 }
2178 
2179 static BLKINFO *
get_lexical_block_info(LL_DebugInfo * db,int sptr,bool unchecked)2180 get_lexical_block_info(LL_DebugInfo *db, int sptr, bool unchecked)
2181 {
2182   int idx;
2183   const int blk_sptr = ENCLFUNCG(sptr);
2184 
2185   if (SCG(sptr) == SC_DUMMY) {
2186     /* Assume the initial block of the function if this is a dummy */
2187     return &db->blk_tab[0];
2188   } else if (blk_sptr == 0) {
2189     assert(db->blk_idx > 0,
2190            "get_lexical_block_info(): empty blk_tab when "
2191            "processing sptr",
2192            sptr, ERR_Fatal);
2193     return &db->blk_tab[0];
2194   } else if (flg.smp && STYPEG(blk_sptr) == ST_BLOCK) {
2195     const int fn = ENCLFUNCG(blk_sptr);
2196     if (fn && getLexBlock_notCurrentFunc(fn))
2197       return &db->blk_tab[0];
2198   }
2199 
2200   for (idx = db->blk_idx - 1; idx >= 0; --idx) {
2201     if (db->blk_tab[idx].sptr == blk_sptr)
2202       return &db->blk_tab[idx];
2203   }
2204 
2205   if (unchecked)
2206     return &db->cur_blk;
2207 
2208   assert(false, "get_lexical_block_info(): block not found for sptr", sptr,
2209          ERR_Fatal);
2210   return NULL;
2211 }
2212 
2213 void
lldbg_emit_line(LL_DebugInfo * db,int lineno)2214 lldbg_emit_line(LL_DebugInfo *db, int lineno)
2215 {
2216   static int last_line = 0;
2217   int idx = 0;
2218   int startline, endline;
2219   int i, j;
2220 
2221   assert(db, "Debug info not enabled", 0, ERR_Fatal);
2222   if (db->blk_idx < 0) {
2223     /* lldbg_emit_subprogram has not been called for this function
2224      * Don't do anything for NOW, might need to be revisited later
2225      */
2226     db->cur_line_mdnode = ll_get_md_null();
2227     return;
2228   }
2229   if (last_line != lineno) {
2230     j = db->blk_idx - 1;
2231     while (j >= 0) {
2232       if (db->blk_tab[j].keep) {
2233         idx = j;
2234         startline = db->blk_tab[idx].startline;
2235         endline = db->blk_tab[idx].endline;
2236 
2237         if (lineno >= startline && lineno <= endline)
2238           break;
2239       }
2240       j--;
2241     }
2242     if (!db->blk_tab[idx].keep) {
2243       db->cur_line_mdnode = ll_get_md_null();
2244       return;
2245     }
2246     startline = db->blk_tab[idx].startline;
2247     endline = db->blk_tab[idx].endline;
2248     if (lineno >= startline) {
2249       if (lineno > endline) {
2250         db->blk_tab[idx].line_mdnodes =
2251             (LL_MDRef *)realloc(db->blk_tab[idx].line_mdnodes,
2252                                 sizeof(LL_MDRef) * (lineno - startline + 1));
2253         for (i = lineno; i > endline; i--)
2254           db->blk_tab[idx].line_mdnodes[i - startline] = ll_get_md_null();
2255         endline = lineno;
2256         db->blk_tab[idx].endline = endline;
2257       }
2258       db->cur_line_mdnode = db->blk_tab[idx].line_mdnodes[lineno - startline];
2259       if (LL_MDREF_IS_NULL(db->cur_line_mdnode)) {
2260         db->cur_line_mdnode = lldbg_create_location_mdnode(
2261             db, lineno, 1, db->blk_tab[idx].mdnode);
2262         db->blk_tab[idx].line_mdnodes[lineno - startline] = db->cur_line_mdnode;
2263       }
2264     } else {
2265       db->cur_line_mdnode =
2266           lldbg_create_location_mdnode(db, lineno, 1, db->blk_tab[idx].mdnode);
2267     }
2268     last_line = lineno;
2269   }
2270 }
2271 
2272 LL_MDRef
lldbg_get_line(LL_DebugInfo * db)2273 lldbg_get_line(LL_DebugInfo *db)
2274 {
2275   assert(db, "Debug info not enabled", 0, ERR_Fatal);
2276   return db->cur_line_mdnode;
2277 }
2278 
2279 LL_MDRef
lldbg_cons_line(LL_DebugInfo * db)2280 lldbg_cons_line(LL_DebugInfo *db)
2281 {
2282   if (LL_MDREF_IS_NULL(db->cur_line_mdnode))
2283     return db->cur_subprogram_null_loc;
2284   return lldbg_get_line(db);
2285 }
2286 
2287 static int
dwarf_encoding(DTYPE dtype)2288 dwarf_encoding(DTYPE dtype)
2289 {
2290   TY_KIND ty = DTY(dtype);
2291   switch (ty) {
2292   case TY_PTR:
2293     return DW_ATE_address;
2294   case TY_BINT:
2295   case TY_SINT:
2296   case TY_INT:
2297   case TY_INT8:
2298     return DW_ATE_signed;
2299   case TY_WORD:
2300   case TY_DWORD:
2301     return DW_ATE_unsigned;
2302   case TY_BLOG:
2303   case TY_SLOG:
2304   case TY_LOG:
2305   case TY_LOG8:
2306     return DW_ATE_boolean;
2307   case TY_REAL:
2308   case TY_DBLE:
2309   case TY_QUAD:
2310     return DW_ATE_float;
2311   case TY_CMPLX:
2312   case TY_DCMPLX:
2313     return DW_ATE_complex_float;
2314   default:
2315     break;
2316   }
2317   return (TY_ISUNSIGNED(ty)) ? DW_ATE_unsigned : DW_ATE_signed;
2318 }
2319 
2320 static LL_MDRef
lldbg_create_outlined_parameters_node(LL_DebugInfo * db)2321 lldbg_create_outlined_parameters_node(LL_DebugInfo *db)
2322 {
2323   db->cur_parameters_mdnode = ll_create_flexible_md_node(db->module);
2324   return db->cur_parameters_mdnode;
2325 }
2326 
2327 void
lldbg_emit_outlined_parameter_list(LL_DebugInfo * db,int findex,DTYPE * param_dtypes,int num_args)2328 lldbg_emit_outlined_parameter_list(LL_DebugInfo *db, int findex,
2329                                    DTYPE *param_dtypes, int num_args)
2330 {
2331   LL_MDRef parameters_mdnode, parameter_mdnode;
2332   int i;
2333 
2334   assert(db, "Debug info not enabled", 0, ERR_Fatal);
2335   parameters_mdnode = db->cur_parameters_mdnode;
2336 
2337   if (ll_feature_debug_info_pre34(&db->module->ir))
2338     ll_extend_md_node(db->module, parameters_mdnode, ll_get_md_null());
2339   else if (!ll_feature_debug_info_ver38(&(db)->module->ir))
2340     ll_extend_md_node(db->module, parameters_mdnode,
2341                       lldbg_create_unspecified_type_mdnode(db));
2342 
2343   for (i = 0; i < num_args; i++) {
2344     if (param_dtypes[i]) {
2345       parameter_mdnode = lldbg_emit_type(db, param_dtypes[i], SPTR_NULL, findex,
2346                                          false, true, true);
2347       ll_extend_md_node(db->module, parameters_mdnode, parameter_mdnode);
2348     }
2349   }
2350 
2351   if (num_args == 0) {
2352     parameter_mdnode = lldbg_create_unspecified_parameters_mdnode(db);
2353     ll_extend_md_node(db->module, parameters_mdnode, parameter_mdnode);
2354   }
2355 }
2356 
2357 static LL_MDRef
lldbg_emit_modified_type(LL_DebugInfo * db,DTYPE dtype,SPTR sptr,int findex)2358 lldbg_emit_modified_type(LL_DebugInfo *db, DTYPE dtype, SPTR sptr, int findex)
2359 {
2360   const TY_KIND dty = DTY(DTYPEG(sptr));
2361   return lldbg_emit_type(db, (dty == TY_ARRAY ? DT_CPTR : dtype), sptr, findex,
2362                          false, false, false);
2363 }
2364 
2365 static LL_MDRef
lldbg_emit_accel_cmblk_type(LL_DebugInfo * db,int cmblk,int findex)2366 lldbg_emit_accel_cmblk_type(LL_DebugInfo *db, int cmblk, int findex)
2367 {
2368   LL_MDRef cu_mdnode, file_mdnode, type_mdnode;
2369   LL_MDRef members_mdnode;
2370   ISZ_T sz;
2371   DBLINT64 align, offset;
2372 
2373   cu_mdnode = lldbg_emit_compile_unit(db);
2374   file_mdnode = lldbg_emit_file(db, findex);
2375   members_mdnode = ll_create_flexible_md_node(db->module);
2376   sz = (SIZEG(cmblk) * 8);
2377   align[1] = 64;
2378   align[0] = 0;
2379   type_mdnode = lldbg_create_aggregate_type_mdnode(
2380       db, DW_TAG_class_type, cu_mdnode, "", file_mdnode, 0, sz, align, 0,
2381       members_mdnode, 0);
2382   lldbg_create_aggregate_members_type(db, CMEMFG(cmblk), findex, file_mdnode,
2383                                       members_mdnode, type_mdnode);
2384   return type_mdnode;
2385 }
2386 
2387 static LL_MDRef
lldbg_emit_accel_function_static_type(LL_DebugInfo * db,SPTR first,int findex)2388 lldbg_emit_accel_function_static_type(LL_DebugInfo *db, SPTR first, int findex)
2389 {
2390   LL_MDRef cu_mdnode, file_mdnode, type_mdnode;
2391   LL_MDRef members_mdnode;
2392   DBLINT64 align;
2393   int sptr;
2394   ISZ_T total_size = 0;
2395 
2396   cu_mdnode = lldbg_emit_compile_unit(db);
2397   file_mdnode = lldbg_emit_file(db, findex);
2398   members_mdnode = ll_create_flexible_md_node(db->module);
2399   sptr = first;
2400   while (sptr > NOSYM) {
2401     total_size += ZSIZEOF(DTYPEG(sptr));
2402     sptr = SYMLKG(sptr);
2403   }
2404   total_size *= 8;
2405   align[1] = 64;
2406   align[0] = 0;
2407   type_mdnode = lldbg_create_aggregate_type_mdnode(
2408       db, DW_TAG_class_type, cu_mdnode, "", file_mdnode, 0, total_size, align,
2409       0, members_mdnode, 0);
2410   lldbg_create_aggregate_members_type(db, first, findex, file_mdnode,
2411                                       members_mdnode, type_mdnode);
2412   return type_mdnode;
2413 }
2414 
2415 INLINE static void
dtype_array_check_set(LL_DebugInfo * db,unsigned at,LL_MDRef md)2416 dtype_array_check_set(LL_DebugInfo *db, unsigned at, LL_MDRef md)
2417 {
2418   if (at < db->dtype_array_sz)
2419     db->dtype_array[at] = md;
2420 }
2421 
2422 INLINE static bool
is_assumed_char(DTYPE dtype)2423 is_assumed_char(DTYPE dtype)
2424 {
2425   return (DTY(dtype) == TY_CHAR) && (dtype == DT_ASSCHAR);
2426 }
2427 
2428 INLINE static char *
next_assumed_len_character_name(void)2429 next_assumed_len_character_name(void)
2430 {
2431   static unsigned counter;
2432   static char name[32];
2433   snprintf(name, 32, "character(*)!%u", ++counter);
2434   return name;
2435 }
2436 
2437 INLINE static LL_MDRef
lldbg_create_assumed_len_string_type_mdnode(LL_DebugInfo * db,SPTR sptr,int findex)2438 lldbg_create_assumed_len_string_type_mdnode(LL_DebugInfo *db, SPTR sptr,
2439                                             int findex)
2440 {
2441   SPTR lenArg;
2442   int paramPos;
2443   LL_MDRef mdLen;
2444   LL_MDRef mdLenExp;
2445   LLMD_Builder mdb = llmd_init(db->module);
2446   const char *name = next_assumed_len_character_name();
2447   const long long size = 32;
2448   const long long alignment = 0;
2449   const int encoding = 0;
2450 
2451   cg_fetch_clen_parampos(&lenArg, &paramPos, sptr);
2452   if ((paramPos != -1) && db->cur_subprogram_mdnode) {
2453     mdLen = lldbg_emit_param_variable(db, lenArg, findex, paramPos, true);
2454     mdLenExp = lldbg_emit_empty_expression_mdnode(db);
2455   } else {
2456     mdLen = mdLenExp = ll_get_md_null();
2457   }
2458   llmd_set_class(mdb, LL_DIStringType);
2459   llmd_add_i32(mdb, make_dwtag(db, DW_TAG_string_type));
2460   llmd_add_string(mdb, name);
2461   llmd_add_i64(mdb, size);
2462   llmd_add_i64(mdb, alignment);
2463   llmd_add_i32(mdb, encoding);
2464   llmd_add_md(mdb, mdLen);
2465   llmd_add_md(mdb, mdLenExp);
2466   return llmd_finish(mdb);
2467 }
2468 
2469 static LL_MDRef
lldbg_fwd_local_variable(LL_DebugInfo * db,int sptr,int findex,int emit_dummy_as_local)2470 lldbg_fwd_local_variable(LL_DebugInfo *db, int sptr, int findex,
2471                          int emit_dummy_as_local)
2472 {
2473   LL_MDRef mdnode;
2474   hash_data_t data;
2475   if (hashmap_lookup(db->module->mdnodes_fwdvars, INT2HKEY(sptr), &data)) {
2476     mdnode = (LL_MDRef)(unsigned long)data;
2477   } else {
2478     const unsigned id = ll_reserve_md_node(db->module);
2479     mdnode = LL_MDREF_INITIALIZER(MDRef_Node, id);
2480     hashmap_insert(db->module->mdnodes_fwdvars, INT2HKEY(sptr),
2481                    (hash_data_t)INT2HKEY(mdnode));
2482   }
2483   return mdnode;
2484 }
2485 
2486 /**
2487    \brief Initialize the subrange bound variables
2488    \param cb      The value of a constant bound (or 0) [output]
2489    \param bound_sptr A forward metadata reference for \p sptr [output]
2490    \param sptr    The symbol corresponding to the bound
2491    \param defVal  The default value for \p cb, the constant bound
2492    \param findex  Pass through argument for creating forward reference
2493    \param db      The debug info
2494  */
2495 INLINE static void
init_subrange_bound(LL_DebugInfo * db,ISZ_T * cb,LL_MDRef * bound_sptr,SPTR sptr,ISZ_T defVal,int findex)2496 init_subrange_bound(LL_DebugInfo *db, ISZ_T *cb, LL_MDRef *bound_sptr,
2497                     SPTR sptr, ISZ_T defVal, int findex)
2498 {
2499   if (sptr) {
2500     switch (STYPEG(sptr)) {
2501     case ST_CONST:
2502       *bound_sptr = ll_get_md_null();
2503       *cb = ad_val_of(sptr);
2504       return;
2505     case ST_VAR:
2506       if (!db->scope_is_global) {
2507         *bound_sptr = lldbg_fwd_local_variable(db, sptr, findex, false);
2508         *cb = 0;
2509         return;
2510       }
2511       break;
2512     default:
2513       break;
2514     }
2515   }
2516   *bound_sptr = ll_get_md_null();
2517   *cb = defVal;
2518 }
2519 
2520 static LL_MDRef
lldbg_emit_type(LL_DebugInfo * db,DTYPE dtype,SPTR sptr,int findex,bool is_reference,bool skip_first_dim,bool skipDataDependentTypes)2521 lldbg_emit_type(LL_DebugInfo *db, DTYPE dtype, SPTR sptr, int findex,
2522                 bool is_reference, bool skip_first_dim,
2523                 bool skipDataDependentTypes)
2524 {
2525   LL_MDRef cu_mdnode, file_mdnode, type_mdnode;
2526   LL_MDRef subscripts_mdnode, subscript_mdnode;
2527   LL_MDRef elem_type_mdnode;
2528   LL_MDRef members_mdnode;
2529   LL_MDRef parameters_mdnode;
2530   OPERAND *cur_op;
2531   DBLINT64 align, offset, low, high;
2532   ISZ_T sz, lb, ub, dim_ele;
2533   SPTR element;
2534   DTYPE elem_dtype;
2535   int anum;
2536 
2537   dim_ele = 0;
2538   if (((DTY(dtype) == TY_ARRAY) && skip_first_dim) ||
2539       (dtype >= db->dtype_array_sz))
2540     type_mdnode = ll_get_md_null();
2541   else
2542     if (db->need_dup_composite_type)
2543       type_mdnode = ll_get_md_null();
2544     else
2545       type_mdnode = db->dtype_array[dtype];
2546   if (LL_MDREF_IS_NULL(type_mdnode)) {
2547     if (is_assumed_char(dtype)) {
2548 #if defined(FLANG_LLVM_EXTENSIONS)
2549       if ((!skipDataDependentTypes) &&
2550           ll_feature_has_diextensions(&db->module->ir)) {
2551         type_mdnode =
2552             lldbg_create_assumed_len_string_type_mdnode(db, sptr, findex);
2553       } else {
2554 #endif
2555         type_mdnode =
2556             lldbg_emit_type(db, DT_CPTR, sptr, findex, false, false, false);
2557 #if defined(FLANG_LLVM_EXTENSIONS)
2558         if (!skipDataDependentTypes) {
2559 #endif
2560           dtype_array_check_set(db, dtype, type_mdnode);
2561 #if defined(FLANG_LLVM_EXTENSIONS)
2562         }
2563       }
2564 #endif
2565     } else
2566         if (DT_ISBASIC(dtype) && (DTY(dtype) != TY_PTR)) {
2567 
2568       cu_mdnode = lldbg_emit_compile_unit(db);
2569       sz = zsize_of(dtype) * 8;
2570       if (sz < 0)
2571         sz = 0; /* do not emit negative sizes */
2572       align[1] = ((alignment(dtype) + 1) * 8);
2573       align[0] = 0;
2574       offset[0] = 0;
2575       offset[1] = 0;
2576       cu_mdnode = ll_get_md_null();
2577 #if defined(FLANG_LLVM_EXTENSIONS)
2578       if (ll_feature_from_global_to_md(&db->module->ir) &&
2579           (DTY(dtype) == TY_CHAR))
2580         type_mdnode = lldbg_create_string_type_mdnode(
2581             db, sz, align, stb.tynames[DTY(dtype)], dwarf_encoding(dtype));
2582       else
2583 #endif
2584         type_mdnode = lldbg_create_basic_type_mdnode(
2585             db, cu_mdnode, stb.tynames[DTY(dtype)], ll_get_md_null(), 0, sz,
2586             align, offset, 0, dwarf_encoding(dtype));
2587       dtype_array_check_set(db, dtype, type_mdnode);
2588     } else if (DTY(dtype) == TY_ANY) {
2589       cu_mdnode = lldbg_emit_compile_unit(db);
2590       sz = 0;
2591       align[1] = 0;
2592       align[0] = 0;
2593       offset[0] = 0;
2594       offset[1] = 0;
2595       cu_mdnode = ll_get_md_null();
2596       type_mdnode = lldbg_create_basic_type_mdnode(
2597           db, cu_mdnode, stb.tynames[DTY(dtype)], ll_get_md_null(), 0, sz,
2598           align, offset, 0, dwarf_encoding(dtype));
2599       dtype_array_check_set(db, dtype, type_mdnode);
2600     } else {
2601       /* lldbg_emit_compile_unit() must be called at least once before any call
2602        * to get_filedesc_mdnode() because it establishes db->file_array[]
2603        * as a hidden side effect.
2604        */
2605       cu_mdnode = lldbg_emit_compile_unit(db);
2606 
2607       /* Set file node upfront. `DI' syntax wants a link to a file description,
2608        * rather than a reference to it */
2609       if (ll_feature_debug_info_need_file_descriptions(&db->module->ir))
2610         file_mdnode = get_filedesc_mdnode(db, findex);
2611       else
2612         file_mdnode = lldbg_emit_file(db, findex);
2613 
2614       if ((dtype == DT_NONE) && (STYPEG(sptr) == ST_PROC)) {
2615         type_mdnode = ll_get_md_null();
2616         dtype_array_check_set(db, dtype, type_mdnode);
2617         return type_mdnode;
2618       }
2619       switch (DTY(dtype)) {
2620       case TY_PTR: {
2621         /* Fortran arrays with SDSC and MIDNUM attributes have the type of either
2622          * Pointer to FortranArrayType or FortranArrayType.
2623          */
2624         if (ftn_array_need_debug_info(sptr)) {
2625           SPTR array_sptr = (SPTR)REVMIDLNKG(sptr);
2626           type_mdnode = lldbg_emit_type(db, DTYPEG(array_sptr), array_sptr, findex,
2627                                         false, false, false);
2628           /* Emit FortranArrayType instead of pointer to FortranArrayType
2629            * to workaround a known gdb bug not able to debug array bounds.
2630            * i.e.
2631            * 1) On POWER, gdb 7.x fails to read array bounds either w/ or
2632            * w/o the pointer type layer; gdb 8.x only works w/o the pointer
2633            * type layer.
2634            * 2) On X86, gdb 7.x works either w/ or w/o the pointer type layer,
2635            * however, gdb 8.x only works w/o the pointer type layer.
2636            */
2637           return type_mdnode;
2638         }
2639         type_mdnode = lldbg_emit_type(db, DTySeqTyElement(dtype), sptr, findex,
2640                                       false, false, false);
2641         sz = (ZSIZEOF(dtype) * 8);
2642         align[1] = ((alignment(dtype) + 1) * 8);
2643         align[0] = 0;
2644         offset[0] = 0;
2645         offset[1] = 0;
2646         cu_mdnode = ll_get_md_null();
2647           type_mdnode = lldbg_create_pointer_type_mdnode(
2648               db, cu_mdnode, "", ll_get_md_null(), 0, sz, align, offset, 0,
2649               type_mdnode);
2650           dtype_array_check_set(db, dtype, type_mdnode);
2651         break;
2652       }
2653 
2654       case TY_PFUNC:
2655       case TY_PROC:
2656         parameters_mdnode = lldbg_emit_parameter_list(
2657             db, dtype, DTyReturnType(dtype), sptr, findex);
2658         type_mdnode = lldbg_create_subroutine_type_mdnode(
2659             db, cu_mdnode, file_mdnode, parameters_mdnode, 0);
2660         dtype_array_check_set(db, dtype, type_mdnode);
2661         break;
2662 
2663       case TY_ARRAY: {
2664         LLMD_Builder mdb = llmd_init(db->module);
2665         ADSC *ad;
2666         int i, numdim;
2667         elem_dtype = DTySeqTyElement(dtype);
2668         sz = zsize_of(dtype) * 8;
2669         if (sz < 0)
2670           sz = 0; /* don't emit debug with negative sizes */
2671         align[0] = 0;
2672         align[1] = (alignment(dtype) + 1) * 8;
2673         ad = AD_DPTR(dtype);
2674         numdim = AD_NUMDIM(ad);
2675         if (numdim >= 1 && numdim <= 7) {
2676           for (i = 0; i < numdim; ++i) {
2677             SPTR lower_bnd = AD_LWBD(ad, i);
2678             SPTR upper_bnd = AD_UPBD(ad, i);
2679             if (ll_feature_has_diextensions(&db->module->ir)) {
2680               // use PGI metadata extensions
2681               LL_MDRef lbv;
2682               LL_MDRef ubv;
2683               if (SDSCG(sptr) && MIDNUMG(sptr) &&
2684                   !(lower_bnd && STYPEG(lower_bnd) == ST_CONST &&
2685                     upper_bnd && STYPEG(upper_bnd) == ST_CONST)) {
2686                 /* Create subrange mdnode based on array descriptor */
2687                 subscript_mdnode =
2688                     lldbg_create_ftn_subrange_via_sdsc(db, findex, sptr, i);
2689               } else {
2690                 const ISZ_T M = 1ul << ((sizeof(ISZ_T) * 8) - 1);
2691                 init_subrange_bound(db, &lb, &lbv, lower_bnd, 1, findex);
2692                 init_subrange_bound(db, &ub, &ubv, upper_bnd, M, findex);
2693                 subscript_mdnode =
2694                     lldbg_create_ftn_subrange_mdnode(db, lb, lbv, ub, ubv);
2695               }
2696               llmd_add_md(mdb, subscript_mdnode);
2697             } else {
2698               // cons the old debug metadata
2699               if (lower_bnd && STYPEG(lower_bnd) == ST_CONST && upper_bnd &&
2700                   STYPEG(upper_bnd) == ST_CONST) {
2701                 lb = ad_val_of(lower_bnd); /* or get_isz_cval() */
2702                 if (upper_bnd)
2703                   ub = ad_val_of(upper_bnd); /* or get_isz_cval() */
2704                 else
2705                   ub = 0; /* error or zero-size */
2706                 subscript_mdnode = lldbg_create_subrange_mdnode(db, lb, ub);
2707                 llmd_add_md(mdb, subscript_mdnode);
2708               } else {
2709                 subscript_mdnode = lldbg_create_subrange_mdnode(db, 1, 1);
2710                 llmd_add_md(mdb, subscript_mdnode);
2711               }
2712             }
2713           }
2714         }
2715         elem_type_mdnode =
2716             lldbg_emit_type(db, elem_dtype, sptr, findex, false, false, false);
2717         cu_mdnode = ll_get_md_null();
2718         subscripts_mdnode = llmd_finish(mdb);
2719         if (ll_feature_has_diextensions(&db->module->ir)) {
2720           type_mdnode = lldbg_create_ftn_array_type_mdnode(
2721               db, cu_mdnode, 0, sz, align, elem_type_mdnode, subscripts_mdnode);
2722         } else
2723           type_mdnode = lldbg_create_array_type_mdnode(
2724               db, cu_mdnode, 0, sz, align, elem_type_mdnode, subscripts_mdnode);
2725         dtype_array_check_set(db, dtype, type_mdnode);
2726         break;
2727       }
2728       case TY_UNION:
2729         members_mdnode = ll_create_flexible_md_node(db->module);
2730         sz = (ZSIZEOF(dtype) * 8);
2731         align[1] = ((alignment(dtype) + 1) * 8);
2732         align[0] = 0;
2733         type_mdnode = lldbg_create_union_type_mdnode(
2734             db, cu_mdnode,
2735             DTyAlgTyTag(dtype) ? SYMNAME(DTyAlgTyTag(dtype)) : "", file_mdnode,
2736             0, sz, align, 0, members_mdnode, 0);
2737       case TY_STRUCT:
2738         if (LL_MDREF_IS_NULL(type_mdnode)) {
2739           members_mdnode = ll_create_flexible_md_node(db->module);
2740           sz = (ZSIZEOF(dtype) * 8);
2741           align[1] = ((alignment(dtype) + 1) * 8);
2742           align[0] = 0;
2743           if (!ll_feature_debug_info_pre34(&db->module->ir))
2744             file_mdnode = get_filedesc_mdnode(db, findex);
2745           type_mdnode = lldbg_create_structure_type_mdnode(
2746               db, cu_mdnode,
2747               DTyAlgTyTag(dtype) ? SYMNAME(DTyAlgTyTag(dtype)) : "",
2748               file_mdnode, 0, sz, align, 0, members_mdnode, 0);
2749         }
2750         dtype_array_check_set(db, dtype, type_mdnode);
2751         element = DTyAlgTyMember(dtype);
2752         lldbg_create_aggregate_members_type(db, element, findex, file_mdnode,
2753                                             members_mdnode, type_mdnode);
2754         break;
2755       case TY_VECT: {
2756         LLMD_Builder ssmdb = llmd_init(db->module);
2757         /* TODO: Check that vector datatype is what's expected by LLVM */
2758         lb = 0;
2759         ub = DTyVecLength(dtype) - 1;
2760         subscript_mdnode = lldbg_create_subrange_mdnode(db, lb, ub);
2761         llmd_add_md(ssmdb, subscript_mdnode);
2762         subscripts_mdnode = llmd_finish(ssmdb);
2763         sz = (ZSIZEOF(dtype) * 8);
2764         align[1] = ((alignment(dtype) + 1) * 8);
2765         align[0] = 0;
2766         type_mdnode = lldbg_emit_type(db, DTySeqTyElement(dtype), SPTR_NULL,
2767                                       findex, false, false, false);
2768         type_mdnode = lldbg_create_vector_type_mdnode(
2769             db, cu_mdnode, sz, align, type_mdnode, subscripts_mdnode);
2770         dtype_array_check_set(db, dtype, type_mdnode);
2771         break;
2772       }
2773       default:
2774         assert(0, "dtype not yet handled ", DTY(dtype), ERR_Fatal);
2775       }
2776     }
2777   }
2778 
2779   if (is_reference) {
2780     if (DT_ISBASIC(dtype) && DTY(dtype) != TY_PTR) {
2781       cu_mdnode = lldbg_emit_compile_unit(db);
2782       sz = (ZSIZEOF(DT_CPTR) * 8);
2783       align[1] = ((alignment(DT_CPTR) + 1) * 8);
2784       align[0] = 0;
2785       offset[0] = 0;
2786       offset[1] = 0;
2787       cu_mdnode = ll_get_md_null();
2788       type_mdnode = lldbg_create_pointer_type_mdnode(
2789           db, cu_mdnode, "", ll_get_md_null(), 0, sz, align, offset, 0,
2790           type_mdnode);
2791     } else if (DTY(dtype) == TY_ARRAY) {
2792       cu_mdnode = lldbg_emit_compile_unit(db);
2793       sz = (ZSIZEOF(DT_CPTR) * 8);
2794       align[1] = ((alignment(DT_CPTR) + 1) * 8);
2795       align[0] = 0;
2796       offset[0] = 0;
2797       offset[1] = 0;
2798       cu_mdnode = ll_get_md_null();
2799       type_mdnode = lldbg_create_pointer_type_mdnode(
2800           db, cu_mdnode, "", ll_get_md_null(), 0, sz, align, offset, 0,
2801           type_mdnode);
2802     }
2803   }
2804   return type_mdnode;
2805 }
2806 
2807 static void
llObjtodbgAddUnique(LL_ObjToDbgList * odl,LL_MDRef mdadd)2808 llObjtodbgAddUnique(LL_ObjToDbgList *odl, LL_MDRef mdadd)
2809 {
2810   LL_ObjToDbgListIter i;
2811   for (llObjtodbgFirst(odl, &i); !llObjtodbgAtEnd(&i); llObjtodbgNext(&i)) {
2812     LL_MDRef md = llObjtodbgGet(&i);
2813     if (md == mdadd)
2814       return;
2815   }
2816   llObjtodbgPush(odl, mdadd);
2817 }
2818 
2819 void
lldbg_emit_global_variable(LL_DebugInfo * db,SPTR sptr,ISZ_T off,int findex,LL_Value * value)2820 lldbg_emit_global_variable(LL_DebugInfo *db, SPTR sptr, ISZ_T off, int findex,
2821                            LL_Value *value)
2822 {
2823   LL_MDRef scope_mdnode, file_mdnode, type_mdnode, mdref, fwd;
2824   int sc, decl_line, is_local, flags;
2825   const char *display_name;
2826   bool savedScopeIsGlobal;
2827   hash_data_t val;
2828 
2829   assert(db, "Debug info not enabled", 0, ERR_Fatal);
2830   if ((!sptr) || (!DTYPEG(sptr)))
2831     return;
2832   savedScopeIsGlobal = db->scope_is_global;
2833   db->scope_is_global = true;
2834   db->gbl_var_sptr = sptr;
2835   type_mdnode =
2836       lldbg_emit_type(db, DTYPEG(sptr), sptr, findex, false, false, false);
2837   get_extra_info_for_sptr(&display_name, &scope_mdnode, &type_mdnode, db, sptr);
2838   display_name = SYMNAME(sptr);
2839   file_mdnode = ll_feature_debug_info_need_file_descriptions(&db->module->ir)
2840                     ? get_filedesc_mdnode(db, findex)
2841                     : lldbg_emit_file(db, findex);
2842   sc = SCG(sptr);
2843   decl_line = DECLLINEG(sptr);
2844   if (!decl_line)
2845     decl_line = FUNCLINEG(sptr);
2846   is_local = (sc == SC_STATIC);
2847   if (hashmap_lookup(db->module->mdnodes_fwdvars, INT2HKEY(sptr), &val)) {
2848     fwd = (LL_MDRef)(unsigned long)val;
2849     hashmap_erase(db->module->mdnodes_fwdvars, INT2HKEY(sptr), NULL);
2850   } else {
2851     fwd = ll_get_md_null();
2852   }
2853   flags = CCSYMG(sptr) ? DIFLAG_ARTIFICIAL : 0;
2854   if (ftn_array_need_debug_info(sptr)) {
2855     SPTR array_sptr =(SPTR)REVMIDLNKG(sptr);
2856     /* Overwrite the display_name and flags to represent the user defined
2857      * array instead of a compiler generated symbol of array pointer.
2858      */
2859     display_name = SYMNAME(array_sptr);
2860     flags = 0;
2861   }
2862   mdref = lldbg_create_global_variable_mdnode(
2863       db, scope_mdnode, display_name, SYMNAME(sptr), "", file_mdnode, decl_line,
2864       type_mdnode, is_local, DEFDG(sptr) || (sc != SC_EXTERN), value, -1, flags,
2865       off, sptr, fwd);
2866 
2867   if (!LL_MDREF_IS_NULL(db->gbl_obj_mdnode)) {
2868     if (LL_MDREF_IS_NULL(db->gbl_obj_exp_mdnode)) {
2869       /* Create a dummy global var expression mdnode to be associated to
2870        * the global static object.
2871        */
2872       db->gbl_obj_exp_mdnode = lldbg_create_global_variable_mdnode(
2873           db, scope_mdnode, "", "", "", file_mdnode, 0, type_mdnode, 0, 0,
2874           NULL, -1, DIFLAG_ARTIFICIAL, 0, SPTR_NULL, db->gbl_obj_mdnode);
2875     }
2876     if (db->need_dup_composite_type) {
2877       /* erase dtype record to allow duplication for allocatable array type within
2878        * derived type.
2879        */
2880       dtype_array_check_set(db, DTYPEG(sptr), ll_get_md_null());
2881       db->need_dup_composite_type = false;
2882     }
2883   }
2884   db->gbl_var_sptr = SPTR_NULL;
2885 
2886   if (!LL_MDREF_IS_NULL(mdref)) {
2887     LL_ObjToDbgList **listp = llassem_get_objtodbg_list(sptr);
2888     if (listp) {
2889       if (!*listp)
2890         *listp = llObjtodbgCreate();
2891       llObjtodbgAddUnique(*listp, mdref);
2892       // Associate a dummy global var mdnode to the global static object.
2893       if (!LL_MDREF_IS_NULL(db->gbl_obj_exp_mdnode))
2894         llObjtodbgAddUnique(*listp, db->gbl_obj_exp_mdnode);
2895     }
2896     ll_add_global_debug(db->module, sptr, mdref);
2897     if (gbl.rutype == RU_BDATA && sc == SC_CMBLK) {
2898       const char *modvar_name;
2899       if (CCSYMG(MIDNUMG(sptr))) {
2900         modvar_name = new_debug_name(SYMNAME(ENCLFUNCG(sptr)),
2901                                      SYMNAME(sptr), NULL);
2902       } else {
2903         modvar_name = new_debug_name(SYMNAME(ENCLFUNCG(sptr)),
2904                                      SYMNAME(MIDNUMG(sptr)), SYMNAME(sptr));
2905       }
2906       if (ll_feature_from_global_to_md(&db->module->ir)) {
2907         /* Lookup the !DIGlobalVariable node instead of the
2908          * !DIGlobalVariableExpression node. This step is needed
2909          * by the lldbg_create_imported_entity() */
2910         LL_MDNode *node = db->module->mdnodes[LL_MDREF_value(mdref) - 1];
2911         mdref = node->elem[0];
2912       }
2913       ll_add_module_debug(db->module->modvar_debug_map, modvar_name, mdref);
2914     }
2915   }
2916   db->scope_is_global = savedScopeIsGlobal;
2917 }
2918 
2919 static char *
lldbg_get_addrspace_suffix(int addrspace)2920 lldbg_get_addrspace_suffix(int addrspace)
2921 {
2922   switch (addrspace) {
2923   case 1:
2924     return "_gbl";
2925   case 4:
2926     return "_cst";
2927   default:
2928     return "_gen";
2929   }
2930 }
2931 
2932 static void
lldbg_cancel_value_call(LL_DebugInfo * db,SPTR sptr)2933 lldbg_cancel_value_call(LL_DebugInfo *db, SPTR sptr)
2934 {
2935   int i;
2936   for (i = 0; i < db->param_idx; i++)
2937     if (db->param_stack[i].sptr == sptr)
2938       db->param_stack[i].instr->flags |= CANCEL_CALL_DBG_VALUE;
2939 }
2940 
2941 void
lldbg_register_value_call(LL_DebugInfo * db,INSTR_LIST * instr,int sptr)2942 lldbg_register_value_call(LL_DebugInfo *db, INSTR_LIST *instr, int sptr)
2943 {
2944   int i;
2945 
2946   assert(db, "Debug info not enabled", 0, ERR_Fatal);
2947 
2948   for (i = 0; i < db->param_idx; i++) {
2949     if (db->param_stack[i].sptr == sptr) {
2950       db->param_stack[i].instr = instr;
2951       return;
2952     }
2953   }
2954   assert(db->param_idx < PARAM_STACK_SIZE,
2955          "lldbg_register_value_call(), param stack is full", sptr, ERR_Fatal);
2956   db->param_stack[db->param_idx].instr = instr;
2957   db->param_stack[db->param_idx].mdnode = ll_get_md_null();
2958   db->param_stack[db->param_idx].sptr = sptr;
2959   db->param_idx++;
2960 }
2961 
2962 static LL_MDRef
get_param_mdnode(LL_DebugInfo * db,int sptr)2963 get_param_mdnode(LL_DebugInfo *db, int sptr)
2964 {
2965   int i;
2966   for (i = 0; i < db->param_idx; i++)
2967     if (db->param_stack[i].sptr == sptr)
2968       return db->param_stack[i].mdnode;
2969   return ll_get_md_null();
2970 }
2971 
2972 static void
lldbg_register_param_mdnode(LL_DebugInfo * db,LL_MDRef mdnode,int sptr)2973 lldbg_register_param_mdnode(LL_DebugInfo *db, LL_MDRef mdnode, int sptr)
2974 {
2975   int i;
2976   for (i = 0; i < db->param_idx; i++) {
2977     if (db->param_stack[i].sptr == sptr) {
2978       db->param_stack[i].mdnode = mdnode;
2979       return;
2980     }
2981   }
2982   assert(db->param_idx < PARAM_STACK_SIZE,
2983          "lldbg_register_param_mdnode(),"
2984          " param stack is full",
2985          sptr, ERR_Fatal);
2986   db->param_stack[db->param_idx].instr = NULL;
2987   db->param_stack[db->param_idx].mdnode = mdnode;
2988   db->param_stack[db->param_idx].sptr = sptr;
2989   db->param_idx++;
2990 }
2991 
2992 void
lldbg_emit_lv_list(LL_DebugInfo * db)2993 lldbg_emit_lv_list(LL_DebugInfo *db)
2994 {
2995   int i;
2996   LL_MDRef lv_list_mdnode;
2997 
2998   assert(db, "Debug info not enabled", 0, ERR_Fatal);
2999   assert(db->routine_idx > 0 && db->routine_idx <= db->routine_count,
3000          "lldbg_emit_lv_list(), invalid routine_idx", 0, ERR_Fatal);
3001   lv_list_mdnode = db->llvm_dbg_lv_array[db->routine_idx - 1];
3002   for (i = 0; i < db->param_idx; i++) {
3003     if (!LL_MDREF_IS_NULL(db->param_stack[i].mdnode) &&
3004         ((db->param_stack[i].instr == NULL) ||
3005          !(db->param_stack[i].instr->flags & CANCEL_CALL_DBG_VALUE)))
3006       ll_extend_md_node(db->module, lv_list_mdnode, db->param_stack[i].mdnode);
3007   }
3008 }
3009 
3010 /**
3011    \brief Construct the flag set that corresponds with LLVM metadata
3012  */
3013 INLINE static int
set_dilocalvariable_flags(int sptr)3014 set_dilocalvariable_flags(int sptr)
3015 {
3016 
3017 #ifdef THISG
3018   if (ENCLFUNCG(sptr) && THISG(ENCLFUNCG(sptr)) == sptr) {
3019     return DIFLAG_ARTIFICIAL;
3020   }
3021 #endif
3022   return CCSYMG(sptr) ? DIFLAG_ARTIFICIAL : 0;
3023 }
3024 
3025 LL_MDRef
lldbg_emit_local_variable(LL_DebugInfo * db,SPTR sptr,int findex,int emit_dummy_as_local)3026 lldbg_emit_local_variable(LL_DebugInfo *db, SPTR sptr, int findex,
3027                           int emit_dummy_as_local)
3028 {
3029   LL_MDRef file_mdnode, type_mdnode, var_mdnode;
3030   char *symname;
3031 
3032   assert(db, "Debug info not enabled", 0, ERR_Fatal);
3033   if (ll_feature_debug_info_need_file_descriptions(&db->module->ir))
3034     file_mdnode = get_filedesc_mdnode(db, findex);
3035   else
3036     file_mdnode = lldbg_emit_file(db, findex);
3037   type_mdnode =
3038       lldbg_emit_type(db, DTYPEG(sptr), sptr, findex, false, false, false);
3039 #ifdef THISG
3040   if (ENCLFUNCG(sptr) && THISG(ENCLFUNCG(sptr)) == sptr) {
3041     symname = "this";
3042   } else
3043 #endif
3044   {
3045     symname = (char *)lldbg_alloc(strlen(SYMNAME(sptr)) + 1);
3046     strcpy(symname, SYMNAME(sptr));
3047   }
3048   if (SCG(sptr) == SC_DUMMY && !emit_dummy_as_local) {
3049     lldbg_cancel_value_call(db, sptr);
3050     var_mdnode = get_param_mdnode(db, sptr);
3051     assert(!LL_MDREF_IS_NULL(var_mdnode),
3052            "lldbg_emit_local_variable: parameter not in param stack for sptr ",
3053            sptr, ERR_Fatal);
3054   } else {
3055     int flags = set_dilocalvariable_flags(sptr);
3056     BLKINFO *blk_info = get_lexical_block_info(db, sptr, true);
3057     LL_MDRef fwd;
3058     hash_data_t val;
3059     if (hashmap_lookup(db->module->mdnodes_fwdvars, INT2HKEY(sptr), &val)) {
3060       fwd = (LL_MDRef)(unsigned long)val;
3061       hashmap_erase(db->module->mdnodes_fwdvars, INT2HKEY(sptr), NULL);
3062     } else {
3063       fwd = ll_get_md_null();
3064     }
3065     if (ftn_array_need_debug_info(sptr)) {
3066       SPTR array_sptr =(SPTR)REVMIDLNKG(sptr);
3067       /* Overwrite the symname and flags to represent the user defined array
3068        * instead of a compiler generated symbol of array pointer.
3069        */
3070       symname = (char *)lldbg_alloc(strlen(SYMNAME(array_sptr)) + 1);
3071       strcpy(symname, SYMNAME(array_sptr));
3072       flags = 0;
3073     }
3074     var_mdnode = lldbg_create_local_variable_mdnode(
3075         db, DW_TAG_auto_variable, blk_info->mdnode, symname, file_mdnode, 0, 0,
3076         type_mdnode, flags, fwd);
3077   }
3078   return var_mdnode;
3079 }
3080 
3081 typedef struct {
3082   LL_DebugInfo *db;
3083   int findex;
3084 } CleanupBounds_t;
3085 
3086 static void
cleanup_bounds(hash_key_t ksptr,hash_data_t dmdnode,void * ctxt)3087 cleanup_bounds(hash_key_t ksptr, hash_data_t dmdnode, void *ctxt)
3088 {
3089   CleanupBounds_t *s = (CleanupBounds_t *)ctxt;
3090   LL_DebugInfo *db = s->db;
3091   const int findex = s->findex;
3092   const SPTR sptr = (SPTR)HKEY2INT(ksptr);
3093   lldbg_emit_local_variable(db, sptr, findex, true);
3094 }
3095 
3096 void
lldbg_cleanup_missing_bounds(LL_DebugInfo * db,int findex)3097 lldbg_cleanup_missing_bounds(LL_DebugInfo *db, int findex)
3098 {
3099   if (hashmap_size(db->module->mdnodes_fwdvars)) {
3100     CleanupBounds_t s = {db, findex};
3101     hashmap_iterate(db->module->mdnodes_fwdvars, cleanup_bounds, &s);
3102     hashmap_clear(db->module->mdnodes_fwdvars);
3103   }
3104 }
3105 
3106 LL_MDRef
lldbg_emit_param_variable(LL_DebugInfo * db,SPTR sptr,int findex,int parnum,bool unnamed)3107 lldbg_emit_param_variable(LL_DebugInfo *db, SPTR sptr, int findex, int parnum,
3108                           bool unnamed)
3109 {
3110   LL_MDRef file_mdnode, type_mdnode, var_mdnode;
3111   char *symname;
3112   bool is_reference;
3113   DTYPE dtype;
3114   int flags;
3115 
3116   assert(db, "Debug info not enabled", 0, ERR_Fatal);
3117   if (LL_MDREF_IS_NULL(db->cur_subprogram_mdnode))
3118     return var_mdnode;
3119   if (ll_feature_debug_info_need_file_descriptions(&db->module->ir))
3120     file_mdnode = get_filedesc_mdnode(db, findex);
3121   else
3122     file_mdnode = lldbg_emit_file(db, findex);
3123   is_reference = ((SCG(sptr) == SC_DUMMY) && HOMEDG(sptr) && !PASSBYVALG(sptr));
3124   dtype = DTYPEG(sptr) ? DTYPEG(sptr) : DT_ADDR;
3125   type_mdnode =
3126       lldbg_emit_type(db, dtype, sptr, findex, is_reference, true, false);
3127   if (unnamed) {
3128     symname = NULL;
3129 #ifdef THISG
3130   } else if (ENCLFUNCG(sptr) && THISG(ENCLFUNCG(sptr)) == sptr) {
3131     symname = "this";
3132 #endif
3133   } else {
3134     symname = (char *)lldbg_alloc(sizeof(char) * (strlen(SYMNAME(sptr)) + 1));
3135     strcpy(symname, SYMNAME(sptr));
3136   }
3137   flags = set_dilocalvariable_flags(sptr);
3138   var_mdnode = lldbg_create_local_variable_mdnode(
3139       db, DW_TAG_arg_variable, db->cur_subprogram_mdnode, symname, file_mdnode,
3140       db->cur_subprogram_lineno, parnum, type_mdnode, flags, ll_get_md_null());
3141   lldbg_register_param_mdnode(db, var_mdnode, sptr);
3142   return var_mdnode;
3143 }
3144 
3145 LL_MDRef
lldbg_emit_ptr_param_variable(LL_DebugInfo * db,SPTR sptr,int findex,int parnum)3146 lldbg_emit_ptr_param_variable(LL_DebugInfo *db, SPTR sptr, int findex,
3147                               int parnum)
3148 {
3149   LL_MDRef file_mdnode, type_mdnode, var_mdnode, cu_mdnode;
3150   char *symname;
3151   ISZ_T sz;
3152   DBLINT64 align = {0};
3153   DBLINT64 offset = {0};
3154   int is_reference = 0;
3155   int flags;
3156 
3157   assert(db, "Debug info not enabled", 0, ERR_Fatal);
3158   if (ll_feature_debug_info_need_file_descriptions(&db->module->ir))
3159     file_mdnode = get_filedesc_mdnode(db, findex);
3160   else
3161     file_mdnode = lldbg_emit_file(db, findex);
3162   is_reference = ((SCG(sptr) == SC_DUMMY) && HOMEDG(sptr) && !PASSBYVALG(sptr));
3163   type_mdnode = lldbg_emit_type(db, DTYPEG(sptr), sptr, findex, is_reference,
3164                                 false, false);
3165   cu_mdnode = lldbg_emit_compile_unit(db);
3166   sz = (ZSIZEOF(DT_CPTR) * 8);
3167   align[1] = ((alignment(DT_CPTR) + 1) * 8);
3168   cu_mdnode = ll_get_md_null();
3169   type_mdnode =
3170       lldbg_create_pointer_type_mdnode(db, cu_mdnode, "", ll_get_md_null(), 0,
3171                                        sz, align, offset, 0, type_mdnode);
3172 
3173 #ifdef THISG
3174   if (ENCLFUNCG(sptr) && THISG(ENCLFUNCG(sptr)) == sptr) {
3175     symname = "this";
3176   } else
3177 #endif
3178   {
3179     symname = (char *)lldbg_alloc(sizeof(char) * (strlen(SYMNAME(sptr)) + 1));
3180     strcpy(symname, SYMNAME(sptr));
3181   }
3182   flags = set_dilocalvariable_flags(sptr);
3183   var_mdnode = lldbg_create_local_variable_mdnode(
3184       db, DW_TAG_arg_variable, db->cur_subprogram_mdnode, symname, file_mdnode,
3185       db->cur_subprogram_lineno, parnum, type_mdnode, flags, ll_get_md_null());
3186   lldbg_register_param_mdnode(db, var_mdnode, sptr);
3187   return var_mdnode;
3188 }
3189 
3190 void
lldbg_function_end(LL_DebugInfo * db,int func)3191 lldbg_function_end(LL_DebugInfo *db, int func)
3192 {
3193   LL_Type *type;
3194   LL_Value *value;
3195   SPTR i;
3196 
3197   if (!(flg.debug && db))
3198     return;
3199 
3200   for (i = stb.firstusym; i != stb.stg_avail; ++i) {
3201     const int st = STYPEG(i);
3202     const int sc = SCG(i);
3203 
3204     if ((st == ST_ENTRY) || (st == ST_PROC) || (st == ST_CONST) ||
3205         (st == ST_PARAM) || (!DCLDG(i)) || CCSYMG(i) ||
3206         ((sc != SC_EXTERN) && (sc != SC_STATIC)))
3207       continue;
3208 
3209     if (!REFG(i)) {
3210       // generate unreferenced variables
3211       // add these to DWARF output as <optimized out> variables
3212       LL_Type *cache = LLTYPE(i);
3213       const DTYPE dtype = DTYPEG(i);
3214       process_dtype_struct(dtype); // make sure type is emitted
3215       type = make_lltype_from_dtype(dtype);
3216       value = ll_create_value_from_type(db->module, type, "undef");
3217       lldbg_emit_global_variable(db, i, 0, 1, value);
3218       LLTYPE(i) = cache;
3219     } else if ((!SNAME(i)) && REFG(i)) {
3220       // add referenced variables not discovered as yet
3221       const char *sname;
3222       const char *name;
3223       char *buff;
3224       LL_Type *cache = LLTYPE(i);
3225       const DTYPE dtype = DTYPEG(i);
3226       process_dtype_struct(dtype); // make sure type is emitted
3227       type = ll_get_pointer_type(make_lltype_from_dtype(dtype));
3228       name = get_llvm_name(i);
3229       // Hack: splice in the LLVM user-defined IR type name
3230       sname = getsname(i); // temporary pointer
3231       buff = (char *)getitem(LLVM_LONGTERM_AREA, strlen(name) + strlen(sname) +
3232                                                      strlen(type->str) + 25);
3233       sprintf(buff, "bitcast (%%struct%s* @%s to %s)", sname, name, type->str);
3234       value = ll_create_value_from_type(db->module, type, (const char *)buff);
3235       lldbg_emit_global_variable(db, i, 0, 1, value);
3236       LLTYPE(i) = cache;
3237     }
3238   }
3239 }
3240 
3241 static LL_MDRef
lldbg_create_imported_entity(LL_DebugInfo * db,SPTR entity_sptr,SPTR func_sptr,IMPORT_TYPE entity_type)3242 lldbg_create_imported_entity(LL_DebugInfo *db, SPTR entity_sptr, SPTR func_sptr,
3243                              IMPORT_TYPE entity_type)
3244 {
3245   LLMD_Builder mdb;
3246   LL_MDRef entity_mdnode, scope_mdnode, file_mdnode, cur_mdnode;
3247   unsigned tag;
3248 
3249   switch (entity_type) {
3250   case IMPORTED_DECLARATION: {
3251     const char *modvar_name;
3252     tag = DW_TAG_imported_declaration;
3253     if (CCSYMG(MIDNUMG(entity_sptr))) {
3254       modvar_name = new_debug_name(SYMNAME(ENCLFUNCG(entity_sptr)),
3255                                    SYMNAME(entity_sptr), NULL);
3256     } else {
3257       modvar_name = new_debug_name(SYMNAME(ENCLFUNCG(entity_sptr)),
3258                                    SYMNAME(MIDNUMG(entity_sptr)), SYMNAME(entity_sptr));
3259     }
3260     entity_mdnode = ll_get_module_debug(db->module->modvar_debug_map, modvar_name);
3261     break;
3262   }
3263   case IMPORTED_MODULE: {
3264     tag = DW_TAG_imported_module;
3265     entity_mdnode = ll_get_module_debug(db->module->module_debug_map, SYMNAME(entity_sptr));
3266     break;
3267   }
3268   case IMPORTED_UNIT: /* TODO: not implemented yet */
3269   default:
3270     return ll_get_md_null();
3271   }
3272   mdb = llmd_init(db->module);
3273   scope_mdnode = (func_sptr == gbl.currsub) ? db->cur_subprogram_mdnode : scope_mdnode;
3274   if (!entity_mdnode || !scope_mdnode)
3275     return ll_get_md_null();
3276 
3277   file_mdnode = ll_feature_debug_info_need_file_descriptions(&db->module->ir)
3278                     ? get_filedesc_mdnode(db, 1)
3279                     : lldbg_emit_file(db, 1);
3280 
3281   llmd_set_class(mdb, LL_DIImportedEntity);
3282   llmd_add_i32(mdb, make_dwtag(db, tag));  // tag
3283   llmd_add_md(mdb, entity_mdnode);         // entity
3284   llmd_add_md(mdb, scope_mdnode);          // scope
3285   llmd_add_md(mdb, file_mdnode);           // file
3286   llmd_add_i32(mdb, FUNCLINEG(func_sptr)); // line? no accurate line number yet
3287   if (entity_type == IMPORTED_DECLARATION) {
3288     const char *alias_name = lookup_modvar_alias(entity_sptr);
3289     if (alias_name && strcmp(alias_name, SYMNAME(entity_sptr)))
3290       llmd_add_string(mdb, alias_name);    // variable renamed
3291   }
3292 
3293   cur_mdnode = llmd_finish(mdb);
3294   ll_extend_md_node(db->module, db->llvm_dbg_imported, cur_mdnode);
3295   return cur_mdnode;
3296 }
3297 
3298 static void
lldbg_emit_imported_entity(LL_DebugInfo * db,SPTR entity_sptr,SPTR func_sptr,IMPORT_TYPE entity_type)3299 lldbg_emit_imported_entity(LL_DebugInfo *db, SPTR entity_sptr, SPTR func_sptr,
3300                            IMPORT_TYPE entity_type)
3301 {
3302   static hashset_t entity_func_added;
3303   const char *entity_func;
3304 
3305   if (INMODULEG(func_sptr) == entity_sptr)
3306     return;
3307   if (!entity_func_added)
3308     entity_func_added = hashset_alloc(hash_functions_strings);
3309   entity_func = new_debug_name(SYMNAME(entity_sptr), SYMNAME(func_sptr), NULL);
3310   if (hashset_lookup(entity_func_added, entity_func))
3311     return;
3312   hashset_insert(entity_func_added, entity_func);
3313   lldbg_create_imported_entity(db, entity_sptr, func_sptr, entity_type);
3314 }
3315 
3316 void
lldbg_create_cmblk_mem_mdnode_list(SPTR sptr,SPTR gblsym)3317 lldbg_create_cmblk_mem_mdnode_list(SPTR sptr, SPTR gblsym)
3318 {
3319   SPTR var;
3320   LL_MDRef mdref;
3321   LL_ObjToDbgList **listp = &AG_OBJTODBGLIST(gblsym);
3322   if (!*listp)
3323     *listp = llObjtodbgCreate();
3324   for (var = CMEMFG(sptr); var > NOSYM; var = SYMLKG(var)) {
3325       mdref = ll_get_global_debug(cpu_llvm_module, var);
3326       if (!LL_MDREF_IS_NULL(mdref))
3327         llObjtodbgAddUnique(*listp, mdref);
3328   }
3329   /* add processing for COMMON */
3330   mdref = ll_get_global_debug(cpu_llvm_module, sptr);
3331   if (!LL_MDREF_IS_NULL(mdref))
3332     llObjtodbgAddUnique(*listp, mdref);
3333 }
3334 
3335 static LL_MDRef
lldbg_create_cmblk_gv_mdnode(LL_DebugInfo * db,LL_MDRef cmnblk_mdnode,SPTR sptr)3336 lldbg_create_cmblk_gv_mdnode(LL_DebugInfo *db, LL_MDRef cmnblk_mdnode,
3337                              SPTR sptr)
3338 {
3339   LL_MDRef mdref, type_mdnode, subscripts_mdnode, subscript_mdnode,
3340       elem_type_mdnode;
3341   DBLINT64 align;
3342   ISZ_T sz, lb, ub, dim_ele;
3343   DTYPE elem_dtype;
3344   LLMD_Builder mdb = llmd_init(db->module);
3345   const char *display_name;
3346 
3347   elem_dtype = DT_BINT;
3348   sz = SIZEG(sptr);
3349   dim_ele = sz - 1;
3350   lb = 0;
3351   ub = dim_ele;
3352   align[1] = ((alignment(elem_dtype) + 1) * 8);
3353   align[0] = 0;
3354   subscript_mdnode = lldbg_create_subrange_mdnode(db, lb, ub);
3355   llmd_add_md(mdb, subscript_mdnode);
3356   sz *= ZSIZEOF(elem_dtype) * 8;
3357   elem_type_mdnode =
3358       lldbg_emit_type(db, elem_dtype, sptr, 1, false, false, false);
3359   subscripts_mdnode = llmd_finish(mdb);
3360   type_mdnode = lldbg_create_array_type_mdnode(
3361       db, ll_get_md_null(), 0, sz, align, elem_type_mdnode, subscripts_mdnode);
3362   display_name = SYMNAME(sptr);
3363   mdref = lldbg_create_global_variable_mdnode(
3364       db, cmnblk_mdnode, display_name, SYMNAME(sptr), "", ll_get_md_null(),
3365       DECLLINEG(sptr), type_mdnode, 0, 1, NULL, -1, DIFLAG_ARTIFICIAL, 0,
3366       SPTR_NULL, ll_get_md_null());
3367   ll_add_global_debug(db->module, sptr, mdref);
3368   return mdref;
3369 }
3370 
3371 static LL_MDRef
lldbg_create_common_block_mdnode(LL_DebugInfo * db,LL_MDRef scope,LL_MDRef decl,char * name)3372 lldbg_create_common_block_mdnode(LL_DebugInfo *db, LL_MDRef scope,
3373                                  LL_MDRef decl, char *name)
3374 {
3375   LLMD_Builder mdb;
3376   char *common_block_name, *pname, *pmname;
3377 
3378   mdb = llmd_init(db->module);
3379   llmd_set_distinct(mdb);
3380   common_block_name = (char *)lldbg_alloc(strlen(name) + 1);
3381   pname = name;
3382   pmname = common_block_name;
3383   while (*pname != '\0') {
3384     *pmname = tolower(*pname);
3385     pname++;
3386     pmname++;
3387   }
3388   *pmname = '\0'; /* append null char to end of string */
3389 
3390   // Use the DICommonBlock template
3391   llmd_set_class(mdb, LL_DICommonBlock);
3392   llmd_add_md(mdb, scope);                 // scope
3393   llmd_add_md(mdb, decl);                  // declaration
3394   llmd_add_string(mdb, common_block_name); // name
3395   return llmd_finish(mdb);
3396 }
3397 
3398 LL_MDRef
lldbg_emit_common_block_mdnode(LL_DebugInfo * db,SPTR sptr)3399 lldbg_emit_common_block_mdnode(LL_DebugInfo *db, SPTR sptr)
3400 {
3401   LL_MDRef scope_modnode, cmnblk_mdnode, cmnblk_gv_mdnode;
3402   SPTR scope = SCOPEG(sptr), var;
3403   const char *cmnblk_name = new_debug_name(SYMNAME(scope), SYMNAME(sptr), NULL);
3404   LL_MDNode *node;
3405   unsigned slot;
3406 
3407   cmnblk_mdnode = ll_get_module_debug(db->module->common_debug_map, cmnblk_name);
3408   if (!LL_MDREF_IS_NULL(cmnblk_mdnode))
3409     return cmnblk_mdnode;
3410   scope_modnode = db->cur_subprogram_mdnode
3411                       ? db->cur_subprogram_mdnode
3412                       : lldbg_emit_module_mdnode(db, scope);
3413   cmnblk_mdnode = lldbg_create_common_block_mdnode(
3414       db, scope_modnode, ll_get_md_null(), SYMNAME(sptr));
3415   db->cur_cmnblk_mdnode = cmnblk_mdnode;
3416   cmnblk_gv_mdnode = lldbg_create_cmblk_gv_mdnode(db, cmnblk_mdnode, sptr);
3417   slot = LL_MDREF_value(cmnblk_gv_mdnode) - 1;
3418   node = db->module->mdnodes[slot];
3419   cmnblk_gv_mdnode = node->elem[0];
3420   ll_update_md_node(db->module, cmnblk_mdnode, 1, cmnblk_gv_mdnode);
3421   ll_add_module_debug(db->module->common_debug_map, cmnblk_name, cmnblk_mdnode);
3422   if (db->cur_subprogram_mdnode)
3423     add_debug_cmnblk_variables(db, sptr);
3424   db->cur_cmnblk_mdnode = (LL_MDRef)0;
3425   return cmnblk_mdnode;
3426 }
3427 
3428 void
lldbg_add_pending_import_entity(LL_DebugInfo * db,SPTR entity,IMPORT_TYPE entity_type)3429 lldbg_add_pending_import_entity(LL_DebugInfo *db, SPTR entity, IMPORT_TYPE entity_type)
3430 {
3431   import_entity *node_ptr, *new_node;
3432 
3433   if (db->import_entity_list) {
3434     if (db->import_entity_list->func != gbl.currsub) {
3435       db->import_entity_list = NULL;
3436     } else {
3437       node_ptr = db->import_entity_list;
3438       while (node_ptr) {
3439         if (node_ptr->entity == entity)
3440           return;
3441         node_ptr = node_ptr->next;
3442       }
3443     }
3444   }
3445   new_node = (import_entity *)lldbg_alloc(sizeof *new_node);
3446   new_node->entity = entity;
3447   new_node->entity_type = entity_type;
3448   new_node->func = gbl.currsub;
3449   new_node->next = db->import_entity_list;
3450   db->import_entity_list = new_node;
3451 }
3452 
3453 const char*
new_debug_name(const char * str1,const char * str2,const char * str3)3454 new_debug_name(const char *str1, const char *str2, const char *str3)
3455 {
3456   int size;
3457   char *new_name;
3458   const char *sep = "/";
3459 
3460   if (!str1 || !str2)
3461     return NULL;
3462   if (str3) {
3463     size = strlen(str1) + strlen(str2) + strlen(str3) + 3;
3464   } else {
3465     size = strlen(str1) + strlen(str2) + 2;
3466   }
3467   new_name = (char *)lldbg_alloc(size);
3468   strcpy(new_name, str1);
3469   strcat(new_name, sep);
3470   strcat(new_name, str2);
3471   if (str3) {
3472     strcat(new_name, sep);
3473     strcat(new_name, str3);
3474   }
3475   return (const char *)new_name;
3476 }
3477 
3478