re PR debug/66691 (ICE on valid code at -O3 with -g enabled in simplify_subreg, at...
[gcc.git] / gcc / gdbhooks.py
index 3afa7961feb1ea43f4a9c96818299593f063f795..3a62a2d8acbe01179d3852837449d0cd714f2bb2 100644 (file)
@@ -1,5 +1,5 @@
 # Python hooks for gdb for debugging GCC
-# Copyright (C) 2013 Free Software Foundation, Inc.
+# Copyright (C) 2013-2015 Free Software Foundation, Inc.
 
 # Contributed by David Malcolm <dmalcolm@redhat.com>
 
@@ -109,8 +109,30 @@ available:
   1594   execute_pass_list (g->get_passes ()->all_passes);
   (gdb) p node
   $1 = <cgraph_node* 0x7ffff0312720 "foo">
+
+vec<> pointers are printed as the address followed by the elements in
+braces.  Here's a length 2 vec:
+  (gdb) p bb->preds
+  $18 = 0x7ffff0428b68 = {<edge 0x7ffff044d380 (3 -> 5)>, <edge 0x7ffff044d3b8 (4 -> 5)>}
+
+and here's a length 1 vec:
+  (gdb) p bb->succs
+  $19 = 0x7ffff0428bb8 = {<edge 0x7ffff044d3f0 (5 -> EXIT)>}
+
+You cannot yet use array notation [] to access the elements within the
+vector: attempting to do so instead gives you the vec itself (for vec[0]),
+or a (probably) invalid cast to vec<> for the memory after the vec (for
+vec[1] onwards).
+
+Instead (for now) you must access m_vecdata:
+  (gdb) p bb->preds->m_vecdata[0]
+  $20 = <edge 0x7ffff044d380 (3 -> 5)>
+  (gdb) p bb->preds->m_vecdata[1]
+  $21 = <edge 0x7ffff044d3b8 (4 -> 5)>
 """
+import os.path
 import re
+import sys
 
 import gdb
 import gdb.printing
@@ -128,6 +150,12 @@ tree_code_class_dict = gdb.types.make_enum_dict(gdb.lookup_type('enum tree_code_
 tcc_type = tree_code_class_dict['tcc_type']
 tcc_declaration = tree_code_class_dict['tcc_declaration']
 
+# Python3 has int() with arbitrary precision (bignum).  Python2 int() is 32-bit
+# on 32-bit hosts but remote targets may have 64-bit pointers there; Python2
+# long() is always 64-bit but Python3 no longer has anything named long.
+def intptr(gdbval):
+    return long(gdbval) if sys.version_info.major == 2 else int(gdbval)
+
 class Tree:
     """
     Wrapper around a gdb.Value for a tree, with various methods
@@ -137,7 +165,7 @@ class Tree:
         self.gdbval = gdbval
 
     def is_nonnull(self):
-        return long(self.gdbval)
+        return intptr(self.gdbval)
 
     def TREE_CODE(self):
         """
@@ -176,7 +204,7 @@ class TreePrinter:
         # like gcc/print-tree.c:print_node_brief
         # #define TREE_CODE(NODE) ((enum tree_code) (NODE)->base.code)
         # tree_code_name[(int) TREE_CODE (node)])
-        if long(self.gdbval) == 0:
+        if intptr(self.gdbval) == 0:
             return '<tree 0x0>'
 
         val_TREE_CODE = self.node.TREE_CODE()
@@ -188,17 +216,17 @@ class TreePrinter:
         val_tclass = val_tree_code_type[val_TREE_CODE]
 
         val_tree_code_name = gdb.parse_and_eval('tree_code_name')
-        val_code_name = val_tree_code_name[long(val_TREE_CODE)]
-        #print val_code_name.string()
+        val_code_name = val_tree_code_name[intptr(val_TREE_CODE)]
+        #print(val_code_name.string())
 
-        result = '<%s 0x%x' % (val_code_name.string(), long(self.gdbval))
-        if long(val_tclass) == tcc_declaration:
+        result = '<%s 0x%x' % (val_code_name.string(), intptr(self.gdbval))
+        if intptr(val_tclass) == tcc_declaration:
             tree_DECL_NAME = self.node.DECL_NAME()
             if tree_DECL_NAME.is_nonnull():
                  result += ' %s' % tree_DECL_NAME.IDENTIFIER_POINTER()
             else:
                 pass # TODO: labels etc
-        elif long(val_tclass) == tcc_type:
+        elif intptr(val_tclass) == tcc_type:
             tree_TYPE_NAME = Tree(self.gdbval['type_common']['name'])
             if tree_TYPE_NAME.is_nonnull():
                 if tree_TYPE_NAME.TREE_CODE() == IDENTIFIER_NODE:
@@ -221,8 +249,8 @@ class CGraphNodePrinter:
         self.gdbval = gdbval
 
     def to_string (self):
-        result = '<cgraph_node* 0x%x' % long(self.gdbval)
-        if long(self.gdbval):
+        result = '<cgraph_node* 0x%x' % intptr(self.gdbval)
+        if intptr(self.gdbval):
             # symtab_node::name calls lang_hooks.decl_printable_name
             # default implementation (lhd_decl_printable_name) is:
             #    return IDENTIFIER_POINTER (DECL_NAME (decl));
@@ -231,6 +259,26 @@ class CGraphNodePrinter:
         result += '>'
         return result
 
+######################################################################
+# Dwarf DIE pretty-printers
+######################################################################
+
+class DWDieRefPrinter:
+    def __init__(self, gdbval):
+        self.gdbval = gdbval
+
+    def to_string (self):
+        if intptr(self.gdbval) == 0:
+            return '<dw_die_ref 0x0>'
+        result = '<dw_die_ref 0x%x' % intptr(self.gdbval)
+        result += ' %s' % self.gdbval['die_tag']
+        if intptr(self.gdbval['die_parent']) != 0:
+            result += ' <parent=0x%x %s>' % (intptr(self.gdbval['die_parent']),
+                                             self.gdbval['die_parent']['die_tag'])
+                                             
+        result += '>'
+        return result
+
 ######################################################################
 
 class GimplePrinter:
@@ -238,13 +286,13 @@ class GimplePrinter:
         self.gdbval = gdbval
 
     def to_string (self):
-        if long(self.gdbval) == 0:
+        if intptr(self.gdbval) == 0:
             return '<gimple 0x0>'
         val_gimple_code = self.gdbval['code']
         val_gimple_code_name = gdb.parse_and_eval('gimple_code_name')
-        val_code_name = val_gimple_code_name[long(val_gimple_code)]
+        val_code_name = val_gimple_code_name[intptr(val_gimple_code)]
         result = '<%s 0x%x' % (val_code_name.string(),
-                               long(self.gdbval))
+                               intptr(self.gdbval))
         result += '>'
         return result
 
@@ -265,9 +313,9 @@ class BasicBlockPrinter:
         self.gdbval = gdbval
 
     def to_string (self):
-        result = '<basic_block 0x%x' % long(self.gdbval)
-        if long(self.gdbval):
-            result += ' (%s)' % bb_index_to_str(long(self.gdbval['index']))
+        result = '<basic_block 0x%x' % intptr(self.gdbval)
+        if intptr(self.gdbval):
+            result += ' (%s)' % bb_index_to_str(intptr(self.gdbval['index']))
         result += '>'
         return result
 
@@ -276,10 +324,10 @@ class CfgEdgePrinter:
         self.gdbval = gdbval
 
     def to_string (self):
-        result = '<edge 0x%x' % long(self.gdbval)
-        if long(self.gdbval):
-            src = bb_index_to_str(long(self.gdbval['src']['index']))
-            dest = bb_index_to_str(long(self.gdbval['dest']['index']))
+        result = '<edge 0x%x' % intptr(self.gdbval)
+        if intptr(self.gdbval):
+            src = bb_index_to_str(intptr(self.gdbval['src']['index']))
+            dest = bb_index_to_str(intptr(self.gdbval['dest']['index']))
             result += ' (%s -> %s)' % (src, dest)
         result += '>'
         return result
@@ -295,7 +343,7 @@ class Rtx:
 
 def GET_RTX_LENGTH(code):
     val_rtx_length = gdb.parse_and_eval('rtx_length')
-    return long(val_rtx_length[code])
+    return intptr(val_rtx_length[code])
 
 def GET_RTX_NAME(code):
     val_rtx_name = gdb.parse_and_eval('rtx_name')
@@ -318,17 +366,17 @@ class RtxPrinter:
         """
         # We use print_inline_rtx to avoid a trailing newline
         gdb.execute('call print_inline_rtx (stderr, (const_rtx) %s, 0)'
-                    % long(self.gdbval))
+                    % intptr(self.gdbval))
         return ''
 
         # or by hand; based on gcc/print-rtl.c:print_rtx
         result = ('<rtx_def 0x%x'
-                  % (long(self.gdbval)))
+                  % (intptr(self.gdbval)))
         code = self.rtx.GET_CODE()
         result += ' (%s' % GET_RTX_NAME(code)
         format_ = GET_RTX_FORMAT(code)
         for i in range(GET_RTX_LENGTH(code)):
-            print format_[i]
+            print(format_[i])
         result += ')>'
         return result
 
@@ -339,18 +387,41 @@ class PassPrinter:
         self.gdbval = gdbval
 
     def to_string (self):
-        result = '<opt_pass* 0x%x' % long(self.gdbval)
-        if long(self.gdbval):
+        result = '<opt_pass* 0x%x' % intptr(self.gdbval)
+        if intptr(self.gdbval):
             result += (' "%s"(%i)'
                        % (self.gdbval['name'].string(),
-                          long(self.gdbval['static_pass_number'])))
+                          intptr(self.gdbval['static_pass_number'])))
         result += '>'
         return result
 
 ######################################################################
 
+class VecPrinter:
+    #    -ex "up" -ex "p bb->preds"
+    def __init__(self, gdbval):
+        self.gdbval = gdbval
+
+    def display_hint (self):
+        return 'array'
+
+    def to_string (self):
+        # A trivial implementation; prettyprinting the contents is done
+        # by gdb calling the "children" method below.
+        return '0x%x' % intptr(self.gdbval)
+
+    def children (self):
+        if intptr(self.gdbval) == 0:
+            return
+        m_vecpfx = self.gdbval['m_vecpfx']
+        m_num = m_vecpfx['m_num']
+        m_vecdata = self.gdbval['m_vecdata']
+        for i in range(m_num):
+            yield ('[%d]' % i, m_vecdata[i])
+
+######################################################################
+
 # TODO:
-#   * vec
 #   * hashtab
 #   * location_t
 
@@ -411,7 +482,26 @@ def build_pretty_printer():
                              'tree', TreePrinter)
     pp.add_printer_for_types(['cgraph_node *'],
                              'cgraph_node', CGraphNodePrinter)
-    pp.add_printer_for_types(['gimple', 'gimple_statement_base *'],
+    pp.add_printer_for_types(['dw_die_ref'],
+                             'dw_die_ref', DWDieRefPrinter)
+    pp.add_printer_for_types(['gimple', 'gimple_statement_base *',
+
+                              # Keep this in the same order as gimple.def:
+                              'gimple_cond', 'const_gimple_cond',
+                              'gimple_statement_cond *',
+                              'gimple_debug', 'const_gimple_debug',
+                              'gimple_statement_debug *',
+                              'gimple_label', 'const_gimple_label',
+                              'gimple_statement_label *',
+                              'gimple_switch', 'const_gimple_switch',
+                              'gimple_statement_switch *',
+                              'gimple_assign', 'const_gimple_assign',
+                              'gimple_statement_assign *',
+                              'gimple_bind', 'const_gimple_bind',
+                              'gimple_statement_bind *',
+                              'gimple_phi', 'const_gimple_phi',
+                              'gimple_statement_phi *'],
+
                              'gimple',
                              GimplePrinter)
     pp.add_printer_for_types(['basic_block', 'basic_block_def *'],
@@ -423,10 +513,80 @@ def build_pretty_printer():
     pp.add_printer_for_types(['rtx_def *'], 'rtx_def', RtxPrinter)
     pp.add_printer_for_types(['opt_pass *'], 'opt_pass', PassPrinter)
 
+    pp.add_printer_for_regex(r'vec<(\S+), (\S+), (\S+)> \*',
+                             'vec',
+                             VecPrinter)
+
     return pp
 
 gdb.printing.register_pretty_printer(
     gdb.current_objfile(),
     build_pretty_printer())
 
+def find_gcc_source_dir():
+    # Use location of global "g" to locate the source tree
+    sym_g = gdb.lookup_global_symbol('g')
+    path = sym_g.symtab.filename # e.g. '../../src/gcc/context.h'
+    srcdir = os.path.split(path)[0] # e.g. '../../src/gcc'
+    return srcdir
+
+class PassNames:
+    """Parse passes.def, gathering a list of pass class names"""
+    def __init__(self):
+        srcdir = find_gcc_source_dir()
+        self.names = []
+        with open(os.path.join(srcdir, 'passes.def')) as f:
+            for line in f:
+                m = re.match('\s*NEXT_PASS \((.+)\);', line)
+                if m:
+                    self.names.append(m.group(1))
+
+class BreakOnPass(gdb.Command):
+    """
+    A custom command for putting breakpoints on the execute hook of passes.
+    This is largely a workaround for issues with tab-completion in gdb when
+    setting breakpoints on methods on classes within anonymous namespaces.
+
+    Example of use: putting a breakpoint on "final"
+      (gdb) break-on-pass
+    Press <TAB>; it autocompletes to "pass_":
+      (gdb) break-on-pass pass_
+    Press <TAB>:
+      Display all 219 possibilities? (y or n)
+    Press "n"; then type "f":
+      (gdb) break-on-pass pass_f
+    Press <TAB> to autocomplete to pass classnames beginning with "pass_f":
+      pass_fast_rtl_dce              pass_fold_builtins
+      pass_feedback_split_functions  pass_forwprop
+      pass_final                     pass_fre
+      pass_fixup_cfg                 pass_free_cfg
+    Type "in<TAB>" to complete to "pass_final":
+      (gdb) break-on-pass pass_final
+    ...and hit <RETURN>:
+      Breakpoint 6 at 0x8396ba: file ../../src/gcc/final.c, line 4526.
+    ...and we have a breakpoint set; continue execution:
+      (gdb) cont
+      Continuing.
+      Breakpoint 6, (anonymous namespace)::pass_final::execute (this=0x17fb990) at ../../src/gcc/final.c:4526
+      4526       virtual unsigned int execute (function *) { return rest_of_handle_final (); }
+    """
+    def __init__(self):
+        gdb.Command.__init__(self, 'break-on-pass', gdb.COMMAND_BREAKPOINTS)
+        self.pass_names = None
+
+    def complete(self, text, word):
+        # Lazily load pass names:
+        if not self.pass_names:
+            self.pass_names = PassNames()
+
+        return [name
+                for name in sorted(self.pass_names.names)
+                if name.startswith(text)]
+
+    def invoke(self, arg, from_tty):
+        sym = '(anonymous namespace)::%s::execute' % arg
+        breakpoint = gdb.Breakpoint(sym)
+
+BreakOnPass()
+
 print('Successfully loaded GDB hooks for GCC')